groovy-1.8.6/0000755001501200150120000000000011715047076012401 5ustar miguelmiguelgroovy-1.8.6/.gradle/0000755001501200150120000000000011710531066013705 5ustar miguelmiguelgroovy-1.8.6/.gradle/1.0-milestone-6/0000755001501200150120000000000011710531412016336 5ustar miguelmiguelgroovy-1.8.6/.gradle/1.0-milestone-6/outputFileStates/0000755001501200150120000000000011710531412021662 5ustar miguelmiguelgroovy-1.8.6/.gradle/1.0-milestone-6/outputFileStates/cache.bin0000644001501200150120000004444011710535654023441 0ustar miguelmiguelDh.hEU 6~w0 &7HˏHP3ZRRsrjava.lang.Long;̏#Jvaluexrjava.lang.Number xpjA 3ZRRsrjava.lang.Long;̏#Jvaluexrjava.lang.Number xp*!groovy-1.8.6/.gradle/1.0-milestone-6/outputFileStates/cache.properties0000644001501200150120000000003611710531412025042 0ustar miguelmiguel#Fri Jan 27 09:52:01 CET 2012 groovy-1.8.6/.gradle/1.0-milestone-6/outputFileStates/cache.properties.lock0000644001501200150120000000000211710535672025776 0ustar miguelmiguelgroovy-1.8.6/.gradle/1.0-milestone-6/fileSnapshots/0000755001501200150120000000000011710531066021165 5ustar miguelmiguelgroovy-1.8.6/.gradle/1.0-milestone-6/fileSnapshots/cache.bin0000644001501200150120000332667411710535656022760 0ustar miguelmiguelDU 6~w0 |nHP1H2I3Kz4Lj5N<678>s3ZRRsrjava.lang.Long;̏#Jvaluexrjava.lang.Number xp Ukq-3ڬsrYorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileCollectionSnapshotImpl\{V7L snapshotstLjava/util/Map;xpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wx(q3srRorg.gradle.api.internal.changedetection.OutputFilesSnapshotter$OutputFilesSnapshot7RJL filesSnapshott@Lorg/gradle/api/internal/changedetection/FileCollectionSnapshot;L rootFileIdstLjava/util/Map;xpsrYorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileCollectionSnapshotImpl\{V7L snapshotsq~xpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxsq~?@ wx2Nk[3ڬsrYorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileCollectionSnapshotImpl\{V7L snapshotstLjava/util/Map;xpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wx(q3srRorg.gradle.api.internal.changedetection.OutputFilesSnapshotter$OutputFilesSnapshot7RJL filesSnapshott@Lorg/gradle/api/internal/changedetection/FileCollectionSnapshot;L rootFileIdstLjava/util/Map;xpsrYorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileCollectionSnapshotImpl\{V7L snapshotsq~xpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxsq~?@ wx2Nk[3ƬsrYorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileCollectionSnapshotImpl\{V7L snapshotstLjava/util/Map;xpsrjava.util.HashMap`F loadFactorI thresholdxp?@wHtO/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyResourceLoader.javasrOorg.gradle.api.internal.changedetection.DefaultFileSnapshotter$FileHashSnapshotc[hasht[Bxpur[BTxpefE æ՚tm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ConstructorMetaMethodSite.javasq~uq~ cj'M T th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMethodDoc.javasq~uq~ o:yƪOſtr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/ASTTransformationCollectorCodeVisitor.javasq~uq~ ESbsa>tD/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlParser.javasq~uq~ 'h%Δ X,HtP/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MissingClassException.javasq~uq~  pl'L/]th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/LongCachedClass.javasq~uq~ szG\,w*tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/TraversalHelper.javasq~uq~ g%1yLetd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/ProtectionStorage.javasq~uq~  E/+lZ, t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/RangeExpression.javasq~uq~ DO49^8@!tG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GrabResolver.javasq~uq~ QֻRGC#TtJ/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Commons.javasq~uq~ eSʠvۊGf8tV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/FullBinding.javasq~uq~ i00 [tq/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ClassMetaClassGetPropertySite.javasq~uq~ <=XOtUXti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v6/PluginDefaultGroovyMethods.javasq~uq~ 4l sb>Y~utG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyObject.javasq~uq~ ~WoʼQqL+tI/home/blackdrag/coding/groovy/18/src/main/groovy/model/PropertyModel.javasq~uq~ / ]ȇLia~1ht`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyAnnotationRef.javasq~uq~ eMݎD[%ntP/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovydoc.javasq~uq~ X)T\8X4'yj)stM/home/blackdrag/coding/groovy/18/src/main/groovy/servlet/TemplateServlet.javasq~uq~ Kis!I\t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/AntlrASTProcessSnippets.javasq~uq~ Fw|f7/-1!tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/StringCachedClass.javasq~uq~ 4_oev#tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/CodeVisitorSupport.javasq~uq~ tAWzFR.tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ReferenceManager.javasq~uq~ t Tdƥt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/TypeChooser.javasq~uq~ U%س@ stC/home/blackdrag/coding/groovy/18/src/main/groovy/text/Template.javasq~uq~ I!Ϫ,ѝWtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/ReadWriteLockASTTransformation.javasq~uq~ +:x2É\~-ht[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/OptimizerVisitor.javasq~uq~ 7Z׈:޵ʮntI/home/blackdrag/coding/groovy/18/src/main/groovy/xml/dom/DOMCategory.javasq~uq~ [8p0W̓d|tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AbstractASTTransformation.javasq~uq~ [EDU5K_Htw/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayPutAtMetaMethod.javasq~uq~ 78cKa "pRGt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/ClosureTriggerBinding.javasq~uq~ jGi!RĻgtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/PropertyChangeProxyTargetBinding.javasq~uq~ Bl+E2Ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/LRUCache.javasq~uq~ OВ#q`H5tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ConstructorMetaClassSite.javasq~uq~ uqp"}tQ/home/blackdrag/coding/groovy/18/src/main/groovy/time/DatumDependentDuration.javasq~uq~ pb,8yt]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/InnerClassVisitor.javasq~uq~ ˤRoJ2tL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/PackageScope.javasq~uq~ beӹChMT$\RtM/home/blackdrag/coding/groovy/18/src/main/groovy/model/DefaultTableModel.javasq~uq~ [7bH@D-t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/UnaryPlusExpression.javasq~uq~ auyE_Ntl/home/blackdrag/.gradle/caches/artifacts-4/antlr/antlr/c12498cf18507aa6433a94eb7d3e77d5/jars/antlr-2.7.7.jarsq~uq~ 5,RƥYedt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/parser/GroovyLexer.javasq~uq~ XC4BTHuU`:/t/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ant/ant-launcher/c12498cf18507aa6433a94eb7d3e77d5/jars/ant-launcher-1.8.2.jarsq~uq~ >9z Ttc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ElvisOperatorExpression.javasq~uq~ |s~tN >B{t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ReverseListIterator.javasq~uq~ f9-YvgtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Category.javasq~uq~ u cB0t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/AssertStatement.javasq~uq~ YsǠ \*t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/DummyClassGenerator.javasq~uq~  ǃIwֽ<= tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ProcessingUnit.javasq~uq~ '`]=^u*v.1`tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ListExpression.javasq~uq~ YWSj}l*tE/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlSlurper.javasq~uq~ X5ޅ /Kw[tJ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/PropertyReader.javasq~uq~ ny5+Sp?ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/DummyCallSite.javasq~uq~ ]b.9D~%msѲ tu/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayGetAtMetaMethod.javasq~uq~ ƜޖYv&th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/MethodCallerMultiAdapter.javasq~uq~ C$` f7i1+ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodeCollector.javasq~uq~ w`,hota/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/EnumCompletionVisitor.javasq~uq~ O tn~D(@tA/home/blackdrag/coding/groovy/18/src/main/groovy/grape/Grape.javasq~uq~ JgۍQ@Ct`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/NumberAwareComparator.javasq~uq~ R٨ tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/SourceBinding.javasq~uq~ `C4Kղ~ڞth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/TransformMetaMethod.javasq~uq~  24_WϺtg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/GroovyObjectWrapper.javasq~uq~ E8a_mltZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MetaClassHelper.javasq~uq~ >{>E!LtQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyBugError.javasq~uq~ i ~c*ǹV*extb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaCompilerFactory.javasq~uq~ x|y>'1tg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/LRUProtectionStorage.javasq~uq~ J YW܋pڋAtp/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.javasq~uq~ ` y2tr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayPutAtMetaMethod.javasq~uq~ ;:(S]tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/tools/GenericsUtils.javasq~uq~ 5?0D Cn tL/home/blackdrag/coding/groovy/18/src/main/groovy/lang/TrampolineClosure.javasq~uq~ Pj$շat]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/TryCatchStatement.javasq~uq~ L0ͮΜx'etB/home/blackdrag/coding/groovy/18/src/main/groovy/util/Factory.javasq~uq~ O= GUt_Qt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodePrinter.javasq~uq~ VJ 8]~_t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/parser/GroovyRecognizer.javasq~uq~ MmiuutU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/StringHelper.javasq~uq~  ^T q$tm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/IndexedPropertyASTTransformation.javasq~uq~ d;Tk5 ïr"z9tY/home/blackdrag/coding/groovy/18/src/main/groovy/lang/IllegalPropertyAccessException.javasq~uq~ tv/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/SourceTextNotAvailableException.javasq~uq~ E#SZYjQth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/NewStaticMetaMethod.javasq~uq~ M/JZptk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/BooleanCachedClass.javasq~uq~ |DO}gZptQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/FastArray.javasq~uq~ 1;m(*G|]t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/BytecodeExpression.javasq~uq~ (}G$Cn՗ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/DeclarationExpression.javasq~uq~ YZ'mltN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyInterceptable.javasq~uq~ 3 1k'ǏltO/home/blackdrag/coding/groovy/18/src/main/groovy/transform/IndexedProperty.javasq~uq~ [U+;(d"th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/AssertionRenderer.javasq~uq~ pUG DŏTtW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ParserPlugin.javasq~uq~ {|@fiPw~tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/VisitorAdapter.javasq~uq~  s9$tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaMethod.javasq~uq~ o9+_F-Rt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/FlushingStreamWriter.javasq~uq~ ) Iz/tI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ProxyMetaClass.javasq~uq~ d@4p9p\g+9wtW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/EnumVisitor.javasq~uq~  Pk?q6~'4t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/FileSystemCompiler.javasq~uq~ FXoA__Titc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassGeneratorException.javasq~uq~ Fu5Fu8tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/CompileTaskSupport.javasq~uq~ _h1BsHWqtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/GroovyASTTransformation.javasq~uq~ xW.pt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ReturnStatement.javasq~uq~ eNH8MtVYti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMetaMethod.javasq~uq~ I-8.^'u tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassGenerator.javasq~uq~ zJb l)V ڤti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter.javasq~uq~ Q˝Rctr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MissingMethodExceptionNoStack.javasq~uq~ _;J'gk2itD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClass.javasq~uq~ HjxP^tH/home/blackdrag/coding/groovy/18/src/main/groovy/xml/FactorySupport.javasq~uq~ #AJdN=t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BytecodeHelper.javasq~uq~  T3a] 0tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/RootLoaderRef.javasq~uq~ s_~WGKr@t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaCompiler.javasq~uq~ Qb0m*e܇tQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/Phases.javasq~uq~ {zAm%0tU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/NullObject.javasq~uq~ j>CߓV1yt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/JavaTokenTypes.javasq~uq~ ; *#BtK/home/blackdrag/coding/groovy/18/src/main/groovy/io/PlatformLineWriter.javasq~uq~ gOC&gtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/MultipleCompilationErrorsException.javasq~uq~ W %~3oyDti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoInterceptableSite.javasq~uq~ M.O1ftQ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/DefaultPropertyReader.javasq~uq~ #(ѡ5}.WR@tW/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadMapEvaluatingException.javasq~uq~ ʻQSKޠ>ltg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.javasq~uq~ 5:t yX`tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/TriggerBinding.javasq~uq~ Q)*?͘tO/home/blackdrag/coding/groovy/18/src/main/groovy/text/SimpleTemplateEngine.javasq~uq~ юAI[ЌzȐ&Y6 tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/EmptyStatement.javasq~uq~ ή d(A㾺3td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/ExceptionMessage.javasq~uq~ E vt+۔WÚPftg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.javasq~uq~ lfGL)'Ht`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BytecodeVariable.javasq~uq~ `Jb{tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/PackageScopeASTTransformation.javasq~uq~ ìt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ConversionHandler.javasq~uq~ %Q+%t^/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/FilteredNodeChildren.javasq~uq~ x$!Ϗ5YHDs tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.javasq~uq~ PN?CNw9?t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/URLReaderSource.javasq~uq~ @UQo˳t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/Value.javasq~uq~ 9,Ѯ lS]'ztJ/home/blackdrag/coding/groovy/18/src/main/groovy/util/ScriptException.javasq~uq~ _ߤn `tI/home/blackdrag/coding/groovy/18/src/main/groovy/text/TemplateEngine.javasq~uq~ 2p.uldtO/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayoutRow.javasq~uq~ _3j0sqM/t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/InterfaceHelperClassNode.javasq~uq~ ,u itY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ManagedLinkedList.javasq~uq~ V)`11syotb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.javasq~uq~ HY?D{SeF;tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyException.javasq~uq~  NdyK_s[4b_htQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Numbers.javasq~uq~ }rs^;tH/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Slf4j.javasq~uq~ R(/ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultMethodKey.javasq~uq~ Ȃ|E*r: ht[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/SqlGroovyMethods.javasq~uq~ ({m'T?+tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ClassHelper.javasq~uq~ U}:\eጰt]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ContinueStatement.javasq~uq~ xI2\˧* ]t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DateGroovyMethods.javasq~uq~ ƿ0 i/ gtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/GenericsType.javasq~uq~ wx(Ų6ertF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ObjectRange.javasq~uq~ e&pe:jStV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/UberCompileTask.javasq~uq~ C+OR tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/ParserException.javasq~uq~ 9n;ݧ2jt@/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Range.javasq~uq~ }C>PXZtQ/home/blackdrag/coding/groovy/18/src/main/groovy/transform/EqualsAndHashCode.javasq~uq~ ;RM=Q|H\t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/BytecodeInstruction.javasq~uq~ |RqRp5tE/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaMethod.javasq~uq~ |ĭؑ7F:tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ComposedClosure.javasq~uq~ (&6jo`@2ItT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/VariableScope.javasq~uq~ A$bxzxNJVQ>tp/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassGetPropertySite.javasq~uq~ ~aEIt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/ClosureSourceBinding.javasq~uq~ *_.v(Utj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTemplateEngine.javasq~uq~ wn'z:`tL/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayout.javasq~uq~ ?=w֕l tM/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/Main.javasq~uq~ 'PjqJOUK@t_/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassRegistryChangeEventListener.javasq~uq~  wer31gtp/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-tree/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-tree-3.3.1.jarsq~uq~ ETs~tK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ClosureException.javasq~uq~ ̷ӿ0"tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/NewInstanceMetaMethod.javasq~uq~ P, j8ktU/home/blackdrag/coding/groovy/18/src/main/groovy/beans/VetoableASTTransformation.javasq~uq~ z6Ku@ADtj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.javasq~uq~ B`0QX#X:YVtO/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Types.javasq~uq~ 2aC_$M9tN/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovyc.javasq~uq~  .Zb>P.#te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassSite.javasq~uq~ .u]tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedClass.javasq~uq~ %$q"ڊ4tC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Writable.javasq~uq~ ,'#ݡTtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/NullWriter.javasq~uq~ 0o~ -8P,tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/CurriedClosure.javasq~uq~ HOzI k1tm/home/blackdrag/.gradle/caches/artifacts-4/jline/jline/c12498cf18507aa6433a94eb7d3e77d5/jars/jline-0.9.94.jarsq~uq~ F#\w o$qD7td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/DelegatingController.javasq~uq~ f!ٚϕ,@c,ext[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ConvertedClosure.javasq~uq~ YO1*UPTT5u/tB/home/blackdrag/coding/groovy/18/src/main/groovy/util/OrderBy.javasq~uq~ w9W"+MA{٩'GStN/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ASTNode.javasq~uq~ ȳYmwKTj_!t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/CharWrapper.javasq~uq~ d쵡tth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/AnnotationConstantExpression.javasq~uq~  H-̩,9tte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AbstractASTTransformUtil.javasq~uq~ Qmh#XBtO/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/Variable.javasq~uq~ wty8a&׆ctF/home/blackdrag/coding/groovy/18/src/main/groovy/util/NodePrinter.javasq~uq~ pwUK4;OtL/home/blackdrag/coding/groovy/18/src/main/groovy/util/ClosureComparator.javasq~uq~  .vS4m@t@/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Mixin.javasq~uq~ <&+rKdب7tU/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/GPathResult.javasq~uq~ =dy+Ati/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.javasq~uq~ ul/Jt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/LoopingStatement.javasq~uq~ 7jgdwt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/RuntimeParserException.javasq~uq~ GtfE/yF6jtL/home/blackdrag/coding/groovy/18/src/main/groovy/json/StringEscapeUtils.javasq~uq~ @1dccOQzKjtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/IntRange.javasq~uq~  .]8ѺC;tU/home/blackdrag/coding/groovy/18/src/main/groovy/beans/BindableASTTransformation.javasq~uq~ N"ӣR-nItV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyDoc.javasq~uq~ =0vY?7tG/home/blackdrag/coding/groovy/18/src/main/groovy/time/BaseDuration.javasq~uq~ ̵= +y!CtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ForStatement.javasq~uq~ 9ϑoHẂPAtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MethodSelectionException.javasq~uq~ !\h^'yYtK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ExpandoMetaClass.javasq~uq~ *,  tE/home/blackdrag/coding/groovy/18/src/main/groovy/sql/InParameter.javasq~uq~ 44WNwtI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyCallable.javasq~uq~ U+r'K@˜%tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/StaticTypesTransformation.javasq~uq~ D̏:hKO_tT/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JTableProperties.javasq~uq~ 7J>OBf8"t|/home/blackdrag/.gradle/caches/artifacts-4/commons-cli/commons-cli/c12498cf18507aa6433a94eb7d3e77d5/jars/commons-cli-1.2.jarsq~uq~ ܮ? 3;⌞tG/home/blackdrag/coding/groovy/18/src/main/groovy/sql/CallResultSet.javasq~uq~ L+n>D/ ltc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ConstructorSite.javasq~uq~ |tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/ObjectCachedClass.javasq~uq~ KU'([t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/FileReaderSource.javasq~uq~ j~RHtP/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayoutCell.javasq~uq~ ~E,L qt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.javasq~uq~ BJFg4N xt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/LoaderConfiguration.javasq~uq~ `'gp!t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ClosureExpression.javasq~uq~ uf1?WȧtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/RootLoader.javasq~uq~  D]1+.tO/home/blackdrag/coding/groovy/18/src/main/groovy/util/PermutationGenerator.javasq~uq~ zEOL΅lhtD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Singleton.javasq~uq~ ^p򷍎DtG/home/blackdrag/coding/groovy/18/src/main/groovy/grape/GrapeEngine.javasq~uq~ b!, cIyart[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/XmlGroovyMethods.javasq~uq~ /eP\wtA/home/blackdrag/coding/groovy/18/src/main/groovy/io/FileType.javasq~uq~ |\o>E=ztI/home/blackdrag/coding/groovy/18/src/main/groovy/util/ProxyGenerator.javasq~uq~ Yck=b׋tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ArrayUtil.javasq~uq~ F?v8{ btX/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JComponentProperties.javasq~uq~ GTskZvIftU/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JSliderProperties.javasq~uq~ 磙cH DGt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/GroovyCategorySupport.javasq~uq~ Xإˁktf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaAwareResolveVisitor.javasq~uq~ @-`|AxӤmw Xt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/UnaryMinusExpression.javasq~uq~ \$_>@tStv/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-commons/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-commons-3.3.1.jarsq~uq~ ] 1ؕ$otf/home/blackdrag/.gradle/caches/artifacts-4/asm/asm/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-3.3.1.jarsq~uq~ 蕓$$VBt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/InvocationWriter.javasq~uq~ \rvtC/home/blackdrag/coding/groovy/18/src/main/groovy/util/NodeList.javasq~uq~ !T 2!O\YC^t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/typehandling/LongMath.javasq~uq~ (NYJR߫OtV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ConstructorNode.javasq~uq~ ),DꬾfRv>tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MethodPointerExpression.javasq~uq~ hwe_p7Y%jtZ/home/blackdrag/coding/groovy/18/src/main/groovy/sql/BatchingPreparedStatementWrapper.javasq~uq~ mk9F' t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.javasq~uq~ A;ғeg:t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/AggregateBinding.javasq~uq~ nRbG6tL/home/blackdrag/coding/groovy/18/src/main/groovy/util/GroovyCollections.javasq~uq~ vأ(G iZ f@htr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ThreadManagedMetaBeanProperty.javasq~uq~ D.N%t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.javasq~uq~ n)xtA/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Script.javasq~uq~ <Ey꘷M6?@tF/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Log.javasq~uq~ J 'IuEt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilerConfiguration.javasq~uq~ LE v,tX/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadListEvaluatingException.javasq~uq~ jI:I0G݀ ItB/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Binding.javasq~uq~ Uz\1:tR/home/blackdrag/coding/groovy/18/src/main/groovy/transform/PackageScopeTarget.javasq~uq~ e[JO؈$]tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/SynchronizedASTTransformation.javasq~uq~  Ә0btF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Interceptor.javasq~uq~ ?)n#.KxNtG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovySystem.javasq~uq~ ߰ZG$&Ht@th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.javasq~uq~ 8S OSQQtD/home/blackdrag/coding/groovy/18/src/main/groovy/xml/SAXBuilder.javasq~uq~ ؍"Q':J&tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedField.javasq~uq~ T+\Ţ/tw/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayGetAtMetaMethod.javasq~uq~ `@V}KtK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaBeanProperty.javasq~uq~ ~;I THwkZty/home/blackdrag/.gradle/caches/artifacts-4/org.fusesource.jansi/jansi/c12498cf18507aa6433a94eb7d3e77d5/jars/jansi-1.7.jarsq~uq~ U7mߏoTZtb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/VariableSlotLoader.javasq~uq~ 8fm6=>ftX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/TokenException.javasq~uq~ S,d`=b\tV/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JSpinnerProperties.javasq~uq~ O[&\`tk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/typehandling/GroovyCastException.javasq~uq~  ,?gB %g=>tH/home/blackdrag/coding/groovy/18/src/main/groovy/lang/PropertyValue.javasq~uq~ EYg- &඿xtX/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JScrollBarProperties.javasq~uq~ B_[}֦At]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/TernaryExpression.javasq~uq~ nF<:LBdtR/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaArrayLengthProperty.javasq~uq~ OS|M$"xtG/home/blackdrag/coding/groovy/18/src/main/groovy/model/ValueHolder.javasq~uq~ K[)()bjte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.javasq~uq~ f\ ڊ! tG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaProperty.javasq~uq~ ]{-<⺘ItV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/DynamicVariable.javasq~uq~ m.ApЦ9tU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/DgmConverter.javasq~uq~ ZuF`*wOt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/ByteWrapper.javasq~uq~ [F)YCt첈 tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/StaticVerifier.javasq~uq~ Q݉v>ש^-e[Jt^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/EventTriggerBinding.javasq~uq~ ?g[tV?tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/FileSystemResourceManager.javasq~uq~ hh6Zv!tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/Memoize.javasq~uq~ coW7A3 a tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v5/TestNgUtils.javasq~uq~ E5tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/FileScanner.javasq~uq~ LSiQ艼tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassCompletionVerifier.javasq~uq~ N In+|ۗ tD/home/blackdrag/coding/groovy/18/src/main/groovy/json/JsonToken.javasq~uq~ q\+r@t4gږtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/CachedClosureClass.javasq~uq~ <&|VtR/home/blackdrag/coding/groovy/18/src/main/groovy/sql/GroovyResultSetExtension.javasq~uq~ z)HҕTtL/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyClassLoader.javasq~uq~ N ٩jYQY ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/MockOutputTool.javasq~uq~  `ɴRyu'tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/AnnotatedNode.javasq~uq~ nVSϒC>td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex.javasq~uq~ UŔ%5'1tJ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/PropertyWriter.javasq~uq~ Otx>Ͳ~ts/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayGetAtMetaMethod.javasq~uq~ DI)r9X3tX/home/blackdrag/coding/groovy/18/src/main/groovy/grape/GrabAnnotationTransformation.javasq~uq~ /UٱAtF3tS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/EnumHelper.javasq~uq~ srapM Ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyClassDoc.javasq~uq~ -wa<1ؐtY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/MopWriter.javasq~uq~ <;O4 55yth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v6/PluginStaticGroovyMethods.javasq~uq~ :/ehQeqtQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/MethodNode.javasq~uq~ SR4moLR\t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/AsmClassGenerator.javasq~uq~ ޾ndniti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.javasq~uq~ Q)Șkaxtl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap.javasq~uq~ *x١0W<_Ltb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.javasq~uq~ j()s9tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v7/Java7.javasq~uq~ 7ʊQUmoV^|tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/ClassLoaderForClassArtifacts.javasq~uq~ :Ҥ?f|tS/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeChild.javasq~uq~ Q2p]Y:tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaExpandoProperty.javasq~uq~  +Bs~o4ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/FloatCachedClass.javasq~uq~ F <,,FA6atF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GrabExclude.javasq~uq~ ?..΍%tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/DoubleKeyHashMap.javasq~uq~ V*-"&tT/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/Attributes.javasq~uq~ 240= utn/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.javasq~uq~ ~]sW4AπNtq/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ivy/ivy/c12498cf18507aa6433a94eb7d3e77d5/jars/ivy-2.2.0.jarsq~uq~ '9\wkh +tq/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ant/ant/c12498cf18507aa6433a94eb7d3e77d5/jars/ant-1.8.2.jarsq~uq~ cY@(PZzN t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/MutualPropertyBinding.javasq~uq~ (O/ާ/.Gtf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/CategoryASTTransformation.javasq~uq~ HT “M!dotJ/home/blackdrag/coding/groovy/18/src/main/groovy/io/GroovyPrintWriter.javasq~uq~ 2Jz6-x/utS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ListHashMap.javasq~uq~ Dp A@2tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/JavaLexer.javasq~uq~ ˯ԞRD#Eht]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/OutputTool.javasq~uq~ BlP2y[t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/Visitor.javasq~uq~ Lo!_tI/home/blackdrag/coding/groovy/18/src/main/groovy/transform/Canonical.javasq~uq~ _e VSte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/UnicodeLexerSharedInputState.javasq~uq~ bN:TTb'2'/>tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilePhase.javasq~uq~ )vy)RtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/Groovifier.javasq~uq~ ^QK*eFtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/NewifyASTTransformation.javasq~uq~ x꘮99np5te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.javasq~uq~ k"xi[Ư{6 %+tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyObjectSupport.javasq~uq~ _P;)ƢlotX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/GroovyCodeVisitor.javasq~uq~ ${ºg4+=o1tV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/ErrorReporter.javasq~uq~ f{g0/Vytg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyFieldDoc.javasq~uq~ x,>R R4ĄagtV/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeChildren.javasq~uq~ P=p Itg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.javasq~uq~ fP1:%tp/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-util/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-util-3.3.1.jarsq~uq~ &I73&ԙAQMtI/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlNodePrinter.javasq~uq~ L Jr~=td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus.javasq~uq~ Z~dL/mtj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/customizers/SecureASTCustomizer.javasq~uq~ E>~zy2Stb/home/blackdrag/coding/groovy/18/src/main/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder.javasq~uq~ U᧿e htk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/CallSiteAwareMetaMethod.javasq~uq~ -= jiSPte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilationFailedException.javasq~uq~ x_@ bjt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/TokenMismatchException.javasq~uq~  d#Ch(B6ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.javasq~uq~ xr'wtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/ReaderSource.javasq~uq~ `aX%r(y?RyZtl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryObjectExpressionHelper.javasq~uq~ ىp7s'uRM te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ConstructorCallExpression.javasq~uq~ >w9P݌tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/LocatedMessage.javasq~uq~ Tg#U](""nbtW/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassRegistryChangeEvent.javasq~uq~ jXwk%MP\StT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MethodKey.javasq~uq~ fy=9j69Vt/home/blackdrag/.gradle/caches/artifacts-4/com.thoughtworks.xstream/xstream/c12498cf18507aa6433a94eb7d3e77d5/jars/xstream-1.4.1.jarsq~uq~ 1N-Iᴯ@w`it\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ExtendedVerifier.javasq~uq~ AuBzD>t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/PropertyExpression.javasq~uq~ goZ,RLRp#tN/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/Node.javasq~uq~ 剄SyA.6-t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/FileSystemCompilerFacade.javasq~uq~ 4Py(PJtQ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/DefaultPropertyWriter.javasq~uq~ 1P RUZtx/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-analysis/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-analysis-3.3.1.jarsq~uq~ n{&putP/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/ClosureRenderer.javasq~uq~ -D0)Wx0ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/ExternalGroovyClassDoc.javasq~uq~ +SxlKH"BtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Reduction.javasq~uq~ VJnC|jԴptK/home/blackdrag/coding/groovy/18/src/main/groovy/servlet/GroovyServlet.javasq~uq~ Z3a<|@y0>%tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ThrowStatement.javasq~uq~ [ 1rB+Xӕ\tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/xml/DomToGroovy.javasq~uq~ NL{gf|tP/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MissingFieldException.javasq~uq~ +%,HKtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryFloatExpressionHelper.javasq~uq~ p=9֑ӏtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Sequence.javasq~uq~ DqZ"`Jpҷtg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.javasq~uq~ H $$bڼ{`|1t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedConstructor.javasq~uq~ fťLNti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/FlatNodeListTraversal.javasq~uq~  S $B=v th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader.javasq~uq~ gT<LPt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ArrayExpression.javasq~uq~ U/t J)tQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/Reference.javasq~uq~ N S#` tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/DelegatingMetaClass.javasq~uq~ L< Q螥CtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/CastExpression.javasq~uq~ =oeQgV8tS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/Finalizable.javasq~uq~ >եF PXtf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/SyntaxErrorMessage.javasq~uq~ ~g0Ja`۸Ktu/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayPutAtMetaMethod.javasq~uq~  UPݲq_r tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/Logger.javasq~uq~ ѣu1NMRtn/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayPutAtMetaMethod.javasq~uq~ R_T8etf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit.javasq~uq~ 6s MAЮ3ۖtT/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NoChildren.javasq~uq~ $i jإst\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/PrefixExpression.javasq~uq~ /id5P6td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/AbstractCallSite.javasq~uq~ 0EE!QkgK6渫t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/GeneratedClosure.javasq~uq~ ڻHh~dt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyExceptionInterface.javasq~uq~ LY'Ipta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/SourceText.javasq~uq~ K:_'ѕ[۝te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodeAsHTMLPrinter.javasq~uq~ 2aU;:煪t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.javasq~uq~ p<7ɐBtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/CharacterCachedClass.javasq~uq~ >msڗ3itX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/GenerateStubsTask.javasq~uq~ ,Oj2?%O zt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/MemoizeCache.javasq~uq~ n%@^DEStj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryLongExpressionHelper.javasq~uq~ 3A)tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/GroovySourceToken.javasq~uq~ ua/G'HŌtY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/CaseStatement.javasq~uq~ >x CY`tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MapExpression.javasq~uq~ Eg6 'JH tg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AutoCloneASTTransformation.javasq~uq~ M'rIaf#_tI/home/blackdrag/coding/groovy/18/src/main/groovy/sql/GroovyResultSet.javasq~uq~ 0%ZBM2h$Xta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/FileOutputTool.javasq~uq~ D=E%)J{ t@/home/blackdrag/coding/groovy/18/src/main/groovy/util/Proxy.javasq~uq~ y S -tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/LazyASTTransformation.javasq~uq~ FM#$ީt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MethodCallExpression.javasq~uq~ -Hm CtN/home/blackdrag/coding/groovy/18/src/main/groovy/inspect/swingui/TableMap.javasq~uq~ )W]\)ܓΝtq/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MissingMethodExecutionFailed.javasq~uq~ o_1 tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/CompileUnit.javasq~uq~ q~& p$tt/home/blackdrag/.gradle/caches/artifacts-4/xmlpull/xmlpull/c12498cf18507aa6433a94eb7d3e77d5/jars/xmlpull-1.1.3.1.jarsq~uq~ WrrP4"t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/OperandStack.javasq~uq~ KJԨooOtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/LineColumn.javasq~uq~ +X lū-tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/StackTraceUtils.javasq~uq~ = P&[ 4.ltH/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassImpl.javasq~uq~ 2_&dtI/home/blackdrag/coding/groovy/18/src/main/groovy/io/LineColumnReader.javasq~uq~ $P\Q7K>OtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedMethod.javasq~uq~ < A[:ntc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/stc/UnionTypeClassNode.javasq~uq~ L=KɵtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MethodClosure.javasq~uq~ k7V6.4ntr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayGetAtMetaMethod.javasq~uq~ E҈SvI AtL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/Synchronized.javasq~uq~ c^9yUtO/home/blackdrag/coding/groovy/18/src/main/groovy/lang/BenchmarkInterceptor.javasq~uq~ caF'`7}ڛt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavacJavaCompiler.javasq~uq~ 9eʁfltH/home/blackdrag/coding/groovy/18/src/main/groovy/util/IndentPrinter.javasq~uq~ |U&=5zte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/PreOrderTraversal.javasq~uq~ ,[d0tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite.javasq~uq~ 91qtC/home/blackdrag/coding/groovy/18/src/main/groovy/time/Duration.javasq~uq~ ΉS ɩjt`JtB/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Closure.javasq~uq~  πn]88 tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ReturnAdder.javasq~uq~ J*&c~BP!D\tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ClassExtender.javasq~uq~ aѤu..(ktL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/WithReadLock.javasq~uq~ Gg'gq[rta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ExpressionTransformer.javasq~uq~ fꛥ#DEtV/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeIterator.javasq~uq~  އ|].xAtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ReflectorLoader.javasq~uq~ ^M`q6w!tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/NumberCachedClass.javasq~uq~ ݇5r#ktP/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/FieldNode.javasq~uq~ @\Q"mt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.javasq~uq~ cms",q tf/home/blackdrag/coding/groovy/18/src/main/groovy/xml/streamingmarkupsupport/StreamingMarkupWriter.javasq~uq~ 'ރqh%tI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MapWithDefault.javasq~uq~ /h'tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/SimpleCompletor.javasq~uq~ Y:_}|&紅t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.javasq~uq~ Ոiɮ$ӢdtH/home/blackdrag/coding/groovy/18/src/main/groovy/io/FileVisitResult.javasq~uq~ +>9!t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/EmptyExpression.javasq~uq~ m`;<%Ytm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePogoFieldSite.javasq~uq~ 1}%jwvGtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyConstructorDoc.javasq~uq~  u]e\=ntM/home/blackdrag/coding/groovy/18/src/main/groovy/transform/WithWriteLock.javasq~uq~ xQM~pt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/ASTParserException.javasq~uq~ ͡p ^:mu3tt/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayPutAtMetaMethod.javasq~uq~ epk 9HQ[tY/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/ReplacementNode.javasq~uq~ HA1d ~̇+tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyExecutableMemberDoc.javasq~uq~ h7=Y ' dtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ASTTransformationsContext.javasq~uq~  eL]tE/home/blackdrag/coding/groovy/18/src/main/groovy/lang/EmptyRange.javasq~uq~ Qז:T#A%tD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadMap.javasq~uq~ ;$h  /ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayMetaMethod.javasq~uq~ t.E op_stM/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovy.javasq~uq~ fPQUSLXdtM/home/blackdrag/coding/groovy/18/src/main/groovy/xml/MarkupBuilderHelper.javasq~uq~ ||aJktZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/BreakStatement.javasq~uq~ >p#8`{t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/StaticImportVisitor.javasq~uq~  }.Ut]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/ReflectionUtils.javasq~uq~ n@OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$985.classsq~ uq~ Ha[BR od9t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayPutAtMetaMethod.classsq~ uq~ Qw+ZVrQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$100.classsq~ uq~ ƲhhnAitc/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredAttributes.classsq~ uq~ ` gh*mt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/JavaLexer.classsq~ uq~ }p}OiB҄to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite.classsq~ uq~ 5X-͵ء! ;tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$8.classsq~ uq~ tg~wanaL94tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMapBase$Segment.classsq~ uq~ ՖxP>HѩCt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GroovyCodeVisitor.classsq~ uq~ pw鹒W&a^Qtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$1.classsq~ uq~ G#N-?aOt`/home/blackdrag/coding/groovy/18/target/classes/groovy/security/GroovyCodeSourcePermission.classsq~ uq~ PKcTR1 tN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaProperty.classsq~ uq~ *s otT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/GroovyServlet$1.classsq~ uq~ %ɘntr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ReadWriteLockASTTransformation.classsq~ uq~ 7x"뺈1O tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AntBuilderLocator.classsq~ uq~ o&A~4/tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$DoubleInteger.classsq~ uq~ oWw.'6Xtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LazyClassLoaderRef.classsq~ uq~ {4◆30(Ltm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.classsq~ uq~ ͂~[z{!tc/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$CreatePreparedStatementCommand.classsq~ uq~ /&E?x֯t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ X(,N5sh̿@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$73.classsq~ uq~ #CV*vltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$327.classsq~ uq~ U&zd ~4ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap$Entry.classsq~ uq~ F2#̜Ht_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSpinnerValueBinding.classsq~ uq~ Ԏ[zy"tX/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$1.classsq~ uq~ kո =O;R ktu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongFloat.classsq~ uq~ G2'4f!etN/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/MarkupBuilder.classsq~ uq~ e41jmJ/vFta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ListExpression.classsq~ uq~ ȃ٥R3`StHtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AutoCloneASTTransformation$1.classsq~ uq~ F꽿[gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$658.classsq~ uq~ -!+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$997.classsq~ uq~ "Ow4td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementClearedEvent.classsq~ uq~  RH=bGEata/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/BatchingPreparedStatementWrapper.classsq~ uq~ ͺ՞"*ʜt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$4.classsq~ uq~ ꥁ/ |61tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$462.classsq~ uq~ MCAQctl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.classsq~ uq~ g g׽30,{$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$894.classsq~ uq~ s>eR|tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$ThreadedReferenceManager.classsq~ uq~ {Frtޙ]tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/messages/Message.classsq~ uq~ ClKG@ tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindingUpdatable.classsq~ uq~ e%ayFtM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodeBuilder.classsq~ uq~ ""_6dUtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$5.classsq~ uq~ JX؈VZcth5B tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$74.classsq~ uq~ .5fFlSt`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$3.classsq~ uq~ :w1М!ȓtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$210.classsq~ uq~ W-)D5Rtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/FileSystemCompiler$1.classsq~ uq~ Lj&tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/StringReaderSource.classsq~ uq~ $M:gV ZBәtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/IFileNameFinder.classsq~ uq~ ϭ-'fղg t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/IfStatement.classsq~ uq~ ^ak9VptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$794.classsq~ uq~  PT=UhMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$257.classsq~ uq~ U&KbE[t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/Java6.classsq~ uq~ &x`2 tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.classsq~ uq~ 6!U OaPtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AbstractASTTransformation.classsq~ uq~ YTmъQFdtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$208.classsq~ uq~ Lʷ̋XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$127.classsq~ uq~ E:M r6tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$28.classsq~ uq~ eovLzDF[0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$245.classsq~ uq~ oYȔ;%Ctv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$IntegerLong.classsq~ uq~ ISb>ڥptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$169.classsq~ uq~ >Y)!N<Qw tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleFloat.classsq~ uq~ 4B$tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePojoFieldSite.classsq~ uq~ 5cp*tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$4$1.classsq~ uq~ ^{* n$ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.classsq~ uq~ +2& HAF#^ixtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$146.classsq~ uq~ `+R[/gt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/SyntaxException.classsq~ uq~ ߋV\>WXEz@tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite.classsq~ uq~ M&"!td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$PropertyRemovedEvent.classsq~ uq~ u>Ӵ.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$554.classsq~ uq~ K?cC&*P"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/Phases.classsq~ uq~  ĘkoVhtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$517.classsq~ uq~ W†`cIkPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$736.classsq~ uq~ IQBNRytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$503.classsq~ uq~ }4#4,6>outh/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod.classsq~ uq~ Kӽj@ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ArgumentListExpression.classsq~ uq~ \8p;B t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask.classsq~ uq~ `%,N'lt{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$PrimaryClassNodeOperation.classsq~ uq~ 꺎-G$krta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$1.classsq~ uq~ .C\s!1tO/home/blackdrag/coding/groovy/18/target/classes/groovy/util/IndentPrinter.classsq~ uq~ 65Y_,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$988.classsq~ uq~   _k/W itY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$619.classsq~ uq~ E|32FZ!th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/AssertionWriter$1.classsq~ uq~ WNztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$106.classsq~ uq~ -{a gVtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/NullCallSite.classsq~ uq~ ܺӸK -WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$695.classsq~ uq~ .Ѣo3K?Z8+t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MopWriter.classsq~ uq~  V=#_t`Rtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewInstanceMetaMethod.classsq~ uq~ yjdtg_ -tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$36.classsq~ uq~ `0g,SOttz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerInteger.classsq~ uq~   Q#btX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$21.classsq~ uq~ Y oXٻKRAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$812.classsq~ uq~ P7qetZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/FileIterator.classsq~ uq~ ~54MPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$113.classsq~ uq~ 8nxUd窶yjQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$937.classsq~ uq~ WC 1NU#R3t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$11.classsq~ uq~ %8гz Sb^\tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply.classsq~ uq~ y\ :4tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/LRUCache.classsq~ uq~ MDptx t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrap.classsq~ uq~ _{҇@i%aWtL/home/blackdrag/coding/groovy/18/target/classes/groovy/time/Duration$1.classsq~ uq~ .SKIל8T3 t\/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSliderProperties.classsq~ uq~ 27[ot{ቩdt\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChild$1.classsq~ uq~ c -^];u[~ZtV/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/Main$1.classsq~ uq~ ƚ<ΣtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$912.classsq~ uq~ P.";tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$216.classsq~ uq~ (?ˢKߩwIth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods$1.classsq~ uq~ ZP+3p;J%7tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePogoFieldSite.classsq~ uq~ McㇸtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$683.classsq~ uq~ f֪;9QtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$485.classsq~ uq~ ˌe[&/vs-tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$4.classsq~ uq~ 'X{gEqt_/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$XmlWritable.classsq~ uq~ E˦\֟+5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$212.classsq~ uq~ ?ey},-XtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$8.classsq~ uq~ Qk $Fomti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/NumberMath.classsq~ uq~ F:X-Ztq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ObjectCachedClass.classsq~ uq~ H]5HNrtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassLoaderForClassArtifacts.classsq~ uq~ 'ǮPJvd1DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$523.classsq~ uq~ ŮhZ;Cta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$6.classsq~ uq~ ͯyRS&Åt_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$1.classsq~ uq~ > m~*0iM#>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$165.classsq~ uq~ 0BU.dtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/FastArray$1.classsq~ uq~ >gu$4vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$962.classsq~ uq~ ]}g 1h*+AtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$33.classsq~ uq~ ndOmKR-EtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$714.classsq~ uq~ ~A&ڹcE6tX/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/DefaultPropertyReader.classsq~ uq~ j+,\y6t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$ValueIterator.classsq~ uq~ wӌ|5Ld t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$4.classsq~ uq~ E8agdܝ]tc/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$ServletOutput$2.classsq~ uq~ !4tZ3tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LazyCachedClassRef.classsq~ uq~ zbc $tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeExpression$1.classsq~ uq~ l)ފ B:ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$699.classsq~ uq~ kӃyeO~t[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NoChildren.classsq~ uq~ }o./r\oqtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/AntProjectPropertiesDelegate.classsq~ uq~ {fYtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$407.classsq~ uq~ )`|`$*"5jtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/LongMath.classsq~ uq~ S[*v0ڵ#th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$4.classsq~ uq~ kuJJIﵻ5Vt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SqlGroovyMethods$ResultSetMetaDataIterator.classsq~ uq~ oTׁD92tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$404.classsq~ uq~ 8t9|P WWtT/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovy.classsq~ uq~ clUl*`K6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$191.classsq~ uq~  &f!Lt_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$2.classsq~ uq~ 2Y4uRYtCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$138.classsq~ uq~ s쏑񈢯cqtc/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$ServletOutput$1.classsq~ uq~ c}$kJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$572.classsq~ uq~ Ul16y~tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/PreJava2GroovyConverter.classsq~ uq~ ^LkIM_ VVtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$130.classsq~ uq~ #y\LC,LtN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GrabResolver.classsq~ uq~ yOJ$?J-tO/home/blackdrag/coding/groovy/18/target/classes/groovy/model/ClosureModel.classsq~ uq~ ckSoJst/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryCharExpressionHelper.classsq~ uq~ ѩu#m-oytZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1007.classsq~ uq~ :4ɝ \dt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/RegexSupport.classsq~ uq~ KR`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$615.classsq~ uq~ $F+ttj=tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/StaticMethodCallExpression.classsq~ uq~ 'l`;p otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$644.classsq~ uq~ bGO;dt\/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/VetoableASTTransformation.classsq~ uq~  У1x(VYtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.classsq~ uq~ }N3Bj)1tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OperandStack.classsq~ uq~ efh6.tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedDoubleKeyMap$EntryWithValue.classsq~ uq~ [ǂlދgxztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$652.classsq~ uq~ Tdj tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$916.classsq~ uq~ B.0Πn56tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$1$1.classsq~ uq~ ~iLnUd~%kQ?[t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/HasCleanup.classsq~ uq~ C׼ƄAބhtU/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoCloneStyle.classsq~ uq~ O/(OUeSaEc%vtn/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultIdentifierResolver.classsq~ uq~ >ӻ6Odtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongFloat.classsq~ uq~ P )\ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubGenerator$1.classsq~ uq~ 6 겡 Ǥ*gvtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ASTTransformationsContext.classsq~ uq~ ӳZӪp`t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/WritableFile.classsq~ uq~ ^z}Wit^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceBundle.classsq~ uq~ aTȹts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl$1.classsq~ uq~ \\ˣ_( 7<9ht_/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$XmlTemplate.classsq~ uq~ eɥHp>Wtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/PackageScopeASTTransformation.classsq~ uq~ M-c( c.} t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/GroovyStarter.classsq~ uq~ ctDZTB†tX/home/blackdrag/coding/groovy/18/target/classes/groovy/inspect/swingui/TableSorter.classsq~ uq~ I %Ib76It_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ClassExtender.classsq~ uq~ (f#htn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$2.classsq~ uq~ h_tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/Wrapper.classsq~ uq~ ޏWn, Y3ltX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$46.classsq~ uq~ f}nEv<-KQtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$LabelRange.classsq~ uq~ (C t_`a89tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$398.classsq~ uq~  }Tܷ+a|]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$247.classsq~ uq~ ]щl3>9]tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$ProgressCallback.classsq~ uq~ bo+uQ tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaClassSite.classsq~ uq~ ꪳTf})l~Ӵ; tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$634.classsq~ uq~ 鼙@*tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/LongWrapper.classsq~ uq~ @֗d{StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$465.classsq~ uq~ svH\J ɮC[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$317.classsq~ uq~ Y"QҪOPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$109.classsq~ uq~ CTzV}[ FZ::տtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$140.classsq~ uq~ ۧ閌1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$994.classsq~ uq~ ԇ?fzz`!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$385.classsq~ uq~ gL+Vē?tT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaObjectProtocol.classsq~ uq~ (?zlC_tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap.classsq~ uq~ 6_[utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$656.classsq~ uq~ ;lMrOptj/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$SubClassDefiningClosure.classsq~ uq~ =}7#[.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$809.classsq~ uq~ A֫|@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$982.classsq~ uq~ hm8 1^OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$301.classsq~ uq~ qjkEvntG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$21.classsq~ uq~ maQ~ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$767.classsq~ uq~ ֒jr^dte/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/Builder$Built.classsq~ uq~ CE]9n'tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableField.classsq~ uq~ 1}ťISXZzjRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$347.classsq~ uq~ jș(>G=tU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$1.classsq~ uq~ ۈH_]s tU/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyResultSetProxy.classsq~ uq~ m$>Uj &htY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$682.classsq~ uq~  o&nfB#t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryShortExpressionHelper.classsq~ uq~ r0*;E=WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$104.classsq~ uq~ 16W]]itG/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Mixin.classsq~ uq~ ҋAŸ1Dotj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/SimpleCompletor.classsq~ uq~ <[H ift_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/DoubleKeyHashMap.classsq~ uq~ mmC쵀vtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ContinueStatement.classsq~ uq~  3! <:!zϐtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$494.classsq~ uq~ W&g2^$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$194.classsq~ uq~  }>y# 91z@v~tT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/TemplateServlet.classsq~ uq~ TH933בO{]NtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$787.classsq~ uq~ !A;oG%Rtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$Pair.classsq~ uq~ gNx\gbOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$890.classsq~ uq~ _i◳`X0^ohwbtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ElvisOperatorExpression.classsq~ uq~ RM?_'T!Ztv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$GroovyClassOperation.classsq~ uq~ -äI8steڵMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$753.classsq~ uq~  b0O0oI.0tm/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/StreamingMarkupWriter.classsq~ uq~ ;=Ĝ݅'ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ClassGenerator.classsq~ uq~ "rGymcktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$746.classsq~ uq~ ,/HPϨDDFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$876.classsq~ uq~ T:ǰ&̯ytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$653.classsq~ uq~ QQ?}>ލtth/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$StaticDefiningClosure.classsq~ uq~ (qx@%xtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationFailedException.classsq~ uq~ zQ4š2(+/%tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MethodSelectionException.classsq~ uq~ rʛtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$87.classsq~ uq~ u^2MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$600.classsq~ uq~  ȉ4sQT8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$684.classsq~ uq~ 7agkqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$200.classsq~ uq~ eoE$g IAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$487.classsq~ uq~ ݻ>lg'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$533.classsq~ uq~ Wrc ObcCftj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSiteArray$1.classsq~ uq~ K/db{(y冽tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaCompiler.classsq~ uq~ cQ 8A%OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$524.classsq~ uq~ ; ^QYXi0tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/builder/AstBuilderTransformation.classsq~ uq~ V<3*>tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$91.classsq~ uq~ Ggv/! ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$745.classsq~ uq~ Sr`&M=stY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$185.classsq~ uq~ }WLֱN=3t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$PropertyEvent.classsq~ uq~ }`Bhtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/EnumConstantClassNode.classsq~ uq~ 4Pš C;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$397.classsq~ uq~  RȻر9ǟ9tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$2.classsq~ uq~ #q9DHtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$436.classsq~ uq~ HyVG i atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$921.classsq~ uq~ ~HѥtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$936.classsq~ uq~ ͒<$y|tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureTriggerBinding.classsq~ uq~ [n@em?Z|tM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log.classsq~ uq~ D]m1셃babd.tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LogASTTransformation$LoggingStrategy.classsq~ uq~ /3y;8qeth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/DeclarationExpression.classsq~ uq~ j#:]Z^te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassCodeVisitorSupport.classsq~ uq~ ok[ݳ@73|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$961.classsq~ uq~ &ؠ9'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$241.classsq~ uq~ P~ɜ?3[tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1024.classsq~ uq~ 9f~v|=vbt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$NormalMethodChooser.classsq~ uq~ .d5pzL˘ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$411.classsq~ uq~ 4¾uaChXtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite.classsq~ uq~ m̓PcWː,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$672.classsq~ uq~ `/[uEtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/AdaptingMetaClass.classsq~ uq~ ; *־wtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$181.classsq~ uq~ q6ˎBtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$218.classsq~ uq~ kF̚3gjhD!tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$2.classsq~ uq~ $&\mˏ1Hqt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference.classsq~ uq~ x?+;#yf7;tP/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoClone.classsq~ uq~  ;}&7 VctZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1050.classsq~ uq~ FA*tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$70.classsq~ uq~ 6gEn63&4#td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$2$1.classsq~ uq~ YHjѨU|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$439.classsq~ uq~ \<֥r5z\t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/LoggingHelper.classsq~ uq~ | ;LytR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$11.classsq~ uq~ 3piL8LB t~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/Memoize$SoftReferenceMemoizeFunction.classsq~ uq~ ҕh8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$899.classsq~ uq~ +m gts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor$1.classsq~ uq~ R2`ġ!NMhUsUte/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$GetMethodMetaProperty.classsq~ uq~ coPratt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$LongDouble.classsq~ uq~ ([㹲D]+tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$7.classsq~ uq~ v󼶦a~'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$349.classsq~ uq~ qjćkf2td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods.classsq~ uq~ _PT"4htb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap$1.classsq~ uq~  =dD!9tG/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Range.classsq~ uq~ "cvz#I-êtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$476.classsq~ uq~ cڑ+ ptT/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/Main.classsq~ uq~ f]?? tP/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyRowResult.classsq~ uq~ 4BOWltZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1032.classsq~ uq~ X~膷|tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1013.classsq~ uq~ ].-V!Z 3ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/BooleanWrapper.classsq~ uq~ ޶٣\!StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$725.classsq~ uq~ , -\3rto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor$LowerCaseClass.classsq~ uq~ 9e ˻}tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$57.classsq~ uq~ x .ɅȄ Y8tL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/EmptyRange.classsq~ uq~ W/FT5Uߩ%tV/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/impl/TableLayoutRow.classsq~ uq~ p(NhStY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$733.classsq~ uq~ "(f^MI))tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$387.classsq~ uq~ [[ <[ӘEFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$563.classsq~ uq~ A`P o:tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/EmptyExpression.classsq~ uq~ ~ވr@t1 1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$362.classsq~ uq~ Зcx۹)t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$HashIterator.classsq~ uq~ GElTskΨtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoInterceptableSite.classsq~ uq~ P0ԃ`}tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindingProxy$ModelBindingPropertyBinding.classsq~ uq~ >v1VتGt]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementEvent.classsq~ uq~ ^IW0P]h}tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap$EntryIterator.classsq~ uq~ w3^??pD3Bh"Wtg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredNodeChildren$2.classsq~ uq~ sU6RrݳtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$702.classsq~ uq~ :C=d9+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$187.classsq~ uq~ s?B@N`motY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$591.classsq~ uq~  uc ܗWE~)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$265.classsq~ uq~ `#䇿Xܿlta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/Memoize.classsq~ uq~ 3Ҳ5[Ni th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ConfigurationException.classsq~ uq~ #x/Fjffth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/DoubleWrapper.classsq~ uq~ 3U3wD tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/DefaultPropertyAccessor.classsq~ uq~ 4ЄȜk &Ctb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$NodeReference.classsq~ uq~ 6=ƚ BZft[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v4/Java4.classsq~ uq~ s<{t}i,tP/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MapWithDefault.classsq~ uq~ p PKq$Itk/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassRegistry$MetaClassCreationHandle.classsq~ uq~ WlW RDtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/JavaTokenTypes.classsq~ uq~ } tF/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Grab.classsq~ uq~ ƠTJ{tI/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString.classsq~ uq~ U(&t"Tt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/StringHelper.classsq~ uq~ pXe3{J߹RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$713.classsq~ uq~ bg [z9tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$2$1.classsq~ uq~ P7dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$128.classsq~ uq~ E6tNCltZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1003.classsq~ uq~ ޝŕojqAtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$DoubleDouble.classsq~ uq~ EO4PMtH/home/blackdrag/coding/groovy/18/target/classes/groovy/grape/Grape.classsq~ uq~ }Ȍ,zyOto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ByteCachedClass.classsq~ uq~ Bbءtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedMethod$1.classsq~ uq~ 3+Bo tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$616.classsq~ uq~ cȎZ"[e[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$180.classsq~ uq~ ˜j %iPty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer$ImportType.classsq~ uq~ cԓqjte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ReverseListIterator.classsq~ uq~ L;'~ et\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChild$2.classsq~ uq~ ?/ZF|vp 5tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$2.classsq~ uq~ `%[^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$363.classsq~ uq~ +''! l5Itq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader$1.classsq~ uq~ P6D엘?UtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1019.classsq~ uq~ vkLn&s c/tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$823.classsq~ uq~ gµ兼(tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyExecutableMemberDoc.classsq~ uq~ ǘcE[qN!atG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$23.classsq~ uq~ gR[cBGtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$697.classsq~ uq~ ݼ=Vփ)Z#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$454.classsq~ uq~ b^@ajMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$420.classsq~ uq~ n/u#u%t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/LabelVerifier.classsq~ uq~ 'Os{dtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/AssertStatement.classsq~ uq~ v E{ˢtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilerConfiguration.classsq~ uq~ =+UźmԲtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$880.classsq~ uq~ `gH5-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$449.classsq~ uq~ -}[hh0#XcFュtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongLong.classsq~ uq~ ֢2RUxJ&tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/MixinInMetaClass$1.classsq~ uq~ )~dimtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$PropertyFullBinding.classsq~ uq~ qqr& C:]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$744.classsq~ uq~ d!쉸`-jtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$33.classsq~ uq~ !o\׉tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$532.classsq~ uq~ us~<&7ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureTriggerBinding$1.classsq~ uq~  a\9tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$85.classsq~ uq~ jlLV86,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$220.classsq~ uq~ 1k1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$381.classsq~ uq~ Gn+^s btY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/VerifyClass.classsq~ uq~ kAj=s#HC4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$796.classsq~ uq~ C6+SetY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$703.classsq~ uq~ T4l$RZtP/home/blackdrag/coding/groovy/18/target/classes/groovy/io/LineColumnReader.classsq~ uq~  gLu)Ity/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationCollectorCodeVisitor.classsq~ uq~ S-a; 0;>}Ҏtt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$5.classsq~ uq~ G WV;Ry(%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$574.classsq~ uq~ ۪` zHr2t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/FactoryInterceptorMetaClass.classsq~ uq~ ,b_~ g0tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$6.classsq~ uq~ RۛM2prZo#>tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$4.classsq~ uq~ mu UotQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$932.classsq~ uq~ +sJ٘RkptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$447.classsq~ uq~ Tr*cktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$435.classsq~ uq~ s~aiphEts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$LongFloat.classsq~ uq~ CځPta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/BlockStatement.classsq~ uq~ ݋!-Vo`to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MethodCallerMultiAdapter.classsq~ uq~ [Mg?'$! te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BytecodeHelper.classsq~ uq~ vgTI xta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/CastExpression.classsq~ uq~ s}_I mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$195.classsq~ uq~ 7nzZ8[)tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Reduction.classsq~ uq~ Q(`:U*fvMto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.classsq~ uq~ O 9tT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$3.classsq~ uq~ Dg*pXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$448.classsq~ uq~ i@#&ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$335.classsq~ uq~ hp=B*`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$156.classsq~ uq~ iqd$ZEz2tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$4.classsq~ uq~ B$CDtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$841.classsq~ uq~ ֬ KEtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap$Segment.classsq~ uq~ t5ZV'yG7iwyvtW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ClosureInvokingMethod.classsq~ uq~ uyڄH׹5wtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$72.classsq~ uq~ 2/ev#tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ImportNode.classsq~ uq~ 13N^J6A.tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1008.classsq~ uq~ ;F 2UÚho tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/io/GroovyPrintStream.classsq~ uq~ sxo¾^x0{_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/FileScanner.classsq~ uq~ #_/VQ6tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyProgramElementDoc.classsq~ uq~ g2gĴtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$167.classsq~ uq~ {!,iԻ2̈́tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$316.classsq~ uq~ _*N&VA¬tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/PluginDefaultGroovyMethods.classsq~ uq~ $bb 9$/5t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding$EventTriggerFullBinding.classsq~ uq~ @ͫWdktZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1037.classsq~ uq~ AZ :b-e&tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaProperty.classsq~ uq~ +lR-*/;WCtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$CategoryMethod.classsq~ uq~ u5ǣF[>9~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$450.classsq~ uq~ 74qE~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$340.classsq~ uq~ G/"_9qtL/home/blackdrag/coding/groovy/18/target/classes/groovy/model/FormModel.classsq~ uq~ ;ű||dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$981.classsq~ uq~  uvP6B5 t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/Statement.classsq~ uq~ OWEwgy0bkVti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/VariableSlotLoader.classsq~ uq~ ӝ B B1[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$872.classsq~ uq~ [BPBҐ柺tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/NamespaceBuilder.classsq~ uq~ ^>@O #ǽtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/CategoryASTTransformation.classsq~ uq~ ,PEwtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaProperty$2.classsq~ uq~ ;!δyY>itm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$NullObject.classsq~ uq~ \Ьb8 Mt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v7/Java7.classsq~ uq~ =%&*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$114.classsq~ uq~ Dp#~[OKTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$622.classsq~ uq~ (,0rtN/home/blackdrag/coding/groovy/18/target/classes/groovy/time/TimeCategory.classsq~ uq~ 84+f)ԗ[4t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference$1.classsq~ uq~ EgP'Zc$tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyAnnotationRef.classsq~ uq~ %$NSLtJCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$150.classsq~ uq~  ~l4 ~N?ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewMetaMethod.classsq~ uq~ TŽ&l2YgtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyCodeSource$1.classsq~ uq~ V*4Rtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ExpressionStatement.classsq~ uq~ u~~R*=TtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$933.classsq~ uq~ T5t6Z 3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$879.classsq~ uq~ Vm9Rf?tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass$2.classsq~ uq~ ai3wP4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$315.classsq~ uq~ R]wFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$318.classsq~ uq~  IhOqk t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod$AnonymousMetaMethod.classsq~ uq~ p EUfktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$606.classsq~ uq~ 5w_. F¹ItX/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/NamespaceBuilderSupport.classsq~ uq~ pDn] ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatLong.classsq~ uq~ [)>N$ t[/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange$IntRangeIterator.classsq~ uq~ D/+kZw|m]>tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite.classsq~ uq~ 5]Ega~}b>ktn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedMethod$MyComparator.classsq~ uq~ #~ګENtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$1.classsq~ uq~ I֤ PhtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$13.classsq~ uq~ aOM^0RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$915.classsq~ uq~ &ܟ&HtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$735.classsq~ uq~ |[y-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$154.classsq~ uq~ I@"-xta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$3.classsq~ uq~ Iht`N t[/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$CreateStatementCommand.classsq~ uq~ Zb|ȩ_Â;h-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$663.classsq~ uq~ 80VntF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$6.classsq~ uq~ uJp6_H1ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$354.classsq~ uq~ a i "Rtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$2.classsq~ uq~ dmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$987.classsq~ uq~ ůeBvއ+{Ut]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyTag.classsq~ uq~ ^CwP(W0rt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ReturnAdder$1.classsq~ uq~ !ӑ8lvytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$640.classsq~ uq~ ]Ƽƚ};v2Vtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/DelegatingController.classsq~ uq~ %}=ވ^tS/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/Synchronized.classsq~ uq~ V¬pt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayGetAtMetaMethod.classsq~ uq~ ű@nôOJz1t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer$SecuringCodeVisitor.classsq~ uq~ Π,Ptr#ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/ResourceManager.classsq~ uq~ Q&1Ik&ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/messages/WarningMessage.classsq~ uq~ nIY@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$878.classsq~ uq~ bp/ratd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator.classsq~ uq~ &M*>>p tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$655.classsq~ uq~ B_а^d $tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.classsq~ uq~ (}$v:Wytt@/home/blackdrag/coding/groovy/18/target/classes/META-INF/dgminfosq~ uq~ dM$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$309.classsq~ uq~ ` B 2!wtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1018.classsq~ uq~ ^A3 K 8Mftf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$MixedInAccessor$2$1.classsq~ uq~ dgd}Ĥtr/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document.classsq~ uq~ ^IYLt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/gse/StringSetMap.classsq~ uq~ bcIsٛs4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$148.classsq~ uq~ .kqtpȄkta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/WhileStatement.classsq~ uq~  /QW:7Yt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$7.classsq~ uq~ Ȱ7۲VstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$906.classsq~ uq~ ؋f~L5b mtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavacCompilerFactory.classsq~ uq~ 9ݫ̗tW/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Node$3.classsq~ uq~ "y}a㡨utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$941.classsq~ uq~ o\c7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$153.classsq~ uq~ aLFEΗ&*ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$870.classsq~ uq~ o֐]%(gxtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$405.classsq~ uq~ 4Y6 I:ys{tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/PowerAssertionError.classsq~ uq~ -=W0mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$555.classsq~ uq~ A$ȟtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/NodeAsHTMLPrinter.classsq~ uq~ R+Nt{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerFloat.classsq~ uq~ Vki|ns tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$613.classsq~ uq~  ~ژ=Z+3GEt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass.classsq~ uq~ ߝ݃qtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$5.classsq~ uq~ (f .ʌ-WgEtK/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/Vetoable.classsq~ uq~ ]8|CHJᏙt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$10.classsq~ uq~ <ڐaoZ^%>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$772.classsq~ uq~  _۰.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$542.classsq~ uq~ S462'tk(vtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/BytecodeInterface8.classsq~ uq~ P{ɅWVCntg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/SwingTimerFullBinding.classsq~ uq~ Y(+*:_)&tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/PackageNode.classsq~ uq~ ?A/SA5)tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1042.classsq~ uq~ dK~zltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$628.classsq~ uq~ Iqԥtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeInstruction.classsq~ uq~ կ3קtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$120.classsq~ uq~ !ƝB&JUtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$HardRef.classsq~ uq~ *>4$UAP4i}n!ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap.classsq~ uq~ qe.$:jSo ptJ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodeList.classsq~ uq~ [)"Qw6`tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$PhantomRef.classsq~ uq~ )a*^thtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$620.classsq~ uq~ GzQ|׸rTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$685.classsq~ uq~ +גATtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$348.classsq~ uq~ rМ4[mt5(>tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$22.classsq~ uq~ 4=w]E4&t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/AnnotationNode.classsq~ uq~ d!-m./th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$5.classsq~ uq~ U05 Gd`1tX/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyRuntimeException.classsq~ uq~ N&m%w tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$681.classsq~ uq~ ",cPr/#t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList.classsq~ uq~ 7 zf9TS%!Y2#gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$294.classsq~ uq~ ޫ^W/ڋM{htf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/SingleKeyHashMap$Copier.classsq~ uq~ Eu{Ɇ'tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$4.classsq~ uq~ |q[S$MytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$428.classsq~ uq~ A!LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$414.classsq~ uq~ ]UjcN䷝Mits/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/MetaClassConstructorSite.classsq~ uq~ NY\et[/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ReadOnlyPropertyException.classsq~ uq~ ѦTrG+?-Z!0tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ThreadLocalMapHandler.classsq~ uq~ Sʉ<Dta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit.classsq~ uq~ y)af*X- ftH/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Grapes.classsq~ uq~ ǜEӔe&t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GStringImpl.classsq~ uq~ ]  L1Nɢto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMemberDoc.classsq~ uq~ ֋WV P! ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatFloat.classsq~ uq~ H:'j7X'tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyConstructorDoc.classsq~ uq~ 56H6Ӎ7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$774.classsq~ uq~ HGnQŅ t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/Groovifier.classsq~ uq~ 8,h-_yV?tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$5.classsq~ uq~ "J65`+٭`>%ɖtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$441.classsq~ uq~ +4_=%=&ltd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyPackageDoc.classsq~ uq~ d2Ђ=tB2k}tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LocalMap.classsq~ uq~ 6Ъ69|{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$509.classsq~ uq~ ܉@&8NCn*Itf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$ExpandoMetaProperty.classsq~ uq~ T$(;rH-~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$268.classsq~ uq~ Mz\C1tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/OptimizerVisitor.classsq~ uq~ |-&U%|tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableConstructor.classsq~ uq~ xX kyTtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1.classsq~ uq~ X!:tO/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/InOutParameter.classsq~ uq~ "Ur"Z.tU/home/blackdrag/coding/groovy/18/target/classes/groovy/model/DefaultTableColumn.classsq~ uq~ 6 }b7F6jti/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$ExpandoMetaConstructor.classsq~ uq~ 'g  S]]td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/URLReaderSource.classsq~ uq~ yEifȜfOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$931.classsq~ uq~ u5VIW %tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaClassGetPropertySite.classsq~ uq~ Δh^ʱ͋tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$47.classsq~ uq~ y?n鈮S\(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$234.classsq~ uq~ R'¯߳bj:AtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$27.classsq~ uq~ @M"M ;ZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$101.classsq~ uq~ bNVu>4,tutY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$897.classsq~ uq~ ȔqeO+ <Gth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/SourceText.classsq~ uq~ ,] .ց >r"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$704.classsq~ uq~ jvϘo<t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/LexerFrame$1.classsq~ uq~ !>ۨS\}ލ$tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$4.classsq~ uq~ +SI\ -(W>AtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$675.classsq~ uq~ W+~ڌOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$776.classsq~ uq~ J]3}`MtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$13.classsq~ uq~ zE-40b;_BrXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$431.classsq~ uq~ ^il/| >tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BitwiseNegationExpression.classsq~ uq~ 6LpT ᆎ9tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$453.classsq~ uq~ )0f LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$379.classsq~ uq~ tNJ7zHtr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/IntegerCachedClass.classsq~ uq~ `QB* P#3Iq3tL/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AntBuilder.classsq~ uq~ 26n,K/tT/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder.classsq~ uq~ G0t\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult.classsq~ uq~ o1?C`5Jstr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/UnlimitedConcurrentCache.classsq~ uq~ hqegN4 3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$768.classsq~ uq~  񷲟] ץte/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$SimpleTemplate.classsq~ uq~ e]&h<a_QEotT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/TracingInterceptor.classsq~ uq~ $#FQԪtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$136.classsq~ uq~ E\6 u0ngzt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ ~85$O[EtD/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql.classsq~ uq~ #/Q 4.tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$7$1.classsq~ uq~ [,tXErtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$111.classsq~ uq~ <ZіtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$888.classsq~ uq~ N/"E2Rtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods$ProcessRunner.classsq~ uq~ EK0y*!t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$3.classsq~ uq~ B-&Lqa0tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/NewifyASTTransformation.classsq~ uq~ U.C=tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractSyntheticBinding.classsq~ uq~ X2W/t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMetaMethod$NumberNumberCallSite.classsq~ uq~ .|kv7'Qtp/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ReflectionClassNameResolver.classsq~ uq~ EXOXn{td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MixinASTTransformation.classsq~ uq~ 4 JpptqWtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/ByteWrapper.classsq~ uq~ AU- ͡~`yth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ExpressionTransformer.classsq~ uq~ [>a,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$707.classsq~ uq~  8\$3Q14;ftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$709.classsq~ uq~ K?D!?tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$14.classsq~ uq~ ,0('tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$14.classsq~ uq~ G<($tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$7.classsq~ uq~ u,ss`"`%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$203.classsq~ uq~ F6d$8Eti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.classsq~ uq~ bz2H4xtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$871.classsq~ uq~ jZz tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$1.classsq~ uq~ YKviQ}񿣨TtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$824.classsq~ uq~ ˾GkAܣ+at`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/CurriedClosure.classsq~ uq~ 'O SR t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ 6ixFBF~utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$857.classsq~ uq~ Z"OlSktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$553.classsq~ uq~ $J𫰀 r-L#d?tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$62.classsq~ uq~ ɏrhEJL>tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaClassSite.classsq~ uq~ =B킍tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$612.classsq~ uq~ 5ZSCO; yta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/BreakStatement.classsq~ uq~ ĴlIDCEtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$56.classsq~ uq~ tSt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/NotExpression.classsq~ uq~ 6j}RL!-atK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClass.classsq~ uq~ _֥xk)Etg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/MutualPropertyBinding.classsq~ uq~ M`;Ɏ7ytS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ResourceException.classsq~ uq~  :y n[=,nta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v5/TestNgUtils.classsq~ uq~ {:EcÔjFtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap.classsq~ uq~ @ myrAIt_/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadListEvaluatingException.classsq~ uq~ ̿-C8ptR/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovySocketServer.classsq~ uq~ CJ^t!H$stc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/SunClassLoader.classsq~ uq~ 6'x]?N-TvrtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$391.classsq~ uq~ 4|Z4i2tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.classsq~ uq~ Lx;*Gʉ$tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/LexerFrame.classsq~ uq~ 5h?yF+M7kB"tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$2.classsq~ uq~ @;0Y!1SBt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer$StatementChecker.classsq~ uq~ >i._\-atp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassCompletionVisitor$1.classsq~ uq~ gB:)tZV tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrASTProcessSnippets.classsq~ uq~  6IͼRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$650.classsq~ uq~  kLTS)ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$559.classsq~ uq~ FR6ftG/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Proxy.classsq~ uq~ nGG[Betc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeSequence.classsq~ uq~ ZBV&Nm}}tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1010.classsq~ uq~ bTǢ g2vcxb( t[/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/CompilationUnitAware.classsq~ uq~ R*c+$ʗ-ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ThrowStatement.classsq~ uq~ pE`&{t%XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$510.classsq~ uq~ RiġCΨTT[tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMapBase$Entry.classsq~ uq~ {zjUx)etR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MutableMetaClass.classsq~ uq~ r1:%@D7el=tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$479.classsq~ uq~ 5gJ9l+tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/FileSystemCompiler.classsq~ uq~ Sj.QZ`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$759.classsq~ uq~ ^GMvG#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$161.classsq~ uq~ .&ֵiTeQ$t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NoChildren$1.classsq~ uq~ i^rn S.sRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$459.classsq~ uq~  o=V&ֵtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/FloatCachedClass.classsq~ uq~ MB)F\* "ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/EmptyStatement.classsq~ uq~ 2‰_t ¹ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$729.classsq~ uq~ Q0װybuvtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$26.classsq~ uq~ 6j"c1t~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$ClassNodeSkip.classsq~ uq~ {aN\?Dt~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$StatementMeta.classsq~ uq~ ,/Ki(k|WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$550.classsq~ uq~ Z"uU.XKcte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/FileReaderSource.classsq~ uq~ НS,NDýytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$410.classsq~ uq~ z{ ktU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaExpandoProperty.classsq~ uq~ \9)]U 3bttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$539.classsq~ uq~ "ʗ-w+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$264.classsq~ uq~  pw^n ;{{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$157.classsq~ uq~ `q,#tmUE {S0tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$2.classsq~ uq~ rC֩&tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/ASTHelper.classsq~ uq~ #8ynnʟzӲtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/io/GroovyPrintWriter.classsq~ uq~ e֛lˁth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrParserPluginFactory.classsq~ uq~ i]^`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$927.classsq~ uq~ LO O&eftZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1052.classsq~ uq~ Wj"FUdztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$728.classsq~ uq~ _MZ ;72tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$698.classsq~ uq~ S%+~a!D!-th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$1.classsq~ uq~ ',a%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$895.classsq~ uq~ Z);y?ˍtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$839.classsq~ uq~ q2$weZ@t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleDouble.classsq~ uq~ qdÑ^Hk+3tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$88.classsq~ uq~ 2qaC3P#tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$4.classsq~ uq~ ?y\T9mstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$429.classsq~ uq~ 1 7䡠ntZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/SourceInfo.classsq~ uq~ fl~DYdvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$282.classsq~ uq~ sVW,tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$2.classsq~ uq~ MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$514.classsq~ uq~ 쨕ѣ8DE_T >h8ti/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder.classsq~ uq~ !{MP3 stf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/InterfaceHelperClassNode.classsq~ uq~  Z+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$261.classsq~ uq~ Lf'xy2fZ3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$948.classsq~ uq~ PO뉓 zmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$686.classsq~ uq~ .Kfu?it/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptimizeFlagsCollector$OptimizeFlagsEntry.classsq~ uq~ u+oC0!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$818.classsq~ uq~ ?S֧f?H>XtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/Namespace.classsq~ uq~ vkW}؅`rEtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$8.classsq~ uq~ 0ν`^)fVtN/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlSlurper$1.classsq~ uq~ kdQt}FGt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod$MethodClosureMetaMethod.classsq~ uq~ DaJ$Cn rRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$402.classsq~ uq~ G(x {кRt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerDouble.classsq~ uq~  @B2&&Dhvtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$5.classsq~ uq~ OZtUH7jtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$756.classsq~ uq~ GDW < Rt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$5.classsq~ uq~ uLJ߿{ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v5/JUnit4Utils.classsq~ uq~ iFSñ~Ke(t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$1.classsq~ uq~ c[\M/( )]t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$4.classsq~ uq~ UQl0E;wjtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MethodCaller.classsq~ uq~ Qּ 1 sj;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$624.classsq~ uq~ ._}r9BX 5tV/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoExternalize.classsq~ uq~ wd^T?y`tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$3.classsq~ uq~ !g V<tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$814.classsq~ uq~ dPC4z (t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/DynamicVariable.classsq~ uq~ }o KG#M~tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1028.classsq~ uq~ 3"`<@ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$816.classsq~ uq~ #_y/Jt}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$FastPathData.classsq~ uq~ &;-P@_Xtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/StringBufferWriter.classsq~ uq~ pKWs& ȟtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassNode$MapOfLists.classsq~ uq~ ׽gFz_yA=#tX/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/AbstractHttpServlet.classsq~ uq~ @LV&&|tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/time/DatumDependentDuration$1.classsq~ uq~ me| ˄l!t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$9.classsq~ uq~ @G gbth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/FileOutputTool.classsq~ uq~ P/y.(֤i)tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$23.classsq~ uq~ _{bMTwtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1004.classsq~ uq~ /~te%ԶtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$426.classsq~ uq~ eagEL%-]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$802.classsq~ uq~ a7n,k iӋt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/GroovyClass.classsq~ uq~ ʈ~b>),3tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$DebugRef.classsq~ uq~  2eJ[67IGutY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$742.classsq~ uq~ N^ӜD˳xtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ExtendedVerifier.classsq~ uq~ ˇ}KOjXtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1030.classsq~ uq~ 'HEۉ+߷C@tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1033.classsq~ uq~ 4ד)8':ʩ/to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/AnnotationConstantExpression.classsq~ uq~ FuMqިrtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$226.classsq~ uq~ _l*~bt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/NullObject.classsq~ uq~ u<Z궱ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleLong.classsq~ uq~ :磯 `btx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.classsq~ uq~ 0"Bߚbfx:ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedReference$1.classsq~ uq~ nmN t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$2.classsq~ uq~ b3a[tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.classsq~ uq~ 2~B|1iYn{tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$6.classsq~ uq~ "å`䠒OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$817.classsq~ uq~ ~=%5KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$343.classsq~ uq~ XJ/kdtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$275.classsq~ uq~ -tn=׵km9tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$366.classsq~ uq~ ۪p]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$319.classsq~ uq~ g'NÕijtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/FlatNodeListTraversal.classsq~ uq~ Չ558UΟ᷄th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$7.classsq~ uq~ _ͤ;>xcWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$696.classsq~ uq~ azgvQFxՕtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$518.classsq~ uq~ |Ɍ3w; " >ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/VisitorAdapter.classsq~ uq~ D*6Ztw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaClassGetPropertySite.classsq~ uq~ 9DTHM[ tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$38.classsq~ uq~ !xgO2 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$403.classsq~ uq~ HSslLjϻ/t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$CachedMethodComparatorByName.classsq~ uq~ Q,%ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$151.classsq~ uq~ /KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/GroovyException.classsq~ uq~ ٵa 4X'jYt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ s"ygqVatY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$416.classsq~ uq~ YN :txtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$507.classsq~ uq~ <,p($9tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$71.classsq~ uq~ Jv)ujKdWIt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap.classsq~ uq~ {Qm goRHtb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectFactory.classsq~ uq~ 6z7{Tv%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$917.classsq~ uq~ b -t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$1.classsq~ uq~ qxP{V#2tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$9.classsq~ uq~ #`B]t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/TripleKeyHashMap.classsq~ uq~ 7dۜZ61tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$706.classsq~ uq~ ;S苶D_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$913.classsq~ uq~ ?>PTd6u⑸tK/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlParser.classsq~ uq~ ŏ^Wl]t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ z"8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$670.classsq~ uq~ ãJةͳìtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$762.classsq~ uq~ r9qP#c䊿btX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$50.classsq~ uq~ @2E'D,nth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$8.classsq~ uq~  ō: /JK\tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$CategoryMethodList.classsq~ uq~ 9O'agP*tH/home/blackdrag/coding/groovy/18/target/classes/groovy/io/FileType.classsq~ uq~ 'eqtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$4.classsq~ uq~ 3SZEULTtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$1.classsq~ uq~ rֿQ !ktY/home/blackdrag/coding/groovy/18/target/classes/groovy/util/FactoryBuilderSupport$2.classsq~ uq~ FWBXnuMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$771.classsq~ uq~ N xe}' tR/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/GroovyServlet.classsq~ uq~ 8}HjufgItb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/Visitor.classsq~ uq~ i 8vV`HRj tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$8.classsq~ uq~ Qп6H` 0֠tJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange.classsq~ uq~ 1b{fHXtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$6.classsq~ uq~ 86sunm"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$721.classsq~ uq~ XfՔ ,b5t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ Jr 6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$393.classsq~ uq~  j(&4Rݩth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LogASTTransformation.classsq~ uq~ sE"MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$160.classsq~ uq~ Kk\v/¶ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$134.classsq~ uq~ 6a0`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$240.classsq~ uq~ ڂERx0˞Q*th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/NodeCollector.classsq~ uq~ 4X/iXCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$898.classsq~ uq~ Pjud/tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/DefaultMetaClassInfo.classsq~ uq~ {ʪ-oExtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$171.classsq~ uq~ :N9sɁjta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$1.classsq~ uq~ L L45F42y`ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/CompilationCustomizer.classsq~ uq~  !1_1mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$907.classsq~ uq~ %Q1"GDt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$13.classsq~ uq~ Pank@dI tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$233.classsq~ uq~ zȩAoWy[8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$561.classsq~ uq~ `2&| %ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$107.classsq~ uq~ 26w.ttS/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/PropertyAccessor.classsq~ uq~ Vf|iV tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$544.classsq~ uq~ Qdu`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$155.classsq~ uq~ V.t/Ij E`te/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTextComponentProperties$1.classsq~ uq~ ֒^FFE0.tT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletCategory.classsq~ uq~ \-bWrՒ)td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BooleanExpression.classsq~ uq~ 4m.}Z!`ϻtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$999.classsq~ uq~ Q)bJ/ HItX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$83.classsq~ uq~ Dc3"buOth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/IteratorClosureAdapter.classsq~ uq~ ԴP  K/tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyFieldDoc.classsq~ uq~ hAf?ON)yte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformation.classsq~ uq~ YLV!ContZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1006.classsq~ uq~ ? U0nTFHetY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/BatchingStatementWrapper.classsq~ uq~ R.K?1(ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$350.classsq~ uq~ #.݆tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$1.classsq~ uq~ l=Uf6"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$279.classsq~ uq~ lڸ'z$ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$979.classsq~ uq~ < Δ1&ta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$7.classsq~ uq~ |!@p>KMratY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$119.classsq~ uq~ r0a񩾷D<.tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/PropertyValue.classsq~ uq~ reWԕEd0 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$102.classsq~ uq~ tA^ v^[f2tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/GroovyASTTransformationClass.classsq~ uq~ ==VьAnLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$149.classsq~ uq~ kQ7{隫[lD@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$93.classsq~ uq~ Y|'΢r |ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$342.classsq~ uq~ 䉸 N tb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementAddedEvent.classsq~ uq~ 5m){q>xtO/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport.classsq~ uq~ ?ub"|x`>]WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$626.classsq~ uq~ f :AqFtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$28.classsq~ uq~ ]q/Sth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$3.classsq~ uq~ zXS;+tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$MethodChooser.classsq~ uq~ OaS}}tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/PrefixExpression.classsq~ uq~ {q2?k_t/tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask$JavacAdapter.classsq~ uq~ eC#2_XN9n&tH/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/XmlUtil.classsq~ uq~ ,b/ 4tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovydoc.classsq~ uq~ )o]*t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/xml/DomToGroovy.classsq~ uq~ Er}XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$469.classsq~ uq~ ;=/G tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$867.classsq~ uq~ &l ƕetY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$848.classsq~ uq~ UN-9(tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$5.classsq~ uq~ "=Q\_l6]tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attribute.classsq~ uq~ T=IK܋ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$846.classsq~ uq~ R@Q)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$627.classsq~ uq~ ø)گj!O|t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$KeyIterator.classsq~ uq~ 0'5a St|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$EntrySet.classsq~ uq~ |-7]ruq8tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods.classsq~ uq~ Y|EĚYL +9Ktf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/ClosureWriter$1.classsq~ uq~ [ uw[MwitQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$4.classsq~ uq~ ]yew !{0tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$ThreadedReferenceManager$1.classsq~ uq~ 12aGFQ%tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/EnumHelper.classsq~ uq~ _.wbn 縲tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxElementsBinding.classsq~ uq~ gc1څT]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$267.classsq~ uq~ gP!Vi"TζvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$854.classsq~ uq~ &u8 dn"td/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractJComponentBinding.classsq~ uq~ fuyp=OKxtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ReturnAdder$ReturnStatementListener.classsq~ uq~ >{{{13ܗtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerFloat.classsq~ uq~ N9Ben`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$727.classsq~ uq~ Z|aAOctU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$3.classsq~ uq~ 9>dx\ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$887.classsq~ uq~ *V'؉F`wtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$14.classsq~ uq~ ѳt) 6etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$596.classsq~ uq~ %0^T tU/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$1.classsq~ uq~ / XvI"1Xta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JScrollBarValueBinding.classsq~ uq~ ͮJ7|atd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AnnotationVisitor.classsq~ uq~ LVh~m @^w{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$676.classsq~ uq~ Gx*![4htStj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/MethodPointerExpression.classsq~ uq~ QNҋfBitY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$451.classsq~ uq~ u h!~!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$795.classsq~ uq~ [F%M÷tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex$Header.classsq~ uq~ a؈A\&UtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$81.classsq~ uq~ i-13)#FOXZt]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attributes$1.classsq~ uq~ h~9|~|7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$813.classsq~ uq~ -KRG@tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$1.classsq~ uq~ ?>mtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$4.classsq~ uq~  ̶['~*Ļ9jKtd/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IncorrectClosureArgumentsException.classsq~ uq~ #1b 1,stz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayGetAtMetaMethod.classsq~ uq~ IğNTwktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$832.classsq~ uq~ ϱt/w Rtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatInteger.classsq~ uq~ w)à3b;I[{wta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$5.classsq~ uq~ 2KEtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$17.classsq~ uq~ ="bʎƻ(tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/OwnedMetaClass.classsq~ uq~ @3U59tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap$Segment.classsq~ uq~ 4úיa7ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/GroovySourceToken.classsq~ uq~ \O";>1UtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$117.classsq~ uq~ 癒M|š`Jts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl$2.classsq~ uq~ ت3]tPNt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrParserPlugin$AnonymousInnerClassCarrier.classsq~ uq~  (4|2F!stY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$547.classsq~ uq~ 1]qW}tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport$2.classsq~ uq~ «ngtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$732.classsq~ uq~ E:^;krEtR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$16.classsq~ uq~ ߺg)9^=tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$ClassgenCallback.classsq~ uq~ L6 kr=tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$287.classsq~ uq~ |L]K98to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMethodDoc.classsq~ uq~ % j)q?VZUt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ForStatement.classsq~ uq~ Ve+N/*ۊ tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/UnicodeLexerSharedInputState.classsq~ uq~ y=&8K*otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$657.classsq~ uq~ Eu󜤆tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$253.classsq~ uq~ ' ʟ(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$716.classsq~ uq~ CTziN)uctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$205.classsq~ uq~ q]!&kth/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxSelectedIndexBinding.classsq~ uq~ g7qZVAkp4tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/FastArray.classsq~ uq~ FWAltW/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Node$2.classsq~ uq~ @<ӹ"/p3Ltc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractButtonProperties.classsq~ uq~ FI gf MiTFѻtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$649.classsq~ uq~ ~!r~::tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$508.classsq~ uq~ v0wtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader.classsq~ uq~ \a4\O~~td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$1$1.classsq~ uq~  7)0StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$734.classsq~ uq~ _|7;Dta/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$MethodIndexAction.classsq~ uq~ % '7:gFtd/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementRemovedEvent.classsq~ uq~ \gے +giq^wadtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$866.classsq~ uq~ x cM[&tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/TupleExpression.classsq~ uq~ ;y,\|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$611.classsq~ uq~ fC"2EEkBtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/PostfixExpression.classsq~ uq~ gO(y+Dtz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatDouble.classsq~ uq~ vFYO4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$836.classsq~ uq~ u?hњ V(t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayPutAtMetaMethod.classsq~ uq~ j⧄\T]0z)ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayGetAtMetaMethod.classsq~ uq~  M7|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$829.classsq~ uq~ ^\NT 3EktU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyObjectSupport.classsq~ uq~ }J%x톏(tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/InheritConstructors.classsq~ uq~ Ir W^tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$61.classsq~ uq~ V4g @V/tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$312.classsq~ uq~ Ưڮ1NjRҺtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$505.classsq~ uq~ {W3K=tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/GeneratorContext.classsq~ uq~ x%S$dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$223.classsq~ uq~ )%yl{X"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$53.classsq~ uq~ {;%+?׭;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$947.classsq~ uq~  =]Lt_/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/Builder.classsq~ uq~ =7{s(YLts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ClassInfoSet$Segment.classsq~ uq~ c^ ⤑7-A$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$412.classsq~ uq~ L|9B1u0tK/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonToken.classsq~ uq~ Dyȸ@ctX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Numbers.classsq~ uq~ 9 d <|M5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$808.classsq~ uq~ Pxu.+J t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite$ConstructorSiteNoUnwrap.classsq~ uq~ aU2L~tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/UnaryPlusExpression.classsq~ uq~ JXo >HtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ScriptException.classsq~ uq~ 6V,삃u(tY/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Closure$WritableClosure.classsq~ uq~ dG.DtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/MapEntry.classsq~ uq~ $G UA$Q.th/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$ScriptClassLoader$1.classsq~ uq~ S:'؀p5 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$491.classsq~ uq~ ҹD @CAt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/InnerClassNode.classsq~ uq~ r%B? Iztt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/MultipleCompilationErrorsException.classsq~ uq~  ֣r[2$LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$743.classsq~ uq~ q0>5ӫAht^/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$GspPrinter.classsq~ uq~ x;Dz3ytz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$ThreadCategoryInfo.classsq~ uq~ a-K%g*ZKt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/CodeVisitorSupport.classsq~ uq~ H9FTk#ʲqXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$409.classsq~ uq~  Qr+tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$44.classsq~ uq~ hX4DA4tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoGetPropertySite.classsq~ uq~  t~iVGF[Ctf/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ReferenceResolver.classsq~ uq~ _b xX-tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$5.classsq~ uq~ U3Cwt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ErrorCollector.classsq~ uq~ ^|'qYGHtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.classsq~ uq~ 4X)^PURsNtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$288.classsq~ uq~ [GnsK?tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper.classsq~ uq~ Izx%l>0)atO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$3.classsq~ uq~ NoAjIt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptimizeFlagsCollector.classsq~ uq~ =)'}OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$271.classsq~ uq~ k^c#Ptb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ClassExpression.classsq~ uq~ yƺa~ZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$289.classsq~ uq~ \xeS4'%oG>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$740.classsq~ uq~ Ѫa7.otN/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/CallResultSet.classsq~ uq~ NkJ|tf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$MixedInAccessor$1$1.classsq~ uq~ K gj tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString$3.classsq~ uq~ %3Py]zg}}tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/DoWhileStatement.classsq~ uq~ }aKhˈiĿOtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$FloatDouble.classsq~ uq~ wUjhT?tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$188.classsq~ uq~ |<Z" >˧tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$24.classsq~ uq~ `hy[pott/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/CharacterCachedClass.classsq~ uq~ r7BZtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$34.classsq~ uq~ ͭ"XԔ6#tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/parser/GroovyLexer.classsq~ uq~ ʉj"++XAo!53tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$239.classsq~ uq~ l;&xy҆J|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$842.classsq~ uq~ #)W1=jĿ pt}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/SourceTextNotAvailableException.classsq~ uq~ s QAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$357.classsq~ uq~ <#usX17ŬtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$372.classsq~ uq~ cgG:fޕ{-KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$581.classsq~ uq~ xv0.~0%6"S ntY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$567.classsq~ uq~ wštr*t^/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadMapEvaluatingException.classsq~ uq~ t4UsUԙ(=to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/AssertionRenderer.classsq~ uq~ \_DO_G(4tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassHelper$ClassHelperCache.classsq~ uq~ [۶gOnMnytn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ImmutableASTTransformation.classsq~ uq~ *͂]v >t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyType.classsq~ uq~ 3e5ڒ.WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$845.classsq~ uq~ dA\cR/0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$688.classsq~ uq~ `6)+fort]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$3.classsq~ uq~ $\GWGH&TFtP/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass.classsq~ uq~ \JW4T:tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$41.classsq~ uq~ -|I82~ڠZ#tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyFieldDoc.classsq~ uq~ ~+)I|oth/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$NewInstanceResolver.classsq~ uq~ `@&xi8tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$27.classsq~ uq~ Le[olM{w]ItL/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlSlurper.classsq~ uq~ V6)]*S84t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren.classsq~ uq~ *-.\8a_ctq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryLongExpressionHelper.classsq~ uq~ ?N\ '=PtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$78.classsq~ uq~  R vk0MVtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/time/Duration.classsq~ uq~ O0DԾ(AI7tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/MethodCallExpression.classsq~ uq~ !o%5/ٯktX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$54.classsq~ uq~ UpbRܨۥtc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$3$1.classsq~ uq~ mF]gtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ClassInfoSet.classsq~ uq~ .[i-tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSite.classsq~ uq~ sп <ާP|+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$443.classsq~ uq~ ]m9 >3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$401.classsq~ uq~ t o&UdC^tg/home/blackdrag/coding/groovy/18/target/classes/groovy/text/GStringTemplateEngine$GStringTemplate.classsq~ uq~ g aQƄTBwt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$1.classsq~ uq~ vJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$281.classsq~ uq~ 1Ο itc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$6$1.classsq~ uq~ kf ;Q`BtP/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/dom/DOMCategory.classsq~ uq~ Aˀ/`5 te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList$Iter.classsq~ uq~ Qgdi6^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$498.classsq~ uq~  Tpi;vT=ҥ>*tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleLong.classsq~ uq~ Er8 ſtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer.classsq~ uq~ pn={2M69;tJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Sequence.classsq~ uq~ aHzrtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovyc$1.classsq~ uq~ pk ^(7X•~tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/AssertionWriter.classsq~ uq~ Emwz (*tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PerInstancePojoMetaClassSite.classsq~ uq~ ,SųtEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$456.classsq~ uq~ p{r<ޮ5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$638.classsq~ uq~ m0ά;K{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$820.classsq~ uq~ wZRRF{tL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaMethod.classsq~ uq~  QM'd&ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.classsq~ uq~ xW^7 etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$920.classsq~ uq~ aE'AT@tg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$IdentifierResolver.classsq~ uq~ ӫGWq_2z3*to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/NullProtectionStorage.classsq~ uq~ L)оkb9îtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovyMain.classsq~ uq~ K(7p~hX1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$667.classsq~ uq~ ?'(|$%tW_tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$98.classsq~ uq~ ]WpOYmdR5ItS/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding.classsq~ uq~ 1U1 X}~tb/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$DefiningClosure.classsq~ uq~ {d<~td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/TernaryExpression.classsq~ uq~ пOMp[DtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$19.classsq~ uq~ I%k tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$822.classsq~ uq~ 0 r9Uq9htM/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonSlurper.classsq~ uq~ Pp{N+ \tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer.classsq~ uq~ gF3M 5"tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1053.classsq~ uq~ . TWqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$159.classsq~ uq~ .55tR/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ProxyGenerator$1.classsq~ uq~ OTͭ l6!cF?otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$368.classsq~ uq~ 8JRtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$SoftRef.classsq~ uq~ Gh:A}t3tV/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ResultSetOutParameter.classsq~ uq~ %~SW!~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$580.classsq~ uq~ ;N)wotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$478.classsq~ uq~ !vM6Zltw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleFloat.classsq~ uq~ vᚒGn@=&ntp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareCompilationUnit$2.classsq~ uq~ n@Ê*@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$964.classsq~ uq~ ˑhâ_"ߺEU88GtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$726.classsq~ uq~ 0Mˤlt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$3.classsq~ uq~ [[xmBpPPytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$741.classsq~ uq~ q_۴FsK?ŗto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper$1.classsq~ uq~ ?Z*yyVt_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties.classsq~ uq~ i_FvG<긆tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$7.classsq~ uq~ (^5R`3 `ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryObjectExpressionHelper.classsq~ uq~  BM3T Ht]/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$AbstractStatementCommand.classsq~ uq~  1C&ҼOtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavacJavaCompiler.classsq~ uq~ :{Bs5i/0ARota/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyRootDoc.classsq~ uq~ J sz%t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerInteger.classsq~ uq~ F$(9_tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/TupleConstructorASTTransformation.classsq~ uq~ yI* jZI+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$311.classsq~ uq~ +y3o t^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$5.classsq~ uq~ oxZ?5]J@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$601.classsq~ uq~ 2% d1/ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$609.classsq~ uq~ 08.xN82ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$715.classsq~ uq~ @lYJkndtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/RangeExpression.classsq~ uq~ 3AD[=rǠtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$58.classsq~ uq~ h BVӡ&V,P$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$481.classsq~ uq~ 8=50B`:p׭AtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$868.classsq~ uq~ ;"o ŠyaCtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/EqualsAndHashCodeASTTransformation.classsq~ uq~ 4hd!79.7t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.classsq~ uq~ m] Hߘ7WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$125.classsq~ uq~ MȍƲ;Pty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayPutAtMetaMethod.classsq~ uq~ vf $DȏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$192.classsq~ uq~ y;EətY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$747.classsq~ uq~ H /(j?ytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$231.classsq~ uq~ > AjtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$834.classsq~ uq~ 46[zoSe~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$346.classsq~ uq~ Bf0mmD>tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$4.classsq~ uq~ W4]#[PTa‹tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Singleton.classsq~ uq~ Heub" tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ParameterTypes.classsq~ uq~ H>|xݷtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$229.classsq~ uq~  @NXtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/WriterControllerFactory.classsq~ uq~ ;O܉"OI`$mt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ProcessingUnit.classsq~ uq~ I{F#s==td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ReflectionCache.classsq~ uq~ Udm,8ttF/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/QName.classsq~ uq~ C2=IRoStl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixedInMetaClass.classsq~ uq~ #{uft`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor.classsq~ uq~ *p2nPX3ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$610.classsq~ uq~ @gX>V֜Ə)UtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/Utilities.classsq~ uq~ }K+ Ԇn-tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/Finalizable.classsq~ uq~ (*#qwBty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerDouble.classsq~ uq~ #CNYqE9kIWtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/RuntimeParserException.classsq~ uq~ Չ+WSy;tN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovySystem.classsq~ uq~ 23= ﱛq3ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyAnnotationRef.classsq~ uq~ KX?7 d\ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$332.classsq~ uq~ '}x֡OAjktf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/CharWrapper.classsq~ uq~ o/bj 3>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$781.classsq~ uq~ `5W2ʯLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$584.classsq~ uq~ ,DQҟnGe(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$423.classsq~ uq~ nkQ{Huytb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/XmlGroovyMethods.classsq~ uq~ so(t3\vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$623.classsq~ uq~ $ttq ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$LongLong.classsq~ uq~ 1\."P{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$361.classsq~ uq~ Sn07tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$618.classsq~ uq~ pV7s::putY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$754.classsq~ uq~ I.@`^WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$582.classsq~ uq~ Fu tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/TypeChooser.classsq~ uq~ #a|_EWS_tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.classsq~ uq~ pQvG-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$299.classsq~ uq~ |9+XYg֓tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$944.classsq~ uq~ ھX Ҫ:'tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$29.classsq~ uq~ ku<[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$724.classsq~ uq~ =4n!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/Janitor.classsq~ uq~ _rƣJ+tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/Preferences.classsq~ uq~ z{w ̊XItY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$603.classsq~ uq~ qJw "VQnvg8ta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JScrollBarProperties$1.classsq~ uq~ + /6tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$DoubleLong.classsq~ uq~ k[%1G H)itG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$32.classsq~ uq~ $&j6ysn K3ڞtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareResolveVisitor.classsq~ uq~  X*f9)utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$922.classsq~ uq~ r[Jr5N +~[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$674.classsq~ uq~ o8wZy$%zLt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/DeadEndObject.classsq~ uq~ iH %2jjtY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$AbstractQueryCommand.classsq~ uq~ =\_ygmXW(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$540.classsq~ uq~ X-Oʒsa%ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ReflectionMethodInvoker.classsq~ uq~ TU )5vtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Delegate.classsq~ uq~ ʝJ-a%tb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$MultiPropertyEvent.classsq~ uq~ Ѿ'@:-NtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$558.classsq~ uq~ J9X-xW |te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectRefFactory.classsq~ uq~ -TiG5t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MissingPropertyExceptionNoStack.classsq~ uq~ 2rj^(z ,hr,= tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.classsq~ uq~ wɆ]~! oUtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$145.classsq~ uq~ 9kTU5z#Vto/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultChildPropertySetter.classsq~ uq~ oPeYȧ,qFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$440.classsq~ uq~ B)JOЊGtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$IntegerFloat.classsq~ uq~ KZ6Օ( +tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$811.classsq~ uq~ k;$:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$286.classsq~ uq~ ?-$sIj(td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/GStringExpression.classsq~ uq~ H0ܶwZ dstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$176.classsq~ uq~ iVڌvCeQ=gtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$7.classsq~ uq~ <,+ŸO?\Uite/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding.classsq~ uq~ L`@ tY/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/PackageScopeTarget.classsq~ uq~  s;=4bi ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$886.classsq~ uq~ YLɁGmdz; tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$592.classsq~ uq~ UhetR/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/TypeChecked.classsq~ uq~ Uf)$mƩh%tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayPutAtMetaMethod.classsq~ uq~ qՎJ72|GytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$957.classsq~ uq~ ly:ͦQot^/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSliderValueBinding.classsq~ uq~ Ӄp#/ .rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$142.classsq~ uq~ qkrrtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer$Import.classsq~ uq~ aZwaU!+˦tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$764.classsq~ uq~ aruCxQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$689.classsq~ uq~ @J kktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$790.classsq~ uq~ Jؿ+kf+tg/home/blackdrag/coding/groovy/18/target/classes/groovy/model/DefaultTableModel$MyTableColumnModel.classsq~ uq~ ~CŊNtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$504.classsq~ uq~ \X 'IأOtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$3.classsq~ uq~ A4<~gH~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$152.classsq~ uq~ ~h@|VT~-ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$992.classsq~ uq~ -o@QtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$31.classsq~ uq~ JT;ˑFF:9]tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$FloatDouble.classsq~ uq~ fJJe}"$OltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$946.classsq~ uq~ xWm}nEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$364.classsq~ uq~ 0&XI W8*td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/XmlGroovyMethods$1.classsq~ uq~ Y \.c,>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$643.classsq~ uq~ 8;j(.otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$432.classsq~ uq~ A eTF}nta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$4.classsq~ uq~ KX|#w)<]BtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/GroovycTask.classsq~ uq~ wC%pZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$647.classsq~ uq~ "TI+7byZ|?Ytm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ToStringASTTransformation.classsq~ uq~ s)O& VtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$587.classsq~ uq~ :>(ZV_ύtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/RootLoader.classsq~ uq~ Dz QE2P|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$855.classsq~ uq~ E dCKRrLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$221.classsq~ uq~ EW {M7XztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$178.classsq~ uq~ vw%MPH|(.ShtT/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/MarkupBuilderHelper.classsq~ uq~ .q Eq1dlt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$4.classsq~ uq~ ]Ψ8퐄˰tM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodePrinter.classsq~ uq~ "qbA[ѢtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$782.classsq~ uq~ 4@r&ڠ3;1Ƕpt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$14.classsq~ uq~ U ݔ$CtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$389.classsq~ uq~ ϼ".yʭtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/SingletonASTTransformation.classsq~ uq~ .a}hQɟPӚtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$9.classsq~ uq~ eL:&h|0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$321.classsq~ uq~ 4+atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$763.classsq~ uq~ jcRۛ˓t&D%>to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/PluginStaticGroovyMethods.classsq~ uq~ ;8Kb[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$800.classsq~ uq~ 4J0wbtlKѦtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$862.classsq~ uq~ $\0'A?^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$557.classsq~ uq~  kXL^/2tP/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ProxyGenerator.classsq~ uq~ νI: Һt_/home/blackdrag/coding/groovy/18/target/classes/groovy/grape/GrabAnnotationTransformation.classsq~ uq~ ^ПC kɘtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$452.classsq~ uq~ dRrOph_?ytm/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultReferenceResolver.classsq~ uq~ Iɑ܆:+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$815.classsq~ uq~ ߡĤ;f`8tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$1.classsq~ uq~ R7V8澌OKt-tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$86.classsq~ uq~ &kH9outp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ReflectionMetaMethod.classsq~ uq~ @g5KDI&UtO/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Slf4j.classsq~ uq~ |2>^ՉdLK&?t_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$3.classsq~ uq~ עT-3I;VtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$722.classsq~ uq~ t}ZCy(4te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ParserPluginFactory.classsq~ uq~ U\/~m`j_stWtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindPath.classsq~ uq~ wD뭝HQ_tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$1.classsq~ uq~ K1&+ to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/SharedVariableCollector.classsq~ uq~ 63_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$825.classsq~ uq~ x/_y58vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$382.classsq~ uq~ "iEe EtV/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Types.classsq~ uq~ H4Z+CWX0tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Reference.classsq~ uq~ x#ڇrLOtO/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/ToString.classsq~ uq~ 0CgSls5ytP/home/blackdrag/coding/groovy/18/target/classes/groovy/util/BuilderSupport.classsq~ uq~ UU#!aVWFtU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$4.classsq~ uq~ |%aP8tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/MemoizeCache.classsq~ uq~ aO$t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$StandardClosureChooser.classsq~ uq~ hup 5&jtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MethodNode.classsq~ uq~ TJ^DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$501.classsq~ uq~ 'rto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/TransformMetaMethod.classsq~ uq~  h/Oa%zTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$893.classsq~ uq~  MO8O@;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$530.classsq~ uq~ ؖFXyoBxtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$238.classsq~ uq~ e3zZlte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/SingleKeyHashMap$Entry.classsq~ uq~ HrC;tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$4.classsq~ uq~ prgsȯOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$780.classsq~ uq~ v q7?Bth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/MetaClassSite.classsq~ uq~ a=.cjbStV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$3.classsq~ uq~ }B&Xo)% #a.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$564.classsq~ uq~ ׹3\0 03btN/home/blackdrag/coding/groovy/18/target/classes/groovy/time/TimeDuration.classsq~ uq~ {SSTA̾mtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$NumberNumber.classsq~ uq~  jH(CSptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$425.classsq~ uq~ B1,2tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/CompileUnit.classsq~ uq~ {j>@#lItY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$531.classsq~ uq~ E(Yi\Lkftf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$5.classsq~ uq~ haU tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$952.classsq~ uq~ کXi9tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$18.classsq~ uq~ !D#)OPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$883.classsq~ uq~  KtѦ;gtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$15.classsq~ uq~ zAs1s!ftV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$2.classsq~ uq~ =!aiW,Qth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList$Element.classsq~ uq~ }~2=F/Z΍t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier.classsq~ uq~ R c+BmFV}Y"]tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$25.classsq~ uq~ !;o\$tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$1.classsq~ uq~ /ݚ#;57.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$375.classsq~ uq~ ΂aD vhtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$338.classsq~ uq~ pSPK"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$19.classsq~ uq~ MT A-Mvr`tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$Values.classsq~ uq~ d*1vDT8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$541.classsq~ uq~ 9?+YV$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$989.classsq~ uq~ ٛ[~7Vo|h I5#j2td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$3$1.classsq~ uq~  )ʹ&tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$230.classsq~ uq~ T gKq+ƕ!t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptVisitor.classsq~ uq~ e%xvȶctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$972.classsq~ uq~ ehvBEtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$1.classsq~ uq~  %*_>dm(t\/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/BindableASTTransformation.classsq~ uq~ e$l,РC\ctc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BinaryExpression.classsq~ uq~ `!e ?y-YtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$252.classsq~ uq~ Y;&Z2_tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$10.classsq~ uq~ X*r3]atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$392.classsq~ uq~ Zap`tM/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/OutParameter.classsq~ uq~ #%ן<$:^XttZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1046.classsq~ uq~ alF`Għti/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovySocketServer$GroovyClientConnection.classsq~ uq~ -ن^jOte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$1.classsq~ uq~ )L߳L\YtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$75.classsq~ uq~  LeH&Nt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ OFa+tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$34.classsq~ uq~ Y,CO+"Wޟ( t[/home/blackdrag/coding/groovy/18/target/classes/groovy/io/EncodingAwareBufferedWriter.classsq~ uq~  ;:c GFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$598.classsq~ uq~ >(zq6}ktg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ObservableListIterator.classsq~ uq~ bl(72Ut}tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$20.classsq~ uq~ rFh4m%of}ӻyt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap.classsq~ uq~ g gUp:@ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/InvokerHelper$2.classsq~ uq~ HKƜrɑTitY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$353.classsq~ uq~ Vz`ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorMetaClassSite.classsq~ uq~ [Qnzm1E'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$975.classsq~ uq~ CX͊6mt`/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/dom/DOMCategory$NodeListsHolder.classsq~ uq~ z' jW3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$860.classsq~ uq~ 4 0:pX`tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$LongFloat.classsq~ uq~ qQM6~{&Otb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/FieldExpression.classsq~ uq~ @qI1ML7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$529.classsq~ uq~  L)$Ztd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMap.classsq~ uq~ Fyg2_|?tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$0.classsq~ uq~ O%G'x)Itb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/SwitchStatement.classsq~ uq~ ^FCr3cJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$719.classsq~ uq~ 4v[ bgUHxtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$12.classsq~ uq~ \;N0&[ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$422.classsq~ uq~ ZdzmFt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/ErrorReporter.classsq~ uq~ PDq,L@!BZzti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/MindMapPrinter.classsq~ uq~ L;n !t(t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/ParserException.classsq~ uq~ }]?g'N?L/ytj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/IntegerMath.classsq~ uq~ Ll$KaKto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit$2.classsq~ uq~ brFlbty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongDouble.classsq~ uq~ 7:ףm*_%(tI/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Closure.classsq~ uq~ w}=dٮtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$438.classsq~ uq~ LMNujrvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$881.classsq~ uq~ LQepP\tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$126.classsq~ uq~ Gu?jm%WotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$830.classsq~ uq~ EBN`A@`6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$198.classsq~ uq~ ,"+KBkFx}ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LazyASTTransformation.classsq~ uq~ ͙SI]tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1023.classsq~ uq~ 5 U$VE'ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleInteger.classsq~ uq~ '} C:0tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$CachedMethodComparatorWithString.classsq~ uq~ 㥴8͖tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ResourceConnector.classsq~ uq~ ]5GuI}tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$788.classsq~ uq~ 'hᵍY"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$189.classsq~ uq~ U8EOmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$339.classsq~ uq~ "m7ZILth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/SynchronizedStatement.classsq~ uq~ t07ف0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$827.classsq~ uq~ U7C4LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$243.classsq~ uq~ MtmYM!r6$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$237.classsq~ uq~ :$3 uD #etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$723.classsq~ uq~ lc Wc!2'-t^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$2.classsq~ uq~ Ma7-cFvtK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString$2.classsq~ uq~ x=yAtZ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingPropertyException.classsq~ uq~  5*یS]8F)tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatLong.classsq~ uq~ + ;aV_/"t tI/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Factory.classsq~ uq~ u U\Eot/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ 뢚Қ|4tf/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectBeanFactory.classsq~ uq~ (5 ^E+;tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayPutAtMetaMethod.classsq~ uq~ O~PEȤ4;tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ClosureException.classsq~ uq~ UH6JaP'ݫtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask$GroovycAdapter.classsq~ uq~ qwʎw3tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/InheritConstructorsASTTransformation.classsq~ uq~ _sAby3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$671.classsq~ uq~ !f8Į|te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredNodeChildren.classsq~ uq~ _ Er^\ ڏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$789.classsq~ uq~ Dv_;aSC^Ate/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ConstantExpression.classsq~ uq~ SA`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$499.classsq~ uq~ c3xKtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$749.classsq~ uq~ }KjQ!mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$662.classsq~ uq~ k(T+t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$2.classsq~ uq~ 4 i+HN tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$3.classsq~ uq~ &\AРK*Qth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/MessageSource.classsq~ uq~ "ȟǕ|t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$15.classsq~ uq~ ?lqMSVG]mt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/StaticVerifier.classsq~ uq~ *a`ơtW/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$ExtractIndexAndSql.classsq~ uq~ ܏ e- neltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$500.classsq~ uq~ u41_>tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$64.classsq~ uq~ 爓HǣatQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport$1.classsq~ uq~ Q lOB})tP/home/blackdrag/coding/groovy/18/target/classes/groovy/model/PropertyModel.classsq~ uq~ s._֞{FL{UVotG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$17.classsq~ uq~ cj|h=;DHtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AbstractFactory.classsq~ uq~ ,,Qc9ʣKhƛ"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$320.classsq~ uq~ P*goJb5p2ҙtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$821.classsq~ uq~ R*'֯GtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$760.classsq~ uq~ 4:+k01xtS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyCollections.classsq~ uq~ Fҡ(_ԛr@c/tR/home/blackdrag/coding/groovy/18/target/classes/groovy/io/PlatformLineWriter.classsq~ uq~ wZ Vt\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attribute$1.classsq~ uq~ `-α@tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/GroovyExceptionInterface.classsq~ uq~ |m$*c2dFtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareCompilationUnit$1.classsq~ uq~ USg۷-cto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader.classsq~ uq~ 3mQsEdt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSite.classsq~ uq~ ✨G*+cXR3tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureSourceBinding.classsq~ uq~  sDȏtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$2.classsq~ uq~ Ʌ:HnjXG=Ok1tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongLong.classsq~ uq~ ;%26`WKtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$534.classsq~ uq~ !e@,;:G/Ctw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport$RangeInfo.classsq~ uq~ uȴ{l˳tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/BooleanCachedClass.classsq~ uq~ cy #DNtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatFloat.classsq~ uq~ ydA$x!=tY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ResultSetMetaDataWrapper.classsq~ uq~ xoKE?tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$877.classsq~ uq~ bt<ˉ2rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$833.classsq~ uq~ b]\CwZtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.classsq~ uq~ &]sGݱitZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1005.classsq~ uq~ NN.Ü0tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/tools/WideningCategories.classsq~ uq~ ]RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$552.classsq~ uq~  y*+tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$6.classsq~ uq~ ݷ>1{-umbta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/InvokerHelper$1.classsq~ uq~ YOn3LӦ+| tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$995.classsq~ uq~ Zϭm$ /t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GenericsType$1.classsq~ uq~ diB7TIfxtr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/ClasspathResourceManager.classsq~ uq~ 㰸E8YHto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewStaticMetaMethod.classsq~ uq~ i2 dtK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Buildable.classsq~ uq~ rjQzp~tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/UnicodeEscapingReader$DummyLexer.classsq~ uq~ Y9w|:td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/TryCatchStatement.classsq~ uq~   /55.8ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap$Entry.classsq~ uq~ IQARЉJh]t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite$NoParamSiteInnerClass.classsq~ uq~ gyyk*bgI8t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/FullBinding.classsq~ uq~ Еf_&>rCÆmjti/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$RelationNameResolver.classsq~ uq~ pxF[ &sotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$751.classsq~ uq~  08+w&~tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$ExceptionTableEntry.classsq~ uq~ sLvM(v(tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/inspect/swingui/TableSorter$1.classsq~ uq~ {1uxFqtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$63.classsq~ uq~ `/X&4φtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$207.classsq~ uq~ 2f%VvxCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$278.classsq~ uq~ ރ]Ȧ 81tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$837.classsq~ uq~ @ުyM&_Vth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyConstructorDoc.classsq~ uq~ Kf&LgSᵎtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$5.classsq~ uq~ pюNm3t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/HashCodeHelper.classsq~ uq~ \*I%tc/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ObservableIterator.classsq~ uq~ LQհ<.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$249.classsq~ uq~ ޠ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$222.classsq~ uq~ &f\L(_DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$865.classsq~ uq~ ^)K6^TPWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$513.classsq~ uq~ +-* h]tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/GroovyCastException.classsq~ uq~ W V7J`gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$334.classsq~ uq~ YLLdnj-3+Vx%te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log$JavaUtilLoggingStrategy.classsq~ uq~ 싈>"1ICuti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyPathFullBinding.classsq~ uq~ ћp?¤^ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$225.classsq~ uq~ qQz>zpjtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/text/Template.classsq~ uq~ mglov6#7j;tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongDouble.classsq~ uq~ K׵q+3E#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$331.classsq~ uq~ g⠞t>TXƺtF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$5.classsq~ uq~ ^F OVfccftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$546.classsq~ uq~ lNH T rtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$97.classsq~ uq~ h?c4?QtS/home/blackdrag/coding/groovy/18/target/classes/groovy/json/StringEscapeUtils.classsq~ uq~ ps.j@$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$162.classsq~ uq~ Zaqlt+̫7tW/home/blackdrag/coding/groovy/18/target/classes/groovy/text/GStringTemplateEngine.classsq~ uq~ .7ﱎ)I^dAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$196.classsq~ uq~ E:'\|~ρIWtM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GrabExclude.classsq~ uq~ /R*g4 m>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$856.classsq~ uq~ Mb㻩k(LXtz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongInteger.classsq~ uq~ |ghk֏Rt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryByteExpressionHelper.classsq~ uq~ \^YԾLFp8:_tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyProgramElementDoc.classsq~ uq~ +嘑$Lّtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassCodeExpressionTransformer.classsq~ uq~ ٯIk+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$934.classsq~ uq~ ޒATXmqC Ptq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/NumberCachedClass.classsq~ uq~ yOXty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/VariableScopeVisitor$StateStackElement.classsq~ uq~ /,"~s=1.tP/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyResultSet.classsq~ uq~ Aм q"8y5tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ClosureComparator.classsq~ uq~ ږ)#ɶ(ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MissingMethodExceptionNoStack.classsq~ uq~ 0-n#rk*K2_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$121.classsq~ uq~ AHT5>p[QtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$25.classsq~ uq~ aIq~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$950.classsq~ uq~ ><쯠FU<݅xtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/TrampolineClosure.classsq~ uq~ rr?y@)ZtK/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/Bindable.classsq~ uq~ )k'OFtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryBooleanExpressionHelper.classsq~ uq~ ٯ*7}}mHtP/home/blackdrag/coding/groovy/18/target/classes/groovy/text/TemplateEngine.classsq~ uq~  "l?u^w:=te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/VariableExpression.classsq~ uq~ @.y@Ertq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$BlockRecorder.classsq~ uq~ VhZYasDtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/CSTNode.classsq~ uq~ zw#I.tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$QueryCommand.classsq~ uq~ X)—kR׽نtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$955.classsq~ uq~ 1 7JKY/tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/ExtensionMethodNode.classsq~ uq~ o~~3YutN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyObject.classsq~ uq~ X,.7KZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$326.classsq~ uq~ NφIe+l1\o^tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ExpandedVariable.classsq~ uq~ 9: K%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$105.classsq~ uq~ պ"d*z?]tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1040.classsq~ uq~ K#e 4*it^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference$2.classsq~ uq~ plq7Mtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorMetaMethodSite.classsq~ uq~ /\zGwIA\tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$3.classsq~ uq~ xk3 dPrՓtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MixinNode.classsq~ uq~ )ͯ[kE^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$242.classsq~ uq~ q(JC\~/֢td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log4j$Log4jLoggingStrategy.classsq~ uq~ 7d NƫD)e"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$170.classsq~ uq~ #(jt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyDoc.classsq~ uq~ )=a VFL*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$566.classsq~ uq~ h!4<ڡ{9tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex$Entry.classsq~ uq~ *gu}dG7tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/StaticTypesTransformation.classsq~ uq~ X֤w[M`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$493.classsq~ uq~ :KvkN6؎ujtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1017.classsq~ uq~ SG)kc'2Bt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ConstructorNode.classsq~ uq~ KwQġ(:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$419.classsq~ uq~ Dz -htY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$446.classsq~ uq~ _]/)"Et`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedField.classsq~ uq~ 7F҇=̑t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/DgmConverter.classsq~ uq~ 2tE3!8{JxMtM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ObjectRange.classsq~ uq~ *ƒE-Ϫ.th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/SourceExtensionHandler.classsq~ uq~ bMMScmztg/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$SimpleTemplate$1.classsq~ uq~ CH{c.^tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$40.classsq~ uq~ `\I]Ptl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMap$Segment.classsq~ uq~ Ǔ{ hitZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1054.classsq~ uq~ ND_ q4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$471.classsq~ uq~ ϴ#! /tj/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxSelectedElementBinding.classsq~ uq~ 컐.SqytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$737.classsq~ uq~ fYqA sSy7ytf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$6.classsq~ uq~  *GUCR1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$605.classsq~ uq~ "Fv4ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$143.classsq~ uq~ =nx,`R?rt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrap.classsq~ uq~ +/۲`SײwptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$330.classsq~ uq~ V)i8uzITtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/StringCachedClass.classsq~ uq~ {7K3)Sr_t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ %+!jADu'th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/SourcePrinter.classsq~ uq~ UYCFwaatc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/LoopingStatement.classsq~ uq~ y]PPtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1039.classsq~ uq~ 3="m:\ftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$691.classsq~ uq~ FhDȩG]޼tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$455.classsq~ uq~ !H+sU>'V'(tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/DoubleCachedClass.classsq~ uq~ sӚf/Iztq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableMethod.classsq~ uq~ S :fɅ %&6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$308.classsq~ uq~ t͝KJYtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovydoc$1.classsq~ uq~  ajucz /$+@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$345.classsq~ uq~ *^Ւ .@J]dtR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass$3.classsq~ uq~ ^xJq%QwÏ)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$430.classsq~ uq~ u{^ASmDti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypesMarker.classsq~ uq~ 85A#gʤ@>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$625.classsq~ uq~ *\mO@ |bywt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType.classsq~ uq~ YD۳`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$766.classsq~ uq~  /Bf@vltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$590.classsq~ uq~ S63˨0FOtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$90.classsq~ uq~ {\yUtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.classsq~ uq~ $6N!K*}tF/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Lazy.classsq~ uq~ {Ilm&t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/VerifyClass$2.classsq~ uq~ DRNƈntY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$556.classsq~ uq~ '!< lg#Yt[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ChangeType.classsq~ uq~ V2EŃC뉊d[,tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.classsq~ uq~  2>fF5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$792.classsq~ uq~ p9drʀ!tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1047.classsq~ uq~ 969Gt]/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTableProperties$2.classsq~ uq~ IL`s^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$642.classsq~ uq~ qkTT B?jt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/Reflector.classsq~ uq~ RuQCdtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$4.classsq~ uq~ !`(#3j_ڊtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$StateStackElement.classsq~ uq~ tIf%JtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$31.classsq~ uq~ Xtx^E'Z]t|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor$ConstructedClassWithPackage.classsq~ uq~ QLoJc:tO/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonTokenType.classsq~ uq~ O2{[/.Y|tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$UpdateStrategy.classsq~ uq~ bq!ONGtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1001.classsq~ uq~ K\(S|-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$272.classsq~ uq~ ݫHL\}7tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.classsq~ uq~ ߈>dHtL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange$1.classsq~ uq~ =; Su$ҝtX/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingMethodException.classsq~ uq~ xA⾚~ 6_tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/PropertyNode.classsq~ uq~ X`A;rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$720.classsq~ uq~ ]i8h2R6*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$951.classsq~ uq~ /dHJ/@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$43.classsq~ uq~ +1ڨ2c[ytd/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTextComponentTextBinding.classsq~ uq~ >98ֽEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$911.classsq~ uq~ V"meeztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$631.classsq~ uq~ "D &*?-tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$30.classsq~ uq~ vXL0 1k\et[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/RootLoaderRef.classsq~ uq~ u1tg+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$502.classsq~ uq~ sH? Y˾tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassVisitorHelper.classsq~ uq~ fK-Y۷tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/FloatingPointMath.classsq~ uq~ WoE9œ6tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSiteAwareMetaMethod.classsq~ uq~ P d?ti/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$GetBeanMethodMetaProperty.classsq~ uq~ c"_Yu2itY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$413.classsq~ uq~ ?! SϰqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$954.classsq~ uq~ @ADT-CtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$108.classsq~ uq~ G$6Fuv7^tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding$EventTriggerFullBinding$1.classsq~ uq~ MI̥s\1AntX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$36.classsq~ uq~ ]$3X ~d tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AutoCloneASTTransformation.classsq~ uq~ ( w䗅Qtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$3.classsq~ uq~ )kb̰t_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSpinnerProperties$1.classsq~ uq~ j}DM;9ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureStaticMetaMethod.classsq~ uq~ ] jNP37RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$124.classsq~ uq~ 1 q~q"'YtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$52.classsq~ uq~  ƢQltM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Interceptor.classsq~ uq~  5oK?LY:tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1041.classsq~ uq~ @*X$#pastK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadMap.classsq~ uq~ i钟r6Z tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$307.classsq~ uq~ Hs^KBYtF/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Eval.classsq~ uq~ ɍ{ qtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ShortCachedClass.classsq~ uq~ Pf2)SXBtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$49.classsq~ uq~ -?1(~dH tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$118.classsq~ uq~ x&/6@ndsts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/FileSystemResourceManager.classsq~ uq~  ~Sb yzUtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$646.classsq~ uq~ M!b_Rm)ltW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingClassException.classsq~ uq~ A_:έtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/AggregateBinding.classsq~ uq~ ,_CFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$283.classsq~ uq~ FB&nn獥cftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$757.classsq~ uq~ S"30TY$.te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredAttributes$1.classsq~ uq~ y!qh9!{tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/IO$Verbosity.classsq~ uq~ #EcM(2*:t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoMetaMethodSiteNoUnwrapNoCoerce.classsq~ uq~ V0Oy Fpstn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod$Proxy.classsq~ uq~ rb[tPXtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MopWriter$MopKey.classsq~ uq~ [j5( GytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$826.classsq~ uq~ >t :t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$8.classsq~ uq~ PFq!C` tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$851.classsq~ uq~ 嘆҄[0͉]*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$902.classsq~ uq~ l$Sr( WJt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/VariableScope.classsq~ uq~ 06cqSztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$260.classsq~ uq~ ~4Y^5ːUTtg/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/TemplateServlet$TemplateCacheEntry.classsq~ uq~ VX[>},tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$949.classsq~ uq~ D \Cژu0tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/SpreadExpression.classsq~ uq~ ac3hN@^tW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingFieldException.classsq~ uq~ kbx lk(td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$10.classsq~ uq~ VTճAU4md6tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$77.classsq~ uq~ .Xk5sγtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$18.classsq~ uq~ 6Ȗ ^*AtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1029.classsq~ uq~ /г}&\Ro;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$137.classsq~ uq~ 0pEgvti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$1.classsq~ uq~  9+ղtU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$6.classsq~ uq~ [ $Ŝ"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$341.classsq~ uq~ ʚ upn'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$980.classsq~ uq~ bf2j84tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$705.classsq~ uq~ +KkR0 dtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$15.classsq~ uq~  +Vtf (Mm*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$635.classsq~ uq~ `T_=(;tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$ChangeType.classsq~ uq~ FF YWIWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$183.classsq~ uq~ #3e'3RtX/home/blackdrag/coding/groovy/18/target/classes/groovy/time/DatumDependentDuration.classsq~ uq~ >$V[mty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ThreadManagedMetaBeanProperty.classsq~ uq~ mCP:|RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$966.classsq~ uq~ Y@[^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$919.classsq~ uq~ p93YxߏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$956.classsq~ uq~ ID@$4ǩt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ wh /ir0to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit$1.classsq~ uq~ J($w,K?$(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$551.classsq~ uq~ >PSNQ]tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor.classsq~ uq~ 9cf*JZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$896.classsq~ uq~ >ax}vttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$427.classsq~ uq~ 5R\:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$371.classsq~ uq~ psqc}'r=ztc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/HScrollableTextPane.classsq~ uq~ K8Цjt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite$StaticMetaMethodSiteNoUnwrap.classsq~ uq~ ki`uNA2;ʕ etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$460.classsq~ uq~ wڷ[4̹,Qt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GroovyClassVisitor.classsq~ uq~ KofMz4CB"tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod$DgmMethodRecord.classsq~ uq~ Ptg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/InvocationWriter.classsq~ uq~  z!W% te/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractButtonProperties$1.classsq~ uq~ ? 9Xk4q tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/PojoWrapper.classsq~ uq~ tz[nt|H1tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1020.classsq~ uq~ w6>BS Tte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/gse/DependencyTracker.classsq~ uq~ ѹn _.tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/FloatWrapper.classsq~ uq~ ^[ly}ydHt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.classsq~ uq~ IEn77*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$482.classsq~ uq~ DW }\tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1027.classsq~ uq~ H1SEZsEt[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attributes.classsq~ uq~ DcttD/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlParser.javasq~uq~ 'h%Δ X,HtP/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MissingClassException.javasq~uq~  pl'L/]th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/LongCachedClass.javasq~uq~ szG\,w*tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/TraversalHelper.javasq~uq~ g%1yLetd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/ProtectionStorage.javasq~uq~  E/+lZ, t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/RangeExpression.javasq~uq~ DO49^8@!tG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GrabResolver.javasq~uq~ QֻRGC#TtJ/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Commons.javasq~uq~ eSʠvۊGf8tV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/FullBinding.javasq~uq~ i00 [tq/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ClassMetaClassGetPropertySite.javasq~uq~ <=XOtUXti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v6/PluginDefaultGroovyMethods.javasq~uq~ 4l sb>Y~utG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyObject.javasq~uq~ ~WoʼQqL+tI/home/blackdrag/coding/groovy/18/src/main/groovy/model/PropertyModel.javasq~uq~ / ]ȇLia~1ht`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyAnnotationRef.javasq~uq~ eMݎD[%ntP/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovydoc.javasq~uq~ X)T\8X4'yj)stM/home/blackdrag/coding/groovy/18/src/main/groovy/servlet/TemplateServlet.javasq~uq~ Kis!I\t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/AntlrASTProcessSnippets.javasq~uq~ Fw|f7/-1!tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/StringCachedClass.javasq~uq~ 4_oev#tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/CodeVisitorSupport.javasq~uq~ tAWzFR.tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ReferenceManager.javasq~uq~ t Tdƥt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/TypeChooser.javasq~uq~ U%س@ stC/home/blackdrag/coding/groovy/18/src/main/groovy/text/Template.javasq~uq~ I!Ϫ,ѝWtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/ReadWriteLockASTTransformation.javasq~uq~ +:x2É\~-ht[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/OptimizerVisitor.javasq~uq~ 7Z׈:޵ʮntI/home/blackdrag/coding/groovy/18/src/main/groovy/xml/dom/DOMCategory.javasq~uq~ [8p0W̓d|tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AbstractASTTransformation.javasq~uq~ [EDU5K_Htw/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayPutAtMetaMethod.javasq~uq~ 78cKa "pRGt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/ClosureTriggerBinding.javasq~uq~ jGi!RĻgtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/PropertyChangeProxyTargetBinding.javasq~uq~ Bl+E2Ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/LRUCache.javasq~uq~ OВ#q`H5tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ConstructorMetaClassSite.javasq~uq~ uqp"}tQ/home/blackdrag/coding/groovy/18/src/main/groovy/time/DatumDependentDuration.javasq~uq~ pb,8yt]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/InnerClassVisitor.javasq~uq~ ˤRoJ2tL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/PackageScope.javasq~uq~ beӹChMT$\RtM/home/blackdrag/coding/groovy/18/src/main/groovy/model/DefaultTableModel.javasq~uq~ [7bH@D-t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/UnaryPlusExpression.javasq~uq~ auyE_Ntl/home/blackdrag/.gradle/caches/artifacts-4/antlr/antlr/c12498cf18507aa6433a94eb7d3e77d5/jars/antlr-2.7.7.jarsq~uq~ 5,RƥYedt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/parser/GroovyLexer.javasq~uq~ XC4BTHuU`:/t/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ant/ant-launcher/c12498cf18507aa6433a94eb7d3e77d5/jars/ant-launcher-1.8.2.jarsq~uq~ >9z Ttc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ElvisOperatorExpression.javasq~uq~ |s~tN >B{t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ReverseListIterator.javasq~uq~ f9-YvgtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Category.javasq~uq~ u cB0t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/AssertStatement.javasq~uq~ YsǠ \*t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/DummyClassGenerator.javasq~uq~  ǃIwֽ<= tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ProcessingUnit.javasq~uq~ '`]=^u*v.1`tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ListExpression.javasq~uq~ YWSj}l*tE/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlSlurper.javasq~uq~ X5ޅ /Kw[tJ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/PropertyReader.javasq~uq~ ny5+Sp?ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/DummyCallSite.javasq~uq~ ]b.9D~%msѲ tu/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayGetAtMetaMethod.javasq~uq~ ƜޖYv&th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/MethodCallerMultiAdapter.javasq~uq~ C$` f7i1+ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodeCollector.javasq~uq~ w`,hota/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/EnumCompletionVisitor.javasq~uq~ O tn~D(@tA/home/blackdrag/coding/groovy/18/src/main/groovy/grape/Grape.javasq~uq~ JgۍQ@Ct`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/NumberAwareComparator.javasq~uq~ R٨ tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/SourceBinding.javasq~uq~ `C4Kղ~ڞth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/TransformMetaMethod.javasq~uq~  24_WϺtg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/GroovyObjectWrapper.javasq~uq~ E8a_mltZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MetaClassHelper.javasq~uq~ >{>E!LtQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyBugError.javasq~uq~ i ~c*ǹV*extb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaCompilerFactory.javasq~uq~ x|y>'1tg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/LRUProtectionStorage.javasq~uq~ J YW܋pڋAtp/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.javasq~uq~ ` y2tr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayPutAtMetaMethod.javasq~uq~ ;:(S]tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/tools/GenericsUtils.javasq~uq~ 5?0D Cn tL/home/blackdrag/coding/groovy/18/src/main/groovy/lang/TrampolineClosure.javasq~uq~ Pj$շat]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/TryCatchStatement.javasq~uq~ L0ͮΜx'etB/home/blackdrag/coding/groovy/18/src/main/groovy/util/Factory.javasq~uq~ O= GUt_Qt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodePrinter.javasq~uq~ VJ 8]~_t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/parser/GroovyRecognizer.javasq~uq~ MmiuutU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/StringHelper.javasq~uq~  ^T q$tm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/IndexedPropertyASTTransformation.javasq~uq~ d;Tk5 ïr"z9tY/home/blackdrag/coding/groovy/18/src/main/groovy/lang/IllegalPropertyAccessException.javasq~uq~ tv/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/SourceTextNotAvailableException.javasq~uq~ E#SZYjQth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/NewStaticMetaMethod.javasq~uq~ M/JZptk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/BooleanCachedClass.javasq~uq~ |DO}gZptQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/FastArray.javasq~uq~ 1;m(*G|]t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/BytecodeExpression.javasq~uq~ (}G$Cn՗ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/DeclarationExpression.javasq~uq~ YZ'mltN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyInterceptable.javasq~uq~ 3 1k'ǏltO/home/blackdrag/coding/groovy/18/src/main/groovy/transform/IndexedProperty.javasq~uq~ [U+;(d"th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/AssertionRenderer.javasq~uq~ pUG DŏTtW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ParserPlugin.javasq~uq~ {|@fiPw~tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/VisitorAdapter.javasq~uq~  s9$tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaMethod.javasq~uq~ o9+_F-Rt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/FlushingStreamWriter.javasq~uq~ ) Iz/tI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ProxyMetaClass.javasq~uq~ d@4p9p\g+9wtW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/EnumVisitor.javasq~uq~  Pk?q6~'4t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/FileSystemCompiler.javasq~uq~ FXoA__Titc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassGeneratorException.javasq~uq~ Fu5Fu8tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/CompileTaskSupport.javasq~uq~ _h1BsHWqtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/GroovyASTTransformation.javasq~uq~ xW.pt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ReturnStatement.javasq~uq~ eNH8MtVYti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMetaMethod.javasq~uq~ I-8.^'u tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassGenerator.javasq~uq~ zJb l)V ڤti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter.javasq~uq~ Q˝Rctr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MissingMethodExceptionNoStack.javasq~uq~ _;J'gk2itD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClass.javasq~uq~ HjxP^tH/home/blackdrag/coding/groovy/18/src/main/groovy/xml/FactorySupport.javasq~uq~ #AJdN=t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BytecodeHelper.javasq~uq~  T3a] 0tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/RootLoaderRef.javasq~uq~ s_~WGKr@t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaCompiler.javasq~uq~ Qb0m*e܇tQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/Phases.javasq~uq~ {zAm%0tU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/NullObject.javasq~uq~ j>CߓV1yt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/JavaTokenTypes.javasq~uq~ ; *#BtK/home/blackdrag/coding/groovy/18/src/main/groovy/io/PlatformLineWriter.javasq~uq~ gOC&gtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/MultipleCompilationErrorsException.javasq~uq~ W %~3oyDti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoInterceptableSite.javasq~uq~ M.O1ftQ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/DefaultPropertyReader.javasq~uq~ #(ѡ5}.WR@tW/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadMapEvaluatingException.javasq~uq~ ʻQSKޠ>ltg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.javasq~uq~ 5:t yX`tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/TriggerBinding.javasq~uq~ Q)*?͘tO/home/blackdrag/coding/groovy/18/src/main/groovy/text/SimpleTemplateEngine.javasq~uq~ юAI[ЌzȐ&Y6 tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/EmptyStatement.javasq~uq~ ή d(A㾺3td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/ExceptionMessage.javasq~uq~ E vt+۔WÚPftg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.javasq~uq~ lfGL)'Ht`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BytecodeVariable.javasq~uq~ `Jb{tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/PackageScopeASTTransformation.javasq~uq~ ìt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ConversionHandler.javasq~uq~ %Q+%t^/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/FilteredNodeChildren.javasq~uq~ x$!Ϗ5YHDs tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.javasq~uq~ PN?CNw9?t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/URLReaderSource.javasq~uq~ @UQo˳t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/Value.javasq~uq~ 9,Ѯ lS]'ztJ/home/blackdrag/coding/groovy/18/src/main/groovy/util/ScriptException.javasq~uq~ _ߤn `tI/home/blackdrag/coding/groovy/18/src/main/groovy/text/TemplateEngine.javasq~uq~ 2p.uldtO/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayoutRow.javasq~uq~ _3j0sqM/t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/InterfaceHelperClassNode.javasq~uq~ ,u itY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ManagedLinkedList.javasq~uq~ V)`11syotb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.javasq~uq~ HY?D{SeF;tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyException.javasq~uq~  NdyK_s[4b_htQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Numbers.javasq~uq~ }rs^;tH/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Slf4j.javasq~uq~ R(/ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultMethodKey.javasq~uq~ Ȃ|E*r: ht[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/SqlGroovyMethods.javasq~uq~ ({m'T?+tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ClassHelper.javasq~uq~ U}:\eጰt]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ContinueStatement.javasq~uq~ xI2\˧* ]t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DateGroovyMethods.javasq~uq~ ƿ0 i/ gtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/GenericsType.javasq~uq~ wx(Ų6ertF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ObjectRange.javasq~uq~ e&pe:jStV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/UberCompileTask.javasq~uq~ C+OR tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/ParserException.javasq~uq~ 9n;ݧ2jt@/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Range.javasq~uq~ }C>PXZtQ/home/blackdrag/coding/groovy/18/src/main/groovy/transform/EqualsAndHashCode.javasq~uq~ ;RM=Q|H\t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/BytecodeInstruction.javasq~uq~ |RqRp5tE/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaMethod.javasq~uq~ |ĭؑ7F:tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ComposedClosure.javasq~uq~ (&6jo`@2ItT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/VariableScope.javasq~uq~ A$bxzxNJVQ>tp/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassGetPropertySite.javasq~uq~ ~aEIt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/ClosureSourceBinding.javasq~uq~ *_.v(Utj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTemplateEngine.javasq~uq~ wn'z:`tL/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayout.javasq~uq~ ?=w֕l tM/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/Main.javasq~uq~ 'PjqJOUK@t_/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassRegistryChangeEventListener.javasq~uq~  wer31gtp/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-tree/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-tree-3.3.1.jarsq~uq~ ETs~tK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ClosureException.javasq~uq~ ̷ӿ0"tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/NewInstanceMetaMethod.javasq~uq~ P, j8ktU/home/blackdrag/coding/groovy/18/src/main/groovy/beans/VetoableASTTransformation.javasq~uq~ z6Ku@ADtj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.javasq~uq~ B`0QX#X:YVtO/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Types.javasq~uq~ 2aC_$M9tN/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovyc.javasq~uq~  .Zb>P.#te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassSite.javasq~uq~ .u]tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedClass.javasq~uq~ %$q"ڊ4tC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Writable.javasq~uq~ ,'#ݡTtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/NullWriter.javasq~uq~ 0o~ -8P,tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/CurriedClosure.javasq~uq~ HOzI k1tm/home/blackdrag/.gradle/caches/artifacts-4/jline/jline/c12498cf18507aa6433a94eb7d3e77d5/jars/jline-0.9.94.jarsq~uq~ F#\w o$qD7td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/DelegatingController.javasq~uq~ f!ٚϕ,@c,ext[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ConvertedClosure.javasq~uq~ YO1*UPTT5u/tB/home/blackdrag/coding/groovy/18/src/main/groovy/util/OrderBy.javasq~uq~ w9W"+MA{٩'GStN/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ASTNode.javasq~uq~ ȳYmwKTj_!t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/CharWrapper.javasq~uq~ d쵡tth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/AnnotationConstantExpression.javasq~uq~  H-̩,9tte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AbstractASTTransformUtil.javasq~uq~ Qmh#XBtO/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/Variable.javasq~uq~ wty8a&׆ctF/home/blackdrag/coding/groovy/18/src/main/groovy/util/NodePrinter.javasq~uq~ pwUK4;OtL/home/blackdrag/coding/groovy/18/src/main/groovy/util/ClosureComparator.javasq~uq~  .vS4m@t@/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Mixin.javasq~uq~ <&+rKdب7tU/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/GPathResult.javasq~uq~ =dy+Ati/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.javasq~uq~ ul/Jt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/LoopingStatement.javasq~uq~ 7jgdwt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/RuntimeParserException.javasq~uq~ GtfE/yF6jtL/home/blackdrag/coding/groovy/18/src/main/groovy/json/StringEscapeUtils.javasq~uq~ @1dccOQzKjtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/IntRange.javasq~uq~  .]8ѺC;tU/home/blackdrag/coding/groovy/18/src/main/groovy/beans/BindableASTTransformation.javasq~uq~ N"ӣR-nItV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyDoc.javasq~uq~ =0vY?7tG/home/blackdrag/coding/groovy/18/src/main/groovy/time/BaseDuration.javasq~uq~ ̵= +y!CtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ForStatement.javasq~uq~ 9ϑoHẂPAtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MethodSelectionException.javasq~uq~ !\h^'yYtK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/ExpandoMetaClass.javasq~uq~ *,  tE/home/blackdrag/coding/groovy/18/src/main/groovy/sql/InParameter.javasq~uq~ 44WNwtI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyCallable.javasq~uq~ U+r'K@˜%tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/StaticTypesTransformation.javasq~uq~ D̏:hKO_tT/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JTableProperties.javasq~uq~ 7J>OBf8"t|/home/blackdrag/.gradle/caches/artifacts-4/commons-cli/commons-cli/c12498cf18507aa6433a94eb7d3e77d5/jars/commons-cli-1.2.jarsq~uq~ ܮ? 3;⌞tG/home/blackdrag/coding/groovy/18/src/main/groovy/sql/CallResultSet.javasq~uq~ L+n>D/ ltc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/ConstructorSite.javasq~uq~ |tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/ObjectCachedClass.javasq~uq~ KU'([t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/FileReaderSource.javasq~uq~ j~RHtP/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/TableLayoutCell.javasq~uq~ ~E,L qt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.javasq~uq~ BJFg4N xt\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/LoaderConfiguration.javasq~uq~ `'gp!t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ClosureExpression.javasq~uq~ uf1?WȧtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/RootLoader.javasq~uq~  D]1+.tO/home/blackdrag/coding/groovy/18/src/main/groovy/util/PermutationGenerator.javasq~uq~ zEOL΅lhtD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Singleton.javasq~uq~ ^p򷍎DtG/home/blackdrag/coding/groovy/18/src/main/groovy/grape/GrapeEngine.javasq~uq~ b!, cIyart[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/XmlGroovyMethods.javasq~uq~ /eP\wtA/home/blackdrag/coding/groovy/18/src/main/groovy/io/FileType.javasq~uq~ |\o>E=ztI/home/blackdrag/coding/groovy/18/src/main/groovy/util/ProxyGenerator.javasq~uq~ Yck=b׋tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ArrayUtil.javasq~uq~ F?v8{ btX/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JComponentProperties.javasq~uq~ GTskZvIftU/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JSliderProperties.javasq~uq~ 磙cH DGt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/GroovyCategorySupport.javasq~uq~ Xإˁktf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaAwareResolveVisitor.javasq~uq~ @-`|AxӤmw Xt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/UnaryMinusExpression.javasq~uq~ \$_>@tStv/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-commons/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-commons-3.3.1.jarsq~uq~ ] 1ؕ$otf/home/blackdrag/.gradle/caches/artifacts-4/asm/asm/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-3.3.1.jarsq~uq~ 蕓$$VBt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/InvocationWriter.javasq~uq~ \rvtC/home/blackdrag/coding/groovy/18/src/main/groovy/util/NodeList.javasq~uq~ !T 2!O\YC^t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/typehandling/LongMath.javasq~uq~ (NYJR߫OtV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/ConstructorNode.javasq~uq~ ),DꬾfRv>tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MethodPointerExpression.javasq~uq~ hwe_p7Y%jtZ/home/blackdrag/coding/groovy/18/src/main/groovy/sql/BatchingPreparedStatementWrapper.javasq~uq~ mk9F' t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.javasq~uq~ A;ғeg:t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/AggregateBinding.javasq~uq~ nRbG6tL/home/blackdrag/coding/groovy/18/src/main/groovy/util/GroovyCollections.javasq~uq~ vأ(G iZ f@htr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ThreadManagedMetaBeanProperty.javasq~uq~ D.N%t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.javasq~uq~ n)xtA/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Script.javasq~uq~ <Ey꘷M6?@tF/home/blackdrag/coding/groovy/18/src/main/groovy/util/logging/Log.javasq~uq~ J 'IuEt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilerConfiguration.javasq~uq~ LE v,tX/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadListEvaluatingException.javasq~uq~ jI:I0G݀ ItB/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Binding.javasq~uq~ Uz\1:tR/home/blackdrag/coding/groovy/18/src/main/groovy/transform/PackageScopeTarget.javasq~uq~ e[JO؈$]tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/SynchronizedASTTransformation.javasq~uq~  Ә0btF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Interceptor.javasq~uq~ ?)n#.KxNtG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovySystem.javasq~uq~ ߰ZG$&Ht@th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.javasq~uq~ 8S OSQQtD/home/blackdrag/coding/groovy/18/src/main/groovy/xml/SAXBuilder.javasq~uq~ ؍"Q':J&tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedField.javasq~uq~ T+\Ţ/tw/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayGetAtMetaMethod.javasq~uq~ `@V}KtK/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaBeanProperty.javasq~uq~ ~;I THwkZty/home/blackdrag/.gradle/caches/artifacts-4/org.fusesource.jansi/jansi/c12498cf18507aa6433a94eb7d3e77d5/jars/jansi-1.7.jarsq~uq~ U7mߏoTZtb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/VariableSlotLoader.javasq~uq~ 8fm6=>ftX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/TokenException.javasq~uq~ S,d`=b\tV/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JSpinnerProperties.javasq~uq~ O[&\`tk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/typehandling/GroovyCastException.javasq~uq~  ,?gB %g=>tH/home/blackdrag/coding/groovy/18/src/main/groovy/lang/PropertyValue.javasq~uq~ EYg- &඿xtX/home/blackdrag/coding/groovy/18/src/main/groovy/swing/binding/JScrollBarProperties.javasq~uq~ B_[}֦At]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/TernaryExpression.javasq~uq~ nF<:LBdtR/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaArrayLengthProperty.javasq~uq~ OS|M$"xtG/home/blackdrag/coding/groovy/18/src/main/groovy/model/ValueHolder.javasq~uq~ K[)()bjte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.javasq~uq~ f\ ڊ! tG/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaProperty.javasq~uq~ ]{-<⺘ItV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/DynamicVariable.javasq~uq~ m.ApЦ9tU/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/DgmConverter.javasq~uq~ ZuF`*wOt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/ByteWrapper.javasq~uq~ [F)YCt첈 tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/StaticVerifier.javasq~uq~ Q݉v>ש^-e[Jt^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/EventTriggerBinding.javasq~uq~ ?g[tV?tl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/FileSystemResourceManager.javasq~uq~ hh6Zv!tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/Memoize.javasq~uq~ coW7A3 a tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v5/TestNgUtils.javasq~uq~ E5tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/FileScanner.javasq~uq~ LSiQ艼tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ClassCompletionVerifier.javasq~uq~ N In+|ۗ tD/home/blackdrag/coding/groovy/18/src/main/groovy/json/JsonToken.javasq~uq~ q\+r@t4gږtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/CachedClosureClass.javasq~uq~ <&|VtR/home/blackdrag/coding/groovy/18/src/main/groovy/sql/GroovyResultSetExtension.javasq~uq~ z)HҕTtL/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyClassLoader.javasq~uq~ N ٩jYQY ta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/MockOutputTool.javasq~uq~  `ɴRyu'tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/AnnotatedNode.javasq~uq~ nVSϒC>td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex.javasq~uq~ UŔ%5'1tJ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/PropertyWriter.javasq~uq~ Otx>Ͳ~ts/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayGetAtMetaMethod.javasq~uq~ DI)r9X3tX/home/blackdrag/coding/groovy/18/src/main/groovy/grape/GrabAnnotationTransformation.javasq~uq~ /UٱAtF3tS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/EnumHelper.javasq~uq~ srapM Ft[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyClassDoc.javasq~uq~ -wa<1ؐtY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/MopWriter.javasq~uq~ <;O4 55yth/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v6/PluginStaticGroovyMethods.javasq~uq~ :/ehQeqtQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/MethodNode.javasq~uq~ SR4moLR\t]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/AsmClassGenerator.javasq~uq~ ޾ndniti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.javasq~uq~ Q)Șkaxtl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap.javasq~uq~ *x١0W<_Ltb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.javasq~uq~ j()s9tT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/vmplugin/v7/Java7.javasq~uq~ 7ʊQUmoV^|tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/ClassLoaderForClassArtifacts.javasq~uq~ :Ҥ?f|tS/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeChild.javasq~uq~ Q2p]Y:tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaExpandoProperty.javasq~uq~  +Bs~o4ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/FloatCachedClass.javasq~uq~ F <,,FA6atF/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GrabExclude.javasq~uq~ ?..΍%tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/DoubleKeyHashMap.javasq~uq~ V*-"&tT/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/Attributes.javasq~uq~ 240= utn/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.javasq~uq~ ~]sW4AπNtq/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ivy/ivy/c12498cf18507aa6433a94eb7d3e77d5/jars/ivy-2.2.0.jarsq~uq~ '9\wkh +tq/home/blackdrag/.gradle/caches/artifacts-4/org.apache.ant/ant/c12498cf18507aa6433a94eb7d3e77d5/jars/ant-1.8.2.jarsq~uq~ cY@(PZzN t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/binding/MutualPropertyBinding.javasq~uq~ (O/ާ/.Gtf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/CategoryASTTransformation.javasq~uq~ HT “M!dotJ/home/blackdrag/coding/groovy/18/src/main/groovy/io/GroovyPrintWriter.javasq~uq~ 2Jz6-x/utS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/ListHashMap.javasq~uq~ Dp A@2tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/JavaLexer.javasq~uq~ ˯ԞRD#Eht]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/OutputTool.javasq~uq~ BlP2y[t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/Visitor.javasq~uq~ Lo!_tI/home/blackdrag/coding/groovy/18/src/main/groovy/transform/Canonical.javasq~uq~ _e VSte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/UnicodeLexerSharedInputState.javasq~uq~ bN:TTb'2'/>tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilePhase.javasq~uq~ )vy)RtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/java/Groovifier.javasq~uq~ ^QK*eFtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/NewifyASTTransformation.javasq~uq~ x꘮99np5te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.javasq~uq~ k"xi[Ư{6 %+tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/GroovyObjectSupport.javasq~uq~ _P;)ƢlotX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/GroovyCodeVisitor.javasq~uq~ ${ºg4+=o1tV/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/ErrorReporter.javasq~uq~ f{g0/Vytg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyFieldDoc.javasq~uq~ x,>R R4ĄagtV/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeChildren.javasq~uq~ P=p Itg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.javasq~uq~ fP1:%tp/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-util/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-util-3.3.1.jarsq~uq~ &I73&ԙAQMtI/home/blackdrag/coding/groovy/18/src/main/groovy/util/XmlNodePrinter.javasq~uq~ L Jr~=td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus.javasq~uq~ Z~dL/mtj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/customizers/SecureASTCustomizer.javasq~uq~ E>~zy2Stb/home/blackdrag/coding/groovy/18/src/main/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder.javasq~uq~ U᧿e htk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/CallSiteAwareMetaMethod.javasq~uq~ -= jiSPte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/CompilationFailedException.javasq~uq~ x_@ bjt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/TokenMismatchException.javasq~uq~  d#Ch(B6ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.javasq~uq~ xr'wtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/io/ReaderSource.javasq~uq~ `aX%r(y?RyZtl/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryObjectExpressionHelper.javasq~uq~ ىp7s'uRM te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ConstructorCallExpression.javasq~uq~ >w9P݌tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/LocatedMessage.javasq~uq~ Tg#U](""nbtW/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassRegistryChangeEvent.javasq~uq~ jXwk%MP\StT/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MethodKey.javasq~uq~ fy=9j69Vt/home/blackdrag/.gradle/caches/artifacts-4/com.thoughtworks.xstream/xstream/c12498cf18507aa6433a94eb7d3e77d5/jars/xstream-1.4.1.jarsq~uq~ 1N-Iᴯ@w`it\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ExtendedVerifier.javasq~uq~ AuBzD>t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/PropertyExpression.javasq~uq~ goZ,RLRp#tN/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/Node.javasq~uq~ 剄SyA.6-t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/FileSystemCompilerFacade.javasq~uq~ 4Py(PJtQ/home/blackdrag/coding/groovy/18/src/main/groovy/beans/DefaultPropertyWriter.javasq~uq~ 1P RUZtx/home/blackdrag/.gradle/caches/artifacts-4/asm/asm-analysis/c12498cf18507aa6433a94eb7d3e77d5/jars/asm-analysis-3.3.1.jarsq~uq~ n{&putP/home/blackdrag/coding/groovy/18/src/main/groovy/swing/impl/ClosureRenderer.javasq~uq~ -D0)Wx0ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/ExternalGroovyClassDoc.javasq~uq~ +SxlKH"BtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/syntax/Reduction.javasq~uq~ VJnC|jԴptK/home/blackdrag/coding/groovy/18/src/main/groovy/servlet/GroovyServlet.javasq~uq~ Z3a<|@y0>%tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/ThrowStatement.javasq~uq~ [ 1rB+Xӕ\tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/xml/DomToGroovy.javasq~uq~ NL{gf|tP/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MissingFieldException.javasq~uq~ +%,HKtk/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryFloatExpressionHelper.javasq~uq~ p=9֑ӏtC/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Sequence.javasq~uq~ DqZ"`Jpҷtg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.javasq~uq~ H $$bڼ{`|1t_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedConstructor.javasq~uq~ fťLNti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/FlatNodeListTraversal.javasq~uq~  S $B=v th/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader.javasq~uq~ gT<LPt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ArrayExpression.javasq~uq~ U/t J)tQ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/Reference.javasq~uq~ N S#` tN/home/blackdrag/coding/groovy/18/src/main/groovy/lang/DelegatingMetaClass.javasq~uq~ L< Q螥CtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/CastExpression.javasq~uq~ =oeQgV8tS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/util/Finalizable.javasq~uq~ >եF PXtf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/messages/SyntaxErrorMessage.javasq~uq~ ~g0Ja`۸Ktu/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayPutAtMetaMethod.javasq~uq~  UPݲq_r tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/Logger.javasq~uq~ ѣu1NMRtn/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayPutAtMetaMethod.javasq~uq~ R_T8etf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit.javasq~uq~ 6s MAЮ3ۖtT/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NoChildren.javasq~uq~ $i jإst\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/PrefixExpression.javasq~uq~ /id5P6td/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/AbstractCallSite.javasq~uq~ 0EE!QkgK6渫t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/GeneratedClosure.javasq~uq~ ڻHh~dt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/GroovyExceptionInterface.javasq~uq~ LY'Ipta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/powerassert/SourceText.javasq~uq~ K:_'ѕ[۝te/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/NodeAsHTMLPrinter.javasq~uq~ 2aU;:煪t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.javasq~uq~ p<7ɐBtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/CharacterCachedClass.javasq~uq~ >msڗ3itX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/GenerateStubsTask.javasq~uq~ ,Oj2?%O zt_/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/memoize/MemoizeCache.javasq~uq~ n%@^DEStj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/BinaryLongExpressionHelper.javasq~uq~ 3A)tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/GroovySourceToken.javasq~uq~ ua/G'HŌtY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/CaseStatement.javasq~uq~ >x CY`tY/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MapExpression.javasq~uq~ Eg6 'JH tg/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/AutoCloneASTTransformation.javasq~uq~ M'rIaf#_tI/home/blackdrag/coding/groovy/18/src/main/groovy/sql/GroovyResultSet.javasq~uq~ 0%ZBM2h$Xta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/FileOutputTool.javasq~uq~ D=E%)J{ t@/home/blackdrag/coding/groovy/18/src/main/groovy/util/Proxy.javasq~uq~ y S -tb/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/LazyASTTransformation.javasq~uq~ FM#$ީt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/MethodCallExpression.javasq~uq~ -Hm CtN/home/blackdrag/coding/groovy/18/src/main/groovy/inspect/swingui/TableMap.javasq~uq~ )W]\)ܓΝtq/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/MissingMethodExecutionFailed.javasq~uq~ o_1 tR/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/CompileUnit.javasq~uq~ q~& p$tt/home/blackdrag/.gradle/caches/artifacts-4/xmlpull/xmlpull/c12498cf18507aa6433a94eb7d3e77d5/jars/xmlpull-1.1.3.1.jarsq~uq~ WrrP4"t\/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/asm/OperandStack.javasq~uq~ KJԨooOtS/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/LineColumn.javasq~uq~ +X lū-tZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/StackTraceUtils.javasq~uq~ = P&[ 4.ltH/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MetaClassImpl.javasq~uq~ 2_&dtI/home/blackdrag/coding/groovy/18/src/main/groovy/io/LineColumnReader.javasq~uq~ $P\Q7K>OtZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/CachedMethod.javasq~uq~ < A[:ntc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/transform/stc/UnionTypeClassNode.javasq~uq~ L=KɵtX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/MethodClosure.javasq~uq~ k7V6.4ntr/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayGetAtMetaMethod.javasq~uq~ E҈SvI AtL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/Synchronized.javasq~uq~ c^9yUtO/home/blackdrag/coding/groovy/18/src/main/groovy/lang/BenchmarkInterceptor.javasq~uq~ caF'`7}ڛt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/javac/JavacJavaCompiler.javasq~uq~ 9eʁfltH/home/blackdrag/coding/groovy/18/src/main/groovy/util/IndentPrinter.javasq~uq~ |U&=5zte/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/treewalker/PreOrderTraversal.javasq~uq~ ,[d0tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite.javasq~uq~ 91qtC/home/blackdrag/coding/groovy/18/src/main/groovy/time/Duration.javasq~uq~ ΉS ɩjt`JtB/home/blackdrag/coding/groovy/18/src/main/groovy/lang/Closure.javasq~uq~  πn]88 tW/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/classgen/ReturnAdder.javasq~uq~ J*&c~BP!D\tX/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/ClassExtender.javasq~uq~ aѤu..(ktL/home/blackdrag/coding/groovy/18/src/main/groovy/transform/WithReadLock.javasq~uq~ Gg'gq[rta/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/ExpressionTransformer.javasq~uq~ fꛥ#DEtV/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/NodeIterator.javasq~uq~  އ|].xAtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/metaclass/ReflectorLoader.javasq~uq~ ^M`q6w!tj/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/stdclasses/NumberCachedClass.javasq~uq~ ݇5r#ktP/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/FieldNode.javasq~uq~ @\Q"mt`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.javasq~uq~ cms",q tf/home/blackdrag/coding/groovy/18/src/main/groovy/xml/streamingmarkupsupport/StreamingMarkupWriter.javasq~uq~ 'ރqh%tI/home/blackdrag/coding/groovy/18/src/main/groovy/lang/MapWithDefault.javasq~uq~ /h'tc/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/shell/util/SimpleCompletor.javasq~uq~ Y:_}|&紅t`/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.javasq~uq~ Ոiɮ$ӢdtH/home/blackdrag/coding/groovy/18/src/main/groovy/io/FileVisitResult.javasq~uq~ +>9!t[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/expr/EmptyExpression.javasq~uq~ m`;<%Ytm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePogoFieldSite.javasq~uq~ 1}%jwvGtm/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyConstructorDoc.javasq~uq~  u]e\=ntM/home/blackdrag/coding/groovy/18/src/main/groovy/transform/WithWriteLock.javasq~uq~ xQM~pt[/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/antlr/ASTParserException.javasq~uq~ ͡p ^:mu3tt/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayPutAtMetaMethod.javasq~uq~ epk 9HQ[tY/home/blackdrag/coding/groovy/18/src/main/groovy/util/slurpersupport/ReplacementNode.javasq~uq~ HA1d ~̇+tf/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/groovydoc/GroovyExecutableMemberDoc.javasq~uq~ h7=Y ' dtd/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/ASTTransformationsContext.javasq~uq~  eL]tE/home/blackdrag/coding/groovy/18/src/main/groovy/lang/EmptyRange.javasq~uq~ Qז:T#A%tD/home/blackdrag/coding/groovy/18/src/main/groovy/lang/SpreadMap.javasq~uq~ ;$h  /ti/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayMetaMethod.javasq~uq~ t.E op_stM/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ant/Groovy.javasq~uq~ fPQUSLXdtM/home/blackdrag/coding/groovy/18/src/main/groovy/xml/MarkupBuilderHelper.javasq~uq~ ||aJktZ/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/ast/stmt/BreakStatement.javasq~uq~ >p#8`{t^/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/control/StaticImportVisitor.javasq~uq~  }.Ut]/home/blackdrag/coding/groovy/18/src/main/org/codehaus/groovy/reflection/ReflectionUtils.javasq~uq~ n@OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$985.classsq~ uq~ Ha[BR od9t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayPutAtMetaMethod.classsq~ uq~ Qw+ZVrQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$100.classsq~ uq~ ƲhhnAitc/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredAttributes.classsq~ uq~ ` gh*mt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/JavaLexer.classsq~ uq~ }p}OiB҄to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite.classsq~ uq~ 5X-͵ء! ;tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$8.classsq~ uq~ tg~wanaL94tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMapBase$Segment.classsq~ uq~ ՖxP>HѩCt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GroovyCodeVisitor.classsq~ uq~ pw鹒W&a^Qtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$1.classsq~ uq~ G#N-?aOt`/home/blackdrag/coding/groovy/18/target/classes/groovy/security/GroovyCodeSourcePermission.classsq~ uq~ PKcTR1 tN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaProperty.classsq~ uq~ *s otT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/GroovyServlet$1.classsq~ uq~ %ɘntr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ReadWriteLockASTTransformation.classsq~ uq~ 7x"뺈1O tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AntBuilderLocator.classsq~ uq~ o&A~4/tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$DoubleInteger.classsq~ uq~ oWw.'6Xtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LazyClassLoaderRef.classsq~ uq~ {4◆30(Ltm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.classsq~ uq~ ͂~[z{!tc/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$CreatePreparedStatementCommand.classsq~ uq~ /&E?x֯t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ X(,N5sh̿@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$73.classsq~ uq~ #CV*vltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$327.classsq~ uq~ U&zd ~4ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap$Entry.classsq~ uq~ F2#̜Ht_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSpinnerValueBinding.classsq~ uq~ Ԏ[zy"tX/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$1.classsq~ uq~ kո =O;R ktu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongFloat.classsq~ uq~ G2'4f!etN/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/MarkupBuilder.classsq~ uq~ e41jmJ/vFta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ListExpression.classsq~ uq~ ȃ٥R3`StHtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AutoCloneASTTransformation$1.classsq~ uq~ F꽿[gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$658.classsq~ uq~ -!+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$997.classsq~ uq~ "Ow4td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementClearedEvent.classsq~ uq~  RH=bGEata/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/BatchingPreparedStatementWrapper.classsq~ uq~ ͺ՞"*ʜt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$4.classsq~ uq~ ꥁ/ |61tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$462.classsq~ uq~ MCAQctl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.classsq~ uq~ g g׽30,{$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$894.classsq~ uq~ s>eR|tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$ThreadedReferenceManager.classsq~ uq~ {Frtޙ]tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/messages/Message.classsq~ uq~ ClKG@ tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindingUpdatable.classsq~ uq~ e%ayFtM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodeBuilder.classsq~ uq~ ""_6dUtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$5.classsq~ uq~ JX؈VZcth5B tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$74.classsq~ uq~ .5fFlSt`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$3.classsq~ uq~ :w1М!ȓtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$210.classsq~ uq~ W-)D5Rtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/FileSystemCompiler$1.classsq~ uq~ Lj&tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/StringReaderSource.classsq~ uq~ $M:gV ZBәtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/IFileNameFinder.classsq~ uq~ ϭ-'fղg t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/IfStatement.classsq~ uq~ ^ak9VptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$794.classsq~ uq~  PT=UhMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$257.classsq~ uq~ U&KbE[t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/Java6.classsq~ uq~ &x`2 tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.classsq~ uq~ 6!U OaPtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AbstractASTTransformation.classsq~ uq~ YTmъQFdtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$208.classsq~ uq~ Lʷ̋XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$127.classsq~ uq~ E:M r6tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$28.classsq~ uq~ eovLzDF[0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$245.classsq~ uq~ oYȔ;%Ctv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$IntegerLong.classsq~ uq~ ISb>ڥptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$169.classsq~ uq~ >Y)!N<Qw tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleFloat.classsq~ uq~ 4B$tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePojoFieldSite.classsq~ uq~ 5cp*tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$4$1.classsq~ uq~ ^{* n$ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.classsq~ uq~ +2& HAF#^ixtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$146.classsq~ uq~ `+R[/gt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/SyntaxException.classsq~ uq~ ߋV\>WXEz@tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite.classsq~ uq~ M&"!td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$PropertyRemovedEvent.classsq~ uq~ u>Ӵ.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$554.classsq~ uq~ K?cC&*P"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/Phases.classsq~ uq~  ĘkoVhtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$517.classsq~ uq~ W†`cIkPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$736.classsq~ uq~ IQBNRytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$503.classsq~ uq~ }4#4,6>outh/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod.classsq~ uq~ Kӽj@ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ArgumentListExpression.classsq~ uq~ \8p;B t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask.classsq~ uq~ `%,N'lt{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$PrimaryClassNodeOperation.classsq~ uq~ 꺎-G$krta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$1.classsq~ uq~ .C\s!1tO/home/blackdrag/coding/groovy/18/target/classes/groovy/util/IndentPrinter.classsq~ uq~ 65Y_,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$988.classsq~ uq~   _k/W itY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$619.classsq~ uq~ E|32FZ!th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/AssertionWriter$1.classsq~ uq~ WNztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$106.classsq~ uq~ -{a gVtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/NullCallSite.classsq~ uq~ ܺӸK -WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$695.classsq~ uq~ .Ѣo3K?Z8+t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MopWriter.classsq~ uq~  V=#_t`Rtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewInstanceMetaMethod.classsq~ uq~ yjdtg_ -tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$36.classsq~ uq~ `0g,SOttz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerInteger.classsq~ uq~   Q#btX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$21.classsq~ uq~ Y oXٻKRAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$812.classsq~ uq~ P7qetZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/FileIterator.classsq~ uq~ ~54MPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$113.classsq~ uq~ 8nxUd窶yjQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$937.classsq~ uq~ WC 1NU#R3t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$11.classsq~ uq~ %8гz Sb^\tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply.classsq~ uq~ y\ :4tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/LRUCache.classsq~ uq~ MDptx t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrap.classsq~ uq~ _{҇@i%aWtL/home/blackdrag/coding/groovy/18/target/classes/groovy/time/Duration$1.classsq~ uq~ .SKIל8T3 t\/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSliderProperties.classsq~ uq~ 27[ot{ቩdt\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChild$1.classsq~ uq~ c -^];u[~ZtV/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/Main$1.classsq~ uq~ ƚ<ΣtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$912.classsq~ uq~ P.";tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$216.classsq~ uq~ (?ˢKߩwIth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods$1.classsq~ uq~ ZP+3p;J%7tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePogoFieldSite.classsq~ uq~ McㇸtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$683.classsq~ uq~ f֪;9QtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$485.classsq~ uq~ ˌe[&/vs-tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$4.classsq~ uq~ 'X{gEqt_/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$XmlWritable.classsq~ uq~ E˦\֟+5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$212.classsq~ uq~ ?ey},-XtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$8.classsq~ uq~ Qk $Fomti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/NumberMath.classsq~ uq~ F:X-Ztq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ObjectCachedClass.classsq~ uq~ H]5HNrtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassLoaderForClassArtifacts.classsq~ uq~ 'ǮPJvd1DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$523.classsq~ uq~ ŮhZ;Cta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$6.classsq~ uq~ ͯyRS&Åt_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$1.classsq~ uq~ > m~*0iM#>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$165.classsq~ uq~ 0BU.dtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/FastArray$1.classsq~ uq~ >gu$4vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$962.classsq~ uq~ ]}g 1h*+AtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$33.classsq~ uq~ ndOmKR-EtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$714.classsq~ uq~ ~A&ڹcE6tX/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/DefaultPropertyReader.classsq~ uq~ j+,\y6t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$ValueIterator.classsq~ uq~ wӌ|5Ld t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$4.classsq~ uq~ E8agdܝ]tc/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$ServletOutput$2.classsq~ uq~ !4tZ3tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LazyCachedClassRef.classsq~ uq~ zbc $tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeExpression$1.classsq~ uq~ l)ފ B:ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$699.classsq~ uq~ kӃyeO~t[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NoChildren.classsq~ uq~ }o./r\oqtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/AntProjectPropertiesDelegate.classsq~ uq~ {fYtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$407.classsq~ uq~ )`|`$*"5jtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/LongMath.classsq~ uq~ S[*v0ڵ#th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$4.classsq~ uq~ kuJJIﵻ5Vt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SqlGroovyMethods$ResultSetMetaDataIterator.classsq~ uq~ oTׁD92tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$404.classsq~ uq~ 8t9|P WWtT/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovy.classsq~ uq~ clUl*`K6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$191.classsq~ uq~  &f!Lt_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$2.classsq~ uq~ 2Y4uRYtCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$138.classsq~ uq~ s쏑񈢯cqtc/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$ServletOutput$1.classsq~ uq~ c}$kJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$572.classsq~ uq~ Ul16y~tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/PreJava2GroovyConverter.classsq~ uq~ ^LkIM_ VVtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$130.classsq~ uq~ #y\LC,LtN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GrabResolver.classsq~ uq~ yOJ$?J-tO/home/blackdrag/coding/groovy/18/target/classes/groovy/model/ClosureModel.classsq~ uq~ ckSoJst/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryCharExpressionHelper.classsq~ uq~ ѩu#m-oytZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1007.classsq~ uq~ :4ɝ \dt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/RegexSupport.classsq~ uq~ KR`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$615.classsq~ uq~ $F+ttj=tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/StaticMethodCallExpression.classsq~ uq~ 'l`;p otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$644.classsq~ uq~ bGO;dt\/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/VetoableASTTransformation.classsq~ uq~  У1x(VYtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.classsq~ uq~ }N3Bj)1tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OperandStack.classsq~ uq~ efh6.tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedDoubleKeyMap$EntryWithValue.classsq~ uq~ [ǂlދgxztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$652.classsq~ uq~ Tdj tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$916.classsq~ uq~ B.0Πn56tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$1$1.classsq~ uq~ ~iLnUd~%kQ?[t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/HasCleanup.classsq~ uq~ C׼ƄAބhtU/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoCloneStyle.classsq~ uq~ O/(OUeSaEc%vtn/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultIdentifierResolver.classsq~ uq~ >ӻ6Odtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongFloat.classsq~ uq~ P )\ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubGenerator$1.classsq~ uq~ 6 겡 Ǥ*gvtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ASTTransformationsContext.classsq~ uq~ ӳZӪp`t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/WritableFile.classsq~ uq~ ^z}Wit^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceBundle.classsq~ uq~ aTȹts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl$1.classsq~ uq~ \\ˣ_( 7<9ht_/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$XmlTemplate.classsq~ uq~ eɥHp>Wtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/PackageScopeASTTransformation.classsq~ uq~ M-c( c.} t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/GroovyStarter.classsq~ uq~ ctDZTB†tX/home/blackdrag/coding/groovy/18/target/classes/groovy/inspect/swingui/TableSorter.classsq~ uq~ I %Ib76It_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ClassExtender.classsq~ uq~ (f#htn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$2.classsq~ uq~ h_tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/Wrapper.classsq~ uq~ ޏWn, Y3ltX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$46.classsq~ uq~ f}nEv<-KQtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$LabelRange.classsq~ uq~ (C t_`a89tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$398.classsq~ uq~  }Tܷ+a|]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$247.classsq~ uq~ ]щl3>9]tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$ProgressCallback.classsq~ uq~ bo+uQ tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaClassSite.classsq~ uq~ ꪳTf})l~Ӵ; tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$634.classsq~ uq~ 鼙@*tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/LongWrapper.classsq~ uq~ @֗d{StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$465.classsq~ uq~ svH\J ɮC[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$317.classsq~ uq~ Y"QҪOPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$109.classsq~ uq~ CTzV}[ FZ::տtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$140.classsq~ uq~ ۧ閌1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$994.classsq~ uq~ ԇ?fzz`!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$385.classsq~ uq~ gL+Vē?tT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaObjectProtocol.classsq~ uq~ (?zlC_tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap.classsq~ uq~ 6_[utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$656.classsq~ uq~ ;lMrOptj/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$SubClassDefiningClosure.classsq~ uq~ =}7#[.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$809.classsq~ uq~ A֫|@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$982.classsq~ uq~ hm8 1^OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$301.classsq~ uq~ qjkEvntG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$21.classsq~ uq~ maQ~ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$767.classsq~ uq~ ֒jr^dte/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/Builder$Built.classsq~ uq~ CE]9n'tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableField.classsq~ uq~ 1}ťISXZzjRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$347.classsq~ uq~ jș(>G=tU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$1.classsq~ uq~ ۈH_]s tU/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyResultSetProxy.classsq~ uq~ m$>Uj &htY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$682.classsq~ uq~  o&nfB#t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryShortExpressionHelper.classsq~ uq~ r0*;E=WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$104.classsq~ uq~ 16W]]itG/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Mixin.classsq~ uq~ ҋAŸ1Dotj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/SimpleCompletor.classsq~ uq~ <[H ift_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/DoubleKeyHashMap.classsq~ uq~ mmC쵀vtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ContinueStatement.classsq~ uq~  3! <:!zϐtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$494.classsq~ uq~ W&g2^$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$194.classsq~ uq~  }>y# 91z@v~tT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/TemplateServlet.classsq~ uq~ TH933בO{]NtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$787.classsq~ uq~ !A;oG%Rtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$Pair.classsq~ uq~ gNx\gbOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$890.classsq~ uq~ _i◳`X0^ohwbtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ElvisOperatorExpression.classsq~ uq~ RM?_'T!Ztv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$GroovyClassOperation.classsq~ uq~ -äI8steڵMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$753.classsq~ uq~  b0O0oI.0tm/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/StreamingMarkupWriter.classsq~ uq~ ;=Ĝ݅'ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ClassGenerator.classsq~ uq~ "rGymcktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$746.classsq~ uq~ ,/HPϨDDFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$876.classsq~ uq~ T:ǰ&̯ytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$653.classsq~ uq~ QQ?}>ލtth/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$StaticDefiningClosure.classsq~ uq~ (qx@%xtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationFailedException.classsq~ uq~ zQ4š2(+/%tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MethodSelectionException.classsq~ uq~ rʛtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$87.classsq~ uq~ u^2MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$600.classsq~ uq~  ȉ4sQT8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$684.classsq~ uq~ 7agkqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$200.classsq~ uq~ eoE$g IAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$487.classsq~ uq~ ݻ>lg'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$533.classsq~ uq~ Wrc ObcCftj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSiteArray$1.classsq~ uq~ K/db{(y冽tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaCompiler.classsq~ uq~ cQ 8A%OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$524.classsq~ uq~ ; ^QYXi0tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/builder/AstBuilderTransformation.classsq~ uq~ V<3*>tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$91.classsq~ uq~ Ggv/! ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$745.classsq~ uq~ Sr`&M=stY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$185.classsq~ uq~ }WLֱN=3t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$PropertyEvent.classsq~ uq~ }`Bhtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/EnumConstantClassNode.classsq~ uq~ 4Pš C;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$397.classsq~ uq~  RȻر9ǟ9tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$2.classsq~ uq~ #q9DHtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$436.classsq~ uq~ HyVG i atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$921.classsq~ uq~ ~HѥtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$936.classsq~ uq~ ͒<$y|tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureTriggerBinding.classsq~ uq~ [n@em?Z|tM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log.classsq~ uq~ D]m1셃babd.tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LogASTTransformation$LoggingStrategy.classsq~ uq~ /3y;8qeth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/DeclarationExpression.classsq~ uq~ j#:]Z^te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassCodeVisitorSupport.classsq~ uq~ ok[ݳ@73|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$961.classsq~ uq~ &ؠ9'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$241.classsq~ uq~ P~ɜ?3[tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1024.classsq~ uq~ 9f~v|=vbt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$NormalMethodChooser.classsq~ uq~ .d5pzL˘ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$411.classsq~ uq~ 4¾uaChXtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite.classsq~ uq~ m̓PcWː,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$672.classsq~ uq~ `/[uEtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/AdaptingMetaClass.classsq~ uq~ ; *־wtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$181.classsq~ uq~ q6ˎBtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$218.classsq~ uq~ kF̚3gjhD!tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$2.classsq~ uq~ $&\mˏ1Hqt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference.classsq~ uq~ x?+;#yf7;tP/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoClone.classsq~ uq~  ;}&7 VctZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1050.classsq~ uq~ FA*tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$70.classsq~ uq~ 6gEn63&4#td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$2$1.classsq~ uq~ YHjѨU|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$439.classsq~ uq~ \<֥r5z\t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/LoggingHelper.classsq~ uq~ | ;LytR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$11.classsq~ uq~ 3piL8LB t~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/Memoize$SoftReferenceMemoizeFunction.classsq~ uq~ ҕh8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$899.classsq~ uq~ +m gts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor$1.classsq~ uq~ R2`ġ!NMhUsUte/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$GetMethodMetaProperty.classsq~ uq~ coPratt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$LongDouble.classsq~ uq~ ([㹲D]+tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$7.classsq~ uq~ v󼶦a~'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$349.classsq~ uq~ qjćkf2td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods.classsq~ uq~ _PT"4htb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap$1.classsq~ uq~  =dD!9tG/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Range.classsq~ uq~ "cvz#I-êtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$476.classsq~ uq~ cڑ+ ptT/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/Main.classsq~ uq~ f]?? tP/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyRowResult.classsq~ uq~ 4BOWltZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1032.classsq~ uq~ X~膷|tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1013.classsq~ uq~ ].-V!Z 3ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/BooleanWrapper.classsq~ uq~ ޶٣\!StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$725.classsq~ uq~ , -\3rto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor$LowerCaseClass.classsq~ uq~ 9e ˻}tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$57.classsq~ uq~ x .ɅȄ Y8tL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/EmptyRange.classsq~ uq~ W/FT5Uߩ%tV/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/impl/TableLayoutRow.classsq~ uq~ p(NhStY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$733.classsq~ uq~ "(f^MI))tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$387.classsq~ uq~ [[ <[ӘEFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$563.classsq~ uq~ A`P o:tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/EmptyExpression.classsq~ uq~ ~ވr@t1 1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$362.classsq~ uq~ Зcx۹)t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$HashIterator.classsq~ uq~ GElTskΨtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoInterceptableSite.classsq~ uq~ P0ԃ`}tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindingProxy$ModelBindingPropertyBinding.classsq~ uq~ >v1VتGt]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementEvent.classsq~ uq~ ^IW0P]h}tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap$EntryIterator.classsq~ uq~ w3^??pD3Bh"Wtg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredNodeChildren$2.classsq~ uq~ sU6RrݳtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$702.classsq~ uq~ :C=d9+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$187.classsq~ uq~ s?B@N`motY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$591.classsq~ uq~  uc ܗWE~)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$265.classsq~ uq~ `#䇿Xܿlta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/Memoize.classsq~ uq~ 3Ҳ5[Ni th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ConfigurationException.classsq~ uq~ #x/Fjffth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/DoubleWrapper.classsq~ uq~ 3U3wD tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/DefaultPropertyAccessor.classsq~ uq~ 4ЄȜk &Ctb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$NodeReference.classsq~ uq~ 6=ƚ BZft[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v4/Java4.classsq~ uq~ s<{t}i,tP/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MapWithDefault.classsq~ uq~ p PKq$Itk/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassRegistry$MetaClassCreationHandle.classsq~ uq~ WlW RDtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/JavaTokenTypes.classsq~ uq~ } tF/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Grab.classsq~ uq~ ƠTJ{tI/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString.classsq~ uq~ U(&t"Tt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/StringHelper.classsq~ uq~ pXe3{J߹RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$713.classsq~ uq~ bg [z9tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$2$1.classsq~ uq~ P7dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$128.classsq~ uq~ E6tNCltZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1003.classsq~ uq~ ޝŕojqAtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$DoubleDouble.classsq~ uq~ EO4PMtH/home/blackdrag/coding/groovy/18/target/classes/groovy/grape/Grape.classsq~ uq~ }Ȍ,zyOto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ByteCachedClass.classsq~ uq~ Bbءtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedMethod$1.classsq~ uq~ 3+Bo tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$616.classsq~ uq~ cȎZ"[e[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$180.classsq~ uq~ ˜j %iPty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer$ImportType.classsq~ uq~ cԓqjte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ReverseListIterator.classsq~ uq~ L;'~ et\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChild$2.classsq~ uq~ ?/ZF|vp 5tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$2.classsq~ uq~ `%[^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$363.classsq~ uq~ +''! l5Itq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader$1.classsq~ uq~ P6D엘?UtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1019.classsq~ uq~ vkLn&s c/tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$823.classsq~ uq~ gµ兼(tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyExecutableMemberDoc.classsq~ uq~ ǘcE[qN!atG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$23.classsq~ uq~ gR[cBGtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$697.classsq~ uq~ ݼ=Vփ)Z#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$454.classsq~ uq~ b^@ajMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$420.classsq~ uq~ n/u#u%t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/LabelVerifier.classsq~ uq~ 'Os{dtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/AssertStatement.classsq~ uq~ v E{ˢtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilerConfiguration.classsq~ uq~ =+UźmԲtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$880.classsq~ uq~ `gH5-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$449.classsq~ uq~ -}[hh0#XcFュtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongLong.classsq~ uq~ ֢2RUxJ&tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/MixinInMetaClass$1.classsq~ uq~ )~dimtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$PropertyFullBinding.classsq~ uq~ qqr& C:]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$744.classsq~ uq~ d!쉸`-jtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$33.classsq~ uq~ !o\׉tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$532.classsq~ uq~ us~<&7ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureTriggerBinding$1.classsq~ uq~  a\9tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$85.classsq~ uq~ jlLV86,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$220.classsq~ uq~ 1k1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$381.classsq~ uq~ Gn+^s btY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/VerifyClass.classsq~ uq~ kAj=s#HC4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$796.classsq~ uq~ C6+SetY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$703.classsq~ uq~ T4l$RZtP/home/blackdrag/coding/groovy/18/target/classes/groovy/io/LineColumnReader.classsq~ uq~  gLu)Ity/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationCollectorCodeVisitor.classsq~ uq~ S-a; 0;>}Ҏtt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$5.classsq~ uq~ G WV;Ry(%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$574.classsq~ uq~ ۪` zHr2t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/FactoryInterceptorMetaClass.classsq~ uq~ ,b_~ g0tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$6.classsq~ uq~ RۛM2prZo#>tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor$4.classsq~ uq~ mu UotQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$932.classsq~ uq~ +sJ٘RkptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$447.classsq~ uq~ Tr*cktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$435.classsq~ uq~ s~aiphEts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$LongFloat.classsq~ uq~ CځPta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/BlockStatement.classsq~ uq~ ݋!-Vo`to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MethodCallerMultiAdapter.classsq~ uq~ [Mg?'$! te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BytecodeHelper.classsq~ uq~ vgTI xta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/CastExpression.classsq~ uq~ s}_I mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$195.classsq~ uq~ 7nzZ8[)tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Reduction.classsq~ uq~ Q(`:U*fvMto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.classsq~ uq~ O 9tT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$3.classsq~ uq~ Dg*pXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$448.classsq~ uq~ i@#&ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$335.classsq~ uq~ hp=B*`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$156.classsq~ uq~ iqd$ZEz2tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$4.classsq~ uq~ B$CDtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$841.classsq~ uq~ ֬ KEtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap$Segment.classsq~ uq~ t5ZV'yG7iwyvtW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ClosureInvokingMethod.classsq~ uq~ uyڄH׹5wtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$72.classsq~ uq~ 2/ev#tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ImportNode.classsq~ uq~ 13N^J6A.tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1008.classsq~ uq~ ;F 2UÚho tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/io/GroovyPrintStream.classsq~ uq~ sxo¾^x0{_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/FileScanner.classsq~ uq~ #_/VQ6tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyProgramElementDoc.classsq~ uq~ g2gĴtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$167.classsq~ uq~ {!,iԻ2̈́tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$316.classsq~ uq~ _*N&VA¬tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/PluginDefaultGroovyMethods.classsq~ uq~ $bb 9$/5t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding$EventTriggerFullBinding.classsq~ uq~ @ͫWdktZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1037.classsq~ uq~ AZ :b-e&tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaProperty.classsq~ uq~ +lR-*/;WCtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$CategoryMethod.classsq~ uq~ u5ǣF[>9~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$450.classsq~ uq~ 74qE~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$340.classsq~ uq~ G/"_9qtL/home/blackdrag/coding/groovy/18/target/classes/groovy/model/FormModel.classsq~ uq~ ;ű||dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$981.classsq~ uq~  uvP6B5 t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/Statement.classsq~ uq~ OWEwgy0bkVti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/VariableSlotLoader.classsq~ uq~ ӝ B B1[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$872.classsq~ uq~ [BPBҐ柺tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/NamespaceBuilder.classsq~ uq~ ^>@O #ǽtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/CategoryASTTransformation.classsq~ uq~ ,PEwtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaProperty$2.classsq~ uq~ ;!δyY>itm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$NullObject.classsq~ uq~ \Ьb8 Mt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v7/Java7.classsq~ uq~ =%&*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$114.classsq~ uq~ Dp#~[OKTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$622.classsq~ uq~ (,0rtN/home/blackdrag/coding/groovy/18/target/classes/groovy/time/TimeCategory.classsq~ uq~ 84+f)ԗ[4t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference$1.classsq~ uq~ EgP'Zc$tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyAnnotationRef.classsq~ uq~ %$NSLtJCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$150.classsq~ uq~  ~l4 ~N?ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewMetaMethod.classsq~ uq~ TŽ&l2YgtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyCodeSource$1.classsq~ uq~ V*4Rtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ExpressionStatement.classsq~ uq~ u~~R*=TtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$933.classsq~ uq~ T5t6Z 3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$879.classsq~ uq~ Vm9Rf?tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass$2.classsq~ uq~ ai3wP4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$315.classsq~ uq~ R]wFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$318.classsq~ uq~  IhOqk t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod$AnonymousMetaMethod.classsq~ uq~ p EUfktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$606.classsq~ uq~ 5w_. F¹ItX/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/NamespaceBuilderSupport.classsq~ uq~ pDn] ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatLong.classsq~ uq~ [)>N$ t[/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange$IntRangeIterator.classsq~ uq~ D/+kZw|m]>tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite.classsq~ uq~ 5]Ega~}b>ktn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedMethod$MyComparator.classsq~ uq~ #~ګENtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$1.classsq~ uq~ I֤ PhtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$13.classsq~ uq~ aOM^0RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$915.classsq~ uq~ &ܟ&HtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$735.classsq~ uq~ |[y-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$154.classsq~ uq~ I@"-xta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$3.classsq~ uq~ Iht`N t[/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$CreateStatementCommand.classsq~ uq~ Zb|ȩ_Â;h-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$663.classsq~ uq~ 80VntF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$6.classsq~ uq~ uJp6_H1ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$354.classsq~ uq~ a i "Rtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$2.classsq~ uq~ dmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$987.classsq~ uq~ ůeBvއ+{Ut]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyTag.classsq~ uq~ ^CwP(W0rt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ReturnAdder$1.classsq~ uq~ !ӑ8lvytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$640.classsq~ uq~ ]Ƽƚ};v2Vtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/DelegatingController.classsq~ uq~ %}=ވ^tS/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/Synchronized.classsq~ uq~ V¬pt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayGetAtMetaMethod.classsq~ uq~ ű@nôOJz1t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer$SecuringCodeVisitor.classsq~ uq~ Π,Ptr#ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/ResourceManager.classsq~ uq~ Q&1Ik&ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/messages/WarningMessage.classsq~ uq~ nIY@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$878.classsq~ uq~ bp/ratd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator.classsq~ uq~ &M*>>p tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$655.classsq~ uq~ B_а^d $tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.classsq~ uq~ (}$v:Wytt@/home/blackdrag/coding/groovy/18/target/classes/META-INF/dgminfosq~ uq~ dM$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$309.classsq~ uq~ ` B 2!wtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1018.classsq~ uq~ ^A3 K 8Mftf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$MixedInAccessor$2$1.classsq~ uq~ dgd}Ĥtr/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document.classsq~ uq~ ^IYLt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/gse/StringSetMap.classsq~ uq~ bcIsٛs4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$148.classsq~ uq~ .kqtpȄkta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/WhileStatement.classsq~ uq~  /QW:7Yt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$7.classsq~ uq~ Ȱ7۲VstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$906.classsq~ uq~ ؋f~L5b mtj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavacCompilerFactory.classsq~ uq~ 9ݫ̗tW/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Node$3.classsq~ uq~ "y}a㡨utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$941.classsq~ uq~ o\c7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$153.classsq~ uq~ aLFEΗ&*ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$870.classsq~ uq~ o֐]%(gxtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$405.classsq~ uq~ 4Y6 I:ys{tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/PowerAssertionError.classsq~ uq~ -=W0mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$555.classsq~ uq~ A$ȟtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/NodeAsHTMLPrinter.classsq~ uq~ R+Nt{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerFloat.classsq~ uq~ Vki|ns tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$613.classsq~ uq~  ~ژ=Z+3GEt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass.classsq~ uq~ ߝ݃qtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$5.classsq~ uq~ (f .ʌ-WgEtK/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/Vetoable.classsq~ uq~ ]8|CHJᏙt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$10.classsq~ uq~ <ڐaoZ^%>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$772.classsq~ uq~  _۰.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$542.classsq~ uq~ S462'tk(vtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/BytecodeInterface8.classsq~ uq~ P{ɅWVCntg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/SwingTimerFullBinding.classsq~ uq~ Y(+*:_)&tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/PackageNode.classsq~ uq~ ?A/SA5)tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1042.classsq~ uq~ dK~zltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$628.classsq~ uq~ Iqԥtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeInstruction.classsq~ uq~ կ3קtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$120.classsq~ uq~ !ƝB&JUtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$HardRef.classsq~ uq~ *>4$UAP4i}n!ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap.classsq~ uq~ qe.$:jSo ptJ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodeList.classsq~ uq~ [)"Qw6`tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$PhantomRef.classsq~ uq~ )a*^thtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$620.classsq~ uq~ GzQ|׸rTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$685.classsq~ uq~ +גATtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$348.classsq~ uq~ rМ4[mt5(>tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$22.classsq~ uq~ 4=w]E4&t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/AnnotationNode.classsq~ uq~ d!-m./th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$5.classsq~ uq~ U05 Gd`1tX/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyRuntimeException.classsq~ uq~ N&m%w tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$681.classsq~ uq~ ",cPr/#t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList.classsq~ uq~ 7 zf9TS%!Y2#gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$294.classsq~ uq~ ޫ^W/ڋM{htf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/SingleKeyHashMap$Copier.classsq~ uq~ Eu{Ɇ'tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$4.classsq~ uq~ |q[S$MytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$428.classsq~ uq~ A!LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$414.classsq~ uq~ ]UjcN䷝Mits/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/MetaClassConstructorSite.classsq~ uq~ NY\et[/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ReadOnlyPropertyException.classsq~ uq~ ѦTrG+?-Z!0tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ThreadLocalMapHandler.classsq~ uq~ Sʉ<Dta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit.classsq~ uq~ y)af*X- ftH/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Grapes.classsq~ uq~ ǜEӔe&t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GStringImpl.classsq~ uq~ ]  L1Nɢto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMemberDoc.classsq~ uq~ ֋WV P! ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatFloat.classsq~ uq~ H:'j7X'tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyConstructorDoc.classsq~ uq~ 56H6Ӎ7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$774.classsq~ uq~ HGnQŅ t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/java/Groovifier.classsq~ uq~ 8,h-_yV?tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$5.classsq~ uq~ "J65`+٭`>%ɖtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$441.classsq~ uq~ +4_=%=&ltd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyPackageDoc.classsq~ uq~ d2Ђ=tB2k}tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$LocalMap.classsq~ uq~ 6Ъ69|{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$509.classsq~ uq~ ܉@&8NCn*Itf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$ExpandoMetaProperty.classsq~ uq~ T$(;rH-~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$268.classsq~ uq~ Mz\C1tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/OptimizerVisitor.classsq~ uq~ |-&U%|tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableConstructor.classsq~ uq~ xX kyTtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1.classsq~ uq~ X!:tO/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/InOutParameter.classsq~ uq~ "Ur"Z.tU/home/blackdrag/coding/groovy/18/target/classes/groovy/model/DefaultTableColumn.classsq~ uq~ 6 }b7F6jti/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$ExpandoMetaConstructor.classsq~ uq~ 'g  S]]td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/URLReaderSource.classsq~ uq~ yEifȜfOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$931.classsq~ uq~ u5VIW %tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaClassGetPropertySite.classsq~ uq~ Δh^ʱ͋tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$47.classsq~ uq~ y?n鈮S\(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$234.classsq~ uq~ R'¯߳bj:AtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$27.classsq~ uq~ @M"M ;ZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$101.classsq~ uq~ bNVu>4,tutY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$897.classsq~ uq~ ȔqeO+ <Gth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/SourceText.classsq~ uq~ ,] .ց >r"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$704.classsq~ uq~ jvϘo<t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/LexerFrame$1.classsq~ uq~ !>ۨS\}ލ$tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$4.classsq~ uq~ +SI\ -(W>AtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$675.classsq~ uq~ W+~ڌOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$776.classsq~ uq~ J]3}`MtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$13.classsq~ uq~ zE-40b;_BrXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$431.classsq~ uq~ ^il/| >tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BitwiseNegationExpression.classsq~ uq~ 6LpT ᆎ9tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$453.classsq~ uq~ )0f LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$379.classsq~ uq~ tNJ7zHtr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/IntegerCachedClass.classsq~ uq~ `QB* P#3Iq3tL/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AntBuilder.classsq~ uq~ 26n,K/tT/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder.classsq~ uq~ G0t\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult.classsq~ uq~ o1?C`5Jstr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/UnlimitedConcurrentCache.classsq~ uq~ hqegN4 3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$768.classsq~ uq~  񷲟] ץte/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$SimpleTemplate.classsq~ uq~ e]&h<a_QEotT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/TracingInterceptor.classsq~ uq~ $#FQԪtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$136.classsq~ uq~ E\6 u0ngzt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ ~85$O[EtD/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql.classsq~ uq~ #/Q 4.tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$7$1.classsq~ uq~ [,tXErtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$111.classsq~ uq~ <ZіtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$888.classsq~ uq~ N/"E2Rtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods$ProcessRunner.classsq~ uq~ EK0y*!t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$3.classsq~ uq~ B-&Lqa0tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/NewifyASTTransformation.classsq~ uq~ U.C=tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractSyntheticBinding.classsq~ uq~ X2W/t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMetaMethod$NumberNumberCallSite.classsq~ uq~ .|kv7'Qtp/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ReflectionClassNameResolver.classsq~ uq~ EXOXn{td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MixinASTTransformation.classsq~ uq~ 4 JpptqWtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/ByteWrapper.classsq~ uq~ AU- ͡~`yth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ExpressionTransformer.classsq~ uq~ [>a,tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$707.classsq~ uq~  8\$3Q14;ftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$709.classsq~ uq~ K?D!?tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$14.classsq~ uq~ ,0('tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$14.classsq~ uq~ G<($tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$7.classsq~ uq~ u,ss`"`%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$203.classsq~ uq~ F6d$8Eti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.classsq~ uq~ bz2H4xtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$871.classsq~ uq~ jZz tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$1.classsq~ uq~ YKviQ}񿣨TtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$824.classsq~ uq~ ˾GkAܣ+at`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/CurriedClosure.classsq~ uq~ 'O SR t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ 6ixFBF~utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$857.classsq~ uq~ Z"OlSktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$553.classsq~ uq~ $J𫰀 r-L#d?tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$62.classsq~ uq~ ɏrhEJL>tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaClassSite.classsq~ uq~ =B킍tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$612.classsq~ uq~ 5ZSCO; yta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/BreakStatement.classsq~ uq~ ĴlIDCEtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$56.classsq~ uq~ tSt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/NotExpression.classsq~ uq~ 6j}RL!-atK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClass.classsq~ uq~ _֥xk)Etg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/MutualPropertyBinding.classsq~ uq~ M`;Ɏ7ytS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ResourceException.classsq~ uq~  :y n[=,nta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v5/TestNgUtils.classsq~ uq~ {:EcÔjFtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap.classsq~ uq~ @ myrAIt_/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadListEvaluatingException.classsq~ uq~ ̿-C8ptR/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovySocketServer.classsq~ uq~ CJ^t!H$stc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/SunClassLoader.classsq~ uq~ 6'x]?N-TvrtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$391.classsq~ uq~ 4|Z4i2tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.classsq~ uq~ Lx;*Gʉ$tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/LexerFrame.classsq~ uq~ 5h?yF+M7kB"tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$2.classsq~ uq~ @;0Y!1SBt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer$StatementChecker.classsq~ uq~ >i._\-atp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassCompletionVisitor$1.classsq~ uq~ gB:)tZV tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrASTProcessSnippets.classsq~ uq~  6IͼRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$650.classsq~ uq~  kLTS)ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$559.classsq~ uq~ FR6ftG/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Proxy.classsq~ uq~ nGG[Betc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/BytecodeSequence.classsq~ uq~ ZBV&Nm}}tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1010.classsq~ uq~ bTǢ g2vcxb( t[/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/CompilationUnitAware.classsq~ uq~ R*c+$ʗ-ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ThrowStatement.classsq~ uq~ pE`&{t%XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$510.classsq~ uq~ RiġCΨTT[tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMapBase$Entry.classsq~ uq~ {zjUx)etR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MutableMetaClass.classsq~ uq~ r1:%@D7el=tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$479.classsq~ uq~ 5gJ9l+tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/FileSystemCompiler.classsq~ uq~ Sj.QZ`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$759.classsq~ uq~ ^GMvG#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$161.classsq~ uq~ .&ֵiTeQ$t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NoChildren$1.classsq~ uq~ i^rn S.sRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$459.classsq~ uq~  o=V&ֵtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/FloatCachedClass.classsq~ uq~ MB)F\* "ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/EmptyStatement.classsq~ uq~ 2‰_t ¹ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$729.classsq~ uq~ Q0װybuvtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$26.classsq~ uq~ 6j"c1t~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$ClassNodeSkip.classsq~ uq~ {aN\?Dt~/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$StatementMeta.classsq~ uq~ ,/Ki(k|WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$550.classsq~ uq~ Z"uU.XKcte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/io/FileReaderSource.classsq~ uq~ НS,NDýytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$410.classsq~ uq~ z{ ktU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaExpandoProperty.classsq~ uq~ \9)]U 3bttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$539.classsq~ uq~ "ʗ-w+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$264.classsq~ uq~  pw^n ;{{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$157.classsq~ uq~ `q,#tmUE {S0tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$2.classsq~ uq~ rC֩&tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/ASTHelper.classsq~ uq~ #8ynnʟzӲtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/io/GroovyPrintWriter.classsq~ uq~ e֛lˁth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrParserPluginFactory.classsq~ uq~ i]^`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$927.classsq~ uq~ LO O&eftZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1052.classsq~ uq~ Wj"FUdztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$728.classsq~ uq~ _MZ ;72tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$698.classsq~ uq~ S%+~a!D!-th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$1.classsq~ uq~ ',a%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$895.classsq~ uq~ Z);y?ˍtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$839.classsq~ uq~ q2$weZ@t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleDouble.classsq~ uq~ qdÑ^Hk+3tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$88.classsq~ uq~ 2qaC3P#tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$4.classsq~ uq~ ?y\T9mstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$429.classsq~ uq~ 1 7䡠ntZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/SourceInfo.classsq~ uq~ fl~DYdvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$282.classsq~ uq~ sVW,tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$2.classsq~ uq~ MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$514.classsq~ uq~ 쨕ѣ8DE_T >h8ti/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder.classsq~ uq~ !{MP3 stf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/InterfaceHelperClassNode.classsq~ uq~  Z+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$261.classsq~ uq~ Lf'xy2fZ3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$948.classsq~ uq~ PO뉓 zmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$686.classsq~ uq~ .Kfu?it/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptimizeFlagsCollector$OptimizeFlagsEntry.classsq~ uq~ u+oC0!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$818.classsq~ uq~ ?S֧f?H>XtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/Namespace.classsq~ uq~ vkW}؅`rEtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$8.classsq~ uq~ 0ν`^)fVtN/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlSlurper$1.classsq~ uq~ kdQt}FGt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod$MethodClosureMetaMethod.classsq~ uq~ DaJ$Cn rRtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$402.classsq~ uq~ G(x {кRt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerDouble.classsq~ uq~  @B2&&Dhvtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$5.classsq~ uq~ OZtUH7jtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$756.classsq~ uq~ GDW < Rt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$5.classsq~ uq~ uLJ߿{ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v5/JUnit4Utils.classsq~ uq~ iFSñ~Ke(t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$1.classsq~ uq~ c[\M/( )]t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$4.classsq~ uq~ UQl0E;wjtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MethodCaller.classsq~ uq~ Qּ 1 sj;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$624.classsq~ uq~ ._}r9BX 5tV/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/AutoExternalize.classsq~ uq~ wd^T?y`tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$3.classsq~ uq~ !g V<tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$814.classsq~ uq~ dPC4z (t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/DynamicVariable.classsq~ uq~ }o KG#M~tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1028.classsq~ uq~ 3"`<@ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$816.classsq~ uq~ #_y/Jt}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$FastPathData.classsq~ uq~ &;-P@_Xtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/StringBufferWriter.classsq~ uq~ pKWs& ȟtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassNode$MapOfLists.classsq~ uq~ ׽gFz_yA=#tX/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/AbstractHttpServlet.classsq~ uq~ @LV&&|tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/time/DatumDependentDuration$1.classsq~ uq~ me| ˄l!t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$9.classsq~ uq~ @G gbth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/FileOutputTool.classsq~ uq~ P/y.(֤i)tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$23.classsq~ uq~ _{bMTwtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1004.classsq~ uq~ /~te%ԶtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$426.classsq~ uq~ eagEL%-]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$802.classsq~ uq~ a7n,k iӋt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/GroovyClass.classsq~ uq~ ʈ~b>),3tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$DebugRef.classsq~ uq~  2eJ[67IGutY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$742.classsq~ uq~ N^ӜD˳xtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ExtendedVerifier.classsq~ uq~ ˇ}KOjXtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1030.classsq~ uq~ 'HEۉ+߷C@tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1033.classsq~ uq~ 4ד)8':ʩ/to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/AnnotationConstantExpression.classsq~ uq~ FuMqިrtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$226.classsq~ uq~ _l*~bt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/NullObject.classsq~ uq~ u<Z궱ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$DoubleLong.classsq~ uq~ :磯 `btx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.classsq~ uq~ 0"Bߚbfx:ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedReference$1.classsq~ uq~ nmN t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$2.classsq~ uq~ b3a[tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.classsq~ uq~ 2~B|1iYn{tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$6.classsq~ uq~ "å`䠒OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$817.classsq~ uq~ ~=%5KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$343.classsq~ uq~ XJ/kdtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$275.classsq~ uq~ -tn=׵km9tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$366.classsq~ uq~ ۪p]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$319.classsq~ uq~ g'NÕijtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/FlatNodeListTraversal.classsq~ uq~ Չ558UΟ᷄th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$7.classsq~ uq~ _ͤ;>xcWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$696.classsq~ uq~ azgvQFxՕtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$518.classsq~ uq~ |Ɍ3w; " >ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/VisitorAdapter.classsq~ uq~ D*6Ztw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaClassGetPropertySite.classsq~ uq~ 9DTHM[ tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$38.classsq~ uq~ !xgO2 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$403.classsq~ uq~ HSslLjϻ/t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$CachedMethodComparatorByName.classsq~ uq~ Q,%ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$151.classsq~ uq~ /KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/GroovyException.classsq~ uq~ ٵa 4X'jYt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ s"ygqVatY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$416.classsq~ uq~ YN :txtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$507.classsq~ uq~ <,p($9tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$71.classsq~ uq~ Jv)ujKdWIt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ComplexKeyHashMap.classsq~ uq~ {Qm goRHtb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectFactory.classsq~ uq~ 6z7{Tv%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$917.classsq~ uq~ b -t`/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxProperties$1.classsq~ uq~ qxP{V#2tF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$9.classsq~ uq~ #`B]t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/TripleKeyHashMap.classsq~ uq~ 7dۜZ61tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$706.classsq~ uq~ ;S苶D_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$913.classsq~ uq~ ?>PTd6u⑸tK/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlParser.classsq~ uq~ ŏ^Wl]t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ z"8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$670.classsq~ uq~ ãJةͳìtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$762.classsq~ uq~ r9qP#c䊿btX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$50.classsq~ uq~ @2E'D,nth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$8.classsq~ uq~  ō: /JK\tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$CategoryMethodList.classsq~ uq~ 9O'agP*tH/home/blackdrag/coding/groovy/18/target/classes/groovy/io/FileType.classsq~ uq~ 'eqtf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$4.classsq~ uq~ 3SZEULTtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$1.classsq~ uq~ rֿQ !ktY/home/blackdrag/coding/groovy/18/target/classes/groovy/util/FactoryBuilderSupport$2.classsq~ uq~ FWBXnuMtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$771.classsq~ uq~ N xe}' tR/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/GroovyServlet.classsq~ uq~ 8}HjufgItb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/Visitor.classsq~ uq~ i 8vV`HRj tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$8.classsq~ uq~ Qп6H` 0֠tJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange.classsq~ uq~ 1b{fHXtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$6.classsq~ uq~ 86sunm"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$721.classsq~ uq~ XfՔ ,b5t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ Jr 6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$393.classsq~ uq~  j(&4Rݩth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LogASTTransformation.classsq~ uq~ sE"MtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$160.classsq~ uq~ Kk\v/¶ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$134.classsq~ uq~ 6a0`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$240.classsq~ uq~ ڂERx0˞Q*th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/NodeCollector.classsq~ uq~ 4X/iXCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$898.classsq~ uq~ Pjud/tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/DefaultMetaClassInfo.classsq~ uq~ {ʪ-oExtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$171.classsq~ uq~ :N9sɁjta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$1.classsq~ uq~ L L45F42y`ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/CompilationCustomizer.classsq~ uq~  !1_1mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$907.classsq~ uq~ %Q1"GDt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$13.classsq~ uq~ Pank@dI tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$233.classsq~ uq~ zȩAoWy[8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$561.classsq~ uq~ `2&| %ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$107.classsq~ uq~ 26w.ttS/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/PropertyAccessor.classsq~ uq~ Vf|iV tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$544.classsq~ uq~ Qdu`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$155.classsq~ uq~ V.t/Ij E`te/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTextComponentProperties$1.classsq~ uq~ ֒^FFE0.tT/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletCategory.classsq~ uq~ \-bWrՒ)td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BooleanExpression.classsq~ uq~ 4m.}Z!`ϻtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$999.classsq~ uq~ Q)bJ/ HItX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$83.classsq~ uq~ Dc3"buOth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/IteratorClosureAdapter.classsq~ uq~ ԴP  K/tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyFieldDoc.classsq~ uq~ hAf?ON)yte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformation.classsq~ uq~ YLV!ContZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1006.classsq~ uq~ ? U0nTFHetY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/BatchingStatementWrapper.classsq~ uq~ R.K?1(ltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$350.classsq~ uq~ #.݆tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$1.classsq~ uq~ l=Uf6"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$279.classsq~ uq~ lڸ'z$ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$979.classsq~ uq~ < Δ1&ta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$7.classsq~ uq~ |!@p>KMratY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$119.classsq~ uq~ r0a񩾷D<.tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/PropertyValue.classsq~ uq~ reWԕEd0 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$102.classsq~ uq~ tA^ v^[f2tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/GroovyASTTransformationClass.classsq~ uq~ ==VьAnLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$149.classsq~ uq~ kQ7{隫[lD@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$93.classsq~ uq~ Y|'΢r |ktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$342.classsq~ uq~ 䉸 N tb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementAddedEvent.classsq~ uq~ 5m){q>xtO/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport.classsq~ uq~ ?ub"|x`>]WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$626.classsq~ uq~ f :AqFtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$28.classsq~ uq~ ]q/Sth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethods$3.classsq~ uq~ zXS;+tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$MethodChooser.classsq~ uq~ OaS}}tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/PrefixExpression.classsq~ uq~ {q2?k_t/tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask$JavacAdapter.classsq~ uq~ eC#2_XN9n&tH/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/XmlUtil.classsq~ uq~ ,b/ 4tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovydoc.classsq~ uq~ )o]*t_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/xml/DomToGroovy.classsq~ uq~ Er}XtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$469.classsq~ uq~ ;=/G tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$867.classsq~ uq~ &l ƕetY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$848.classsq~ uq~ UN-9(tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$5.classsq~ uq~ "=Q\_l6]tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attribute.classsq~ uq~ T=IK܋ptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$846.classsq~ uq~ R@Q)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$627.classsq~ uq~ ø)گj!O|t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$KeyIterator.classsq~ uq~ 0'5a St|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$EntrySet.classsq~ uq~ |-7]ruq8tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ProcessGroovyMethods.classsq~ uq~ Y|EĚYL +9Ktf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/ClosureWriter$1.classsq~ uq~ [ uw[MwitQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$4.classsq~ uq~ ]yew !{0tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceManager$ThreadedReferenceManager$1.classsq~ uq~ 12aGFQ%tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/EnumHelper.classsq~ uq~ _.wbn 縲tc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxElementsBinding.classsq~ uq~ gc1څT]tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$267.classsq~ uq~ gP!Vi"TζvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$854.classsq~ uq~ &u8 dn"td/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractJComponentBinding.classsq~ uq~ fuyp=OKxtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/ReturnAdder$ReturnStatementListener.classsq~ uq~ >{{{13ܗtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerFloat.classsq~ uq~ N9Ben`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$727.classsq~ uq~ Z|aAOctU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$3.classsq~ uq~ 9>dx\ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$887.classsq~ uq~ *V'؉F`wtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$14.classsq~ uq~ ѳt) 6etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$596.classsq~ uq~ %0^T tU/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding$1.classsq~ uq~ / XvI"1Xta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JScrollBarValueBinding.classsq~ uq~ ͮJ7|atd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AnnotationVisitor.classsq~ uq~ LVh~m @^w{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$676.classsq~ uq~ Gx*![4htStj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/MethodPointerExpression.classsq~ uq~ QNҋfBitY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$451.classsq~ uq~ u h!~!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$795.classsq~ uq~ [F%M÷tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex$Header.classsq~ uq~ a؈A\&UtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$81.classsq~ uq~ i-13)#FOXZt]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attributes$1.classsq~ uq~ h~9|~|7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$813.classsq~ uq~ -KRG@tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/AsmClassGenerator$1.classsq~ uq~ ?>mtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$4.classsq~ uq~  ̶['~*Ļ9jKtd/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IncorrectClosureArgumentsException.classsq~ uq~ #1b 1,stz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayGetAtMetaMethod.classsq~ uq~ IğNTwktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$832.classsq~ uq~ ϱt/w Rtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatInteger.classsq~ uq~ w)à3b;I[{wta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$5.classsq~ uq~ 2KEtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$17.classsq~ uq~ ="bʎƻ(tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/OwnedMetaClass.classsq~ uq~ @3U59tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap$Segment.classsq~ uq~ 4úיa7ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/GroovySourceToken.classsq~ uq~ \O";>1UtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$117.classsq~ uq~ 癒M|š`Jts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl$2.classsq~ uq~ ت3]tPNt|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/AntlrParserPlugin$AnonymousInnerClassCarrier.classsq~ uq~  (4|2F!stY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$547.classsq~ uq~ 1]qW}tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport$2.classsq~ uq~ «ngtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$732.classsq~ uq~ E:^;krEtR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$16.classsq~ uq~ ߺg)9^=tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$ClassgenCallback.classsq~ uq~ L6 kr=tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$287.classsq~ uq~ |L]K98to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMethodDoc.classsq~ uq~ % j)q?VZUt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/ForStatement.classsq~ uq~ Ve+N/*ۊ tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/UnicodeLexerSharedInputState.classsq~ uq~ y=&8K*otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$657.classsq~ uq~ Eu󜤆tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$253.classsq~ uq~ ' ʟ(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$716.classsq~ uq~ CTziN)uctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$205.classsq~ uq~ q]!&kth/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxSelectedIndexBinding.classsq~ uq~ g7qZVAkp4tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/FastArray.classsq~ uq~ FWAltW/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Node$2.classsq~ uq~ @<ӹ"/p3Ltc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractButtonProperties.classsq~ uq~ FI gf MiTFѻtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$649.classsq~ uq~ ~!r~::tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$508.classsq~ uq~ v0wtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader.classsq~ uq~ \a4\O~~td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$1$1.classsq~ uq~  7)0StY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$734.classsq~ uq~ _|7;Dta/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$MethodIndexAction.classsq~ uq~ % '7:gFtd/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ElementRemovedEvent.classsq~ uq~ \gے +giq^wadtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$866.classsq~ uq~ x cM[&tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/TupleExpression.classsq~ uq~ ;y,\|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$611.classsq~ uq~ fC"2EEkBtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/PostfixExpression.classsq~ uq~ gO(y+Dtz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatDouble.classsq~ uq~ vFYO4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$836.classsq~ uq~ u?hњ V(t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayPutAtMetaMethod.classsq~ uq~ j⧄\T]0z)ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayGetAtMetaMethod.classsq~ uq~  M7|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$829.classsq~ uq~ ^\NT 3EktU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyObjectSupport.classsq~ uq~ }J%x톏(tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/InheritConstructors.classsq~ uq~ Ir W^tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$61.classsq~ uq~ V4g @V/tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$312.classsq~ uq~ Ưڮ1NjRҺtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$505.classsq~ uq~ {W3K=tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/GeneratorContext.classsq~ uq~ x%S$dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$223.classsq~ uq~ )%yl{X"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$53.classsq~ uq~ {;%+?׭;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$947.classsq~ uq~  =]Lt_/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/Builder.classsq~ uq~ =7{s(YLts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ClassInfoSet$Segment.classsq~ uq~ c^ ⤑7-A$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$412.classsq~ uq~ L|9B1u0tK/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonToken.classsq~ uq~ Dyȸ@ctX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Numbers.classsq~ uq~ 9 d <|M5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$808.classsq~ uq~ Pxu.+J t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite$ConstructorSiteNoUnwrap.classsq~ uq~ aU2L~tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/UnaryPlusExpression.classsq~ uq~ JXo >HtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ScriptException.classsq~ uq~ 6V,삃u(tY/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Closure$WritableClosure.classsq~ uq~ dG.DtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/MapEntry.classsq~ uq~ $G UA$Q.th/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$ScriptClassLoader$1.classsq~ uq~ S:'؀p5 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$491.classsq~ uq~ ҹD @CAt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/InnerClassNode.classsq~ uq~ r%B? Iztt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/MultipleCompilationErrorsException.classsq~ uq~  ֣r[2$LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$743.classsq~ uq~ q0>5ӫAht^/home/blackdrag/coding/groovy/18/target/classes/groovy/text/XmlTemplateEngine$GspPrinter.classsq~ uq~ x;Dz3ytz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$ThreadCategoryInfo.classsq~ uq~ a-K%g*ZKt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/CodeVisitorSupport.classsq~ uq~ H9FTk#ʲqXtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$409.classsq~ uq~  Qr+tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$44.classsq~ uq~ hX4DA4tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoGetPropertySite.classsq~ uq~  t~iVGF[Ctf/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ReferenceResolver.classsq~ uq~ _b xX-tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$5.classsq~ uq~ U3Cwt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ErrorCollector.classsq~ uq~ ^|'qYGHtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.classsq~ uq~ 4X)^PURsNtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$288.classsq~ uq~ [GnsK?tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper.classsq~ uq~ Izx%l>0)atO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$3.classsq~ uq~ NoAjIt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptimizeFlagsCollector.classsq~ uq~ =)'}OtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$271.classsq~ uq~ k^c#Ptb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ClassExpression.classsq~ uq~ yƺa~ZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$289.classsq~ uq~ \xeS4'%oG>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$740.classsq~ uq~ Ѫa7.otN/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/CallResultSet.classsq~ uq~ NkJ|tf/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$MixedInAccessor$1$1.classsq~ uq~ K gj tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString$3.classsq~ uq~ %3Py]zg}}tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/DoWhileStatement.classsq~ uq~ }aKhˈiĿOtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$FloatDouble.classsq~ uq~ wUjhT?tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$188.classsq~ uq~ |<Z" >˧tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$24.classsq~ uq~ `hy[pott/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/CharacterCachedClass.classsq~ uq~ r7BZtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$34.classsq~ uq~ ͭ"XԔ6#tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/parser/GroovyLexer.classsq~ uq~ ʉj"++XAo!53tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$239.classsq~ uq~ l;&xy҆J|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$842.classsq~ uq~ #)W1=jĿ pt}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/SourceTextNotAvailableException.classsq~ uq~ s QAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$357.classsq~ uq~ <#usX17ŬtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$372.classsq~ uq~ cgG:fޕ{-KtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$581.classsq~ uq~ xv0.~0%6"S ntY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$567.classsq~ uq~ wštr*t^/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadMapEvaluatingException.classsq~ uq~ t4UsUԙ(=to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/powerassert/AssertionRenderer.classsq~ uq~ \_DO_G(4tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassHelper$ClassHelperCache.classsq~ uq~ [۶gOnMnytn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ImmutableASTTransformation.classsq~ uq~ *͂]v >t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyType.classsq~ uq~ 3e5ڒ.WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$845.classsq~ uq~ dA\cR/0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$688.classsq~ uq~ `6)+fort]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$3.classsq~ uq~ $\GWGH&TFtP/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass.classsq~ uq~ \JW4T:tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$41.classsq~ uq~ -|I82~ڠZ#tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyFieldDoc.classsq~ uq~ ~+)I|oth/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$NewInstanceResolver.classsq~ uq~ `@&xi8tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$27.classsq~ uq~ Le[olM{w]ItL/home/blackdrag/coding/groovy/18/target/classes/groovy/util/XmlSlurper.classsq~ uq~ V6)]*S84t]/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren.classsq~ uq~ *-.\8a_ctq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryLongExpressionHelper.classsq~ uq~ ?N\ '=PtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$78.classsq~ uq~  R vk0MVtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/time/Duration.classsq~ uq~ O0DԾ(AI7tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/MethodCallExpression.classsq~ uq~ !o%5/ٯktX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$54.classsq~ uq~ UpbRܨۥtc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$3$1.classsq~ uq~ mF]gtk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ClassInfo$ClassInfoSet.classsq~ uq~ .[i-tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSite.classsq~ uq~ sп <ާP|+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$443.classsq~ uq~ ]m9 >3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$401.classsq~ uq~ t o&UdC^tg/home/blackdrag/coding/groovy/18/target/classes/groovy/text/GStringTemplateEngine$GStringTemplate.classsq~ uq~ g aQƄTBwt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$1.classsq~ uq~ vJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$281.classsq~ uq~ 1Ο itc/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$6$1.classsq~ uq~ kf ;Q`BtP/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/dom/DOMCategory.classsq~ uq~ Aˀ/`5 te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList$Iter.classsq~ uq~ Qgdi6^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$498.classsq~ uq~  Tpi;vT=ҥ>*tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleLong.classsq~ uq~ Er8 ſtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer.classsq~ uq~ pn={2M69;tJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Sequence.classsq~ uq~ aHzrtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovyc$1.classsq~ uq~ pk ^(7X•~tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/AssertionWriter.classsq~ uq~ Emwz (*tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PerInstancePojoMetaClassSite.classsq~ uq~ ,SųtEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$456.classsq~ uq~ p{r<ޮ5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$638.classsq~ uq~ m0ά;K{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$820.classsq~ uq~ wZRRF{tL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaMethod.classsq~ uq~  QM'd&ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.classsq~ uq~ xW^7 etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$920.classsq~ uq~ aE'AT@tg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$IdentifierResolver.classsq~ uq~ ӫGWq_2z3*to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/NullProtectionStorage.classsq~ uq~ L)оkb9îtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovyMain.classsq~ uq~ K(7p~hX1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$667.classsq~ uq~ ?'(|$%tW_tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$98.classsq~ uq~ ]WpOYmdR5ItS/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/ServletBinding.classsq~ uq~ 1U1 X}~tb/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$DefiningClosure.classsq~ uq~ {d<~td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/TernaryExpression.classsq~ uq~ пOMp[DtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$19.classsq~ uq~ I%k tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$822.classsq~ uq~ 0 r9Uq9htM/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonSlurper.classsq~ uq~ Pp{N+ \tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/SecureASTCustomizer.classsq~ uq~ gF3M 5"tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1053.classsq~ uq~ . TWqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$159.classsq~ uq~ .55tR/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ProxyGenerator$1.classsq~ uq~ OTͭ l6!cF?otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$368.classsq~ uq~ 8JRtd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$SoftRef.classsq~ uq~ Gh:A}t3tV/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ResultSetOutParameter.classsq~ uq~ %~SW!~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$580.classsq~ uq~ ;N)wotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$478.classsq~ uq~ !vM6Zltw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleFloat.classsq~ uq~ vᚒGn@=&ntp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareCompilationUnit$2.classsq~ uq~ n@Ê*@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$964.classsq~ uq~ ˑhâ_"ߺEU88GtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$726.classsq~ uq~ 0Mˤlt^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$3.classsq~ uq~ [[xmBpPPytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$741.classsq~ uq~ q_۴FsK?ŗto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper$1.classsq~ uq~ ?Z*yyVt_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties.classsq~ uq~ i_FvG<긆tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$7.classsq~ uq~ (^5R`3 `ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryObjectExpressionHelper.classsq~ uq~  BM3T Ht]/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$AbstractStatementCommand.classsq~ uq~  1C&ҼOtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavacJavaCompiler.classsq~ uq~ :{Bs5i/0ARota/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyRootDoc.classsq~ uq~ J sz%t}/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$IntegerInteger.classsq~ uq~ F$(9_tu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/TupleConstructorASTTransformation.classsq~ uq~ yI* jZI+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$311.classsq~ uq~ +y3o t^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$5.classsq~ uq~ oxZ?5]J@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$601.classsq~ uq~ 2% d1/ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$609.classsq~ uq~ 08.xN82ztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$715.classsq~ uq~ @lYJkndtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/RangeExpression.classsq~ uq~ 3AD[=rǠtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$58.classsq~ uq~ h BVӡ&V,P$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$481.classsq~ uq~ 8=50B`:p׭AtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$868.classsq~ uq~ ;"o ŠyaCtv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/EqualsAndHashCodeASTTransformation.classsq~ uq~ 4hd!79.7t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.classsq~ uq~ m] Hߘ7WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$125.classsq~ uq~ MȍƲ;Pty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayPutAtMetaMethod.classsq~ uq~ vf $DȏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$192.classsq~ uq~ y;EətY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$747.classsq~ uq~ H /(j?ytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$231.classsq~ uq~ > AjtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$834.classsq~ uq~ 46[zoSe~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$346.classsq~ uq~ Bf0mmD>tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$4.classsq~ uq~ W4]#[PTa‹tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Singleton.classsq~ uq~ Heub" tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ParameterTypes.classsq~ uq~ H>|xݷtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$229.classsq~ uq~  @NXtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/WriterControllerFactory.classsq~ uq~ ;O܉"OI`$mt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ProcessingUnit.classsq~ uq~ I{F#s==td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/ReflectionCache.classsq~ uq~ Udm,8ttF/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/QName.classsq~ uq~ C2=IRoStl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MixedInMetaClass.classsq~ uq~ #{uft`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor.classsq~ uq~ *p2nPX3ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$610.classsq~ uq~ @gX>V֜Ə)UtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/Utilities.classsq~ uq~ }K+ Ԇn-tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/Finalizable.classsq~ uq~ (*#qwBty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$IntegerDouble.classsq~ uq~ #CNYqE9kIWtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/RuntimeParserException.classsq~ uq~ Չ+WSy;tN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovySystem.classsq~ uq~ 23= ﱛq3ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyAnnotationRef.classsq~ uq~ KX?7 d\ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$332.classsq~ uq~ '}x֡OAjktf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/CharWrapper.classsq~ uq~ o/bj 3>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$781.classsq~ uq~ `5W2ʯLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$584.classsq~ uq~ ,DQҟnGe(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$423.classsq~ uq~ nkQ{Huytb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/XmlGroovyMethods.classsq~ uq~ so(t3\vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$623.classsq~ uq~ $ttq ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$LongLong.classsq~ uq~ 1\."P{tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$361.classsq~ uq~ Sn07tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$618.classsq~ uq~ pV7s::putY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$754.classsq~ uq~ I.@`^WtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$582.classsq~ uq~ Fu tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/TypeChooser.classsq~ uq~ #a|_EWS_tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.classsq~ uq~ pQvG-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$299.classsq~ uq~ |9+XYg֓tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$944.classsq~ uq~ ھX Ҫ:'tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$29.classsq~ uq~ ku<[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$724.classsq~ uq~ =4n!tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/Janitor.classsq~ uq~ _rƣJ+tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/Preferences.classsq~ uq~ z{w ̊XItY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$603.classsq~ uq~ qJw "VQnvg8ta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JScrollBarProperties$1.classsq~ uq~ + /6tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$DoubleLong.classsq~ uq~ k[%1G H)itG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$32.classsq~ uq~ $&j6ysn K3ڞtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareResolveVisitor.classsq~ uq~  X*f9)utY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$922.classsq~ uq~ r[Jr5N +~[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$674.classsq~ uq~ o8wZy$%zLt_/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/DeadEndObject.classsq~ uq~ iH %2jjtY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$AbstractQueryCommand.classsq~ uq~ =\_ygmXW(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$540.classsq~ uq~ X-Oʒsa%ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/ReflectionMethodInvoker.classsq~ uq~ TU )5vtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Delegate.classsq~ uq~ ʝJ-a%tb/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$MultiPropertyEvent.classsq~ uq~ Ѿ'@:-NtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$558.classsq~ uq~ J9X-xW |te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectRefFactory.classsq~ uq~ -TiG5t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MissingPropertyExceptionNoStack.classsq~ uq~ 2rj^(z ,hr,= tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.classsq~ uq~ wɆ]~! oUtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$145.classsq~ uq~ 9kTU5z#Vto/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultChildPropertySetter.classsq~ uq~ oPeYȧ,qFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$440.classsq~ uq~ B)JOЊGtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$IntegerFloat.classsq~ uq~ KZ6Օ( +tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$811.classsq~ uq~ k;$:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$286.classsq~ uq~ ?-$sIj(td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/GStringExpression.classsq~ uq~ H0ܶwZ dstY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$176.classsq~ uq~ iVڌvCeQ=gtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$7.classsq~ uq~ <,+ŸO?\Uite/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding.classsq~ uq~ L`@ tY/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/PackageScopeTarget.classsq~ uq~  s;=4bi ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$886.classsq~ uq~ YLɁGmdz; tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$592.classsq~ uq~ UhetR/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/TypeChecked.classsq~ uq~ Uf)$mƩh%tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayPutAtMetaMethod.classsq~ uq~ qՎJ72|GytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$957.classsq~ uq~ ly:ͦQot^/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSliderValueBinding.classsq~ uq~ Ӄp#/ .rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$142.classsq~ uq~ qkrrtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/customizers/ImportCustomizer$Import.classsq~ uq~ aZwaU!+˦tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$764.classsq~ uq~ aruCxQtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$689.classsq~ uq~ @J kktY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$790.classsq~ uq~ Jؿ+kf+tg/home/blackdrag/coding/groovy/18/target/classes/groovy/model/DefaultTableModel$MyTableColumnModel.classsq~ uq~ ~CŊNtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$504.classsq~ uq~ \X 'IأOtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$3.classsq~ uq~ A4<~gH~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$152.classsq~ uq~ ~h@|VT~-ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$992.classsq~ uq~ -o@QtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$31.classsq~ uq~ JT;ˑFF:9]tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$FloatDouble.classsq~ uq~ fJJe}"$OltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$946.classsq~ uq~ xWm}nEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$364.classsq~ uq~ 0&XI W8*td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/XmlGroovyMethods$1.classsq~ uq~ Y \.c,>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$643.classsq~ uq~ 8;j(.otY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$432.classsq~ uq~ A eTF}nta/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComponentProperties$4.classsq~ uq~ KX|#w)<]BtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/GroovycTask.classsq~ uq~ wC%pZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$647.classsq~ uq~ "TI+7byZ|?Ytm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ToStringASTTransformation.classsq~ uq~ s)O& VtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$587.classsq~ uq~ :>(ZV_ύtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/RootLoader.classsq~ uq~ Dz QE2P|tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$855.classsq~ uq~ E dCKRrLtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$221.classsq~ uq~ EW {M7XztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$178.classsq~ uq~ vw%MPH|(.ShtT/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/MarkupBuilderHelper.classsq~ uq~ .q Eq1dlt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$4.classsq~ uq~ ]Ψ8퐄˰tM/home/blackdrag/coding/groovy/18/target/classes/groovy/util/NodePrinter.classsq~ uq~ "qbA[ѢtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$782.classsq~ uq~ 4@r&ڠ3;1Ƕpt^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$14.classsq~ uq~ U ݔ$CtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$389.classsq~ uq~ ϼ".yʭtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/SingletonASTTransformation.classsq~ uq~ .a}hQɟPӚtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$9.classsq~ uq~ eL:&h|0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$321.classsq~ uq~ 4+atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$763.classsq~ uq~ jcRۛ˓t&D%>to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/vmplugin/v6/PluginStaticGroovyMethods.classsq~ uq~ ;8Kb[tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$800.classsq~ uq~ 4J0wbtlKѦtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$862.classsq~ uq~ $\0'A?^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$557.classsq~ uq~  kXL^/2tP/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ProxyGenerator.classsq~ uq~ νI: Һt_/home/blackdrag/coding/groovy/18/target/classes/groovy/grape/GrabAnnotationTransformation.classsq~ uq~ ^ПC kɘtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$452.classsq~ uq~ dRrOph_?ytm/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$DefaultReferenceResolver.classsq~ uq~ Iɑ܆:+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$815.classsq~ uq~ ߡĤ;f`8tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$1.classsq~ uq~ R7V8澌OKt-tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$86.classsq~ uq~ &kH9outp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ReflectionMetaMethod.classsq~ uq~ @g5KDI&UtO/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Slf4j.classsq~ uq~ |2>^ՉdLK&?t_/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/NodeChildren$3.classsq~ uq~ עT-3I;VtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$722.classsq~ uq~ t}ZCy(4te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ParserPluginFactory.classsq~ uq~ U\/~m`j_stWtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/BindPath.classsq~ uq~ wD뭝HQ_tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$1.classsq~ uq~ K1&+ to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/SharedVariableCollector.classsq~ uq~ 63_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$825.classsq~ uq~ x/_y58vtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$382.classsq~ uq~ "iEe EtV/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/Types.classsq~ uq~ H4Z+CWX0tK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Reference.classsq~ uq~ x#ڇrLOtO/home/blackdrag/coding/groovy/18/target/classes/groovy/transform/ToString.classsq~ uq~ 0CgSls5ytP/home/blackdrag/coding/groovy/18/target/classes/groovy/util/BuilderSupport.classsq~ uq~ UU#!aVWFtU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$4.classsq~ uq~ |%aP8tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/memoize/MemoizeCache.classsq~ uq~ aO$t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$StandardClosureChooser.classsq~ uq~ hup 5&jtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MethodNode.classsq~ uq~ TJ^DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$501.classsq~ uq~ 'rto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/TransformMetaMethod.classsq~ uq~  h/Oa%zTtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$893.classsq~ uq~  MO8O@;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$530.classsq~ uq~ ؖFXyoBxtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$238.classsq~ uq~ e3zZlte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/SingleKeyHashMap$Entry.classsq~ uq~ HrC;tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$4.classsq~ uq~ prgsȯOtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$780.classsq~ uq~ v q7?Bth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/MetaClassSite.classsq~ uq~ a=.cjbStV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$3.classsq~ uq~ }B&Xo)% #a.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$564.classsq~ uq~ ׹3\0 03btN/home/blackdrag/coding/groovy/18/target/classes/groovy/time/TimeDuration.classsq~ uq~ {SSTA̾mtx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$NumberNumber.classsq~ uq~  jH(CSptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$425.classsq~ uq~ B1,2tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/CompileUnit.classsq~ uq~ {j>@#lItY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$531.classsq~ uq~ E(Yi\Lkftf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$5.classsq~ uq~ haU tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$952.classsq~ uq~ کXi9tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$18.classsq~ uq~ !D#)OPtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$883.classsq~ uq~  KtѦ;gtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$15.classsq~ uq~ zAs1s!ftV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$2.classsq~ uq~ =!aiW,Qth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedLinkedList$Element.classsq~ uq~ }~2=F/Z΍t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier.classsq~ uq~ R c+BmFV}Y"]tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$25.classsq~ uq~ !;o\$tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$1.classsq~ uq~ /ݚ#;57.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$375.classsq~ uq~ ΂aD vhtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$338.classsq~ uq~ pSPK"tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$19.classsq~ uq~ MT A-Mvr`tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap$Values.classsq~ uq~ d*1vDT8tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$541.classsq~ uq~ 9?+YV$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$989.classsq~ uq~ ٛ[~7Vo|h I5#j2td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$3$1.classsq~ uq~  )ʹ&tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$230.classsq~ uq~ T gKq+ƕ!t{/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter$OptVisitor.classsq~ uq~ e%xvȶctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$972.classsq~ uq~ ehvBEtV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyScriptEngine$1.classsq~ uq~  %*_>dm(t\/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/BindableASTTransformation.classsq~ uq~ e$l,РC\ctc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/BinaryExpression.classsq~ uq~ `!e ?y-YtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$252.classsq~ uq~ Y;&Z2_tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$10.classsq~ uq~ X*r3]atY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$392.classsq~ uq~ Zap`tM/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/OutParameter.classsq~ uq~ #%ן<$:^XttZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1046.classsq~ uq~ alF`Għti/home/blackdrag/coding/groovy/18/target/classes/groovy/ui/GroovySocketServer$GroovyClientConnection.classsq~ uq~ -ن^jOte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$1.classsq~ uq~ )L߳L\YtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$75.classsq~ uq~  LeH&Nt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ OFa+tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$34.classsq~ uq~ Y,CO+"Wޟ( t[/home/blackdrag/coding/groovy/18/target/classes/groovy/io/EncodingAwareBufferedWriter.classsq~ uq~  ;:c GFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$598.classsq~ uq~ >(zq6}ktg/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ObservableListIterator.classsq~ uq~ bl(72Ut}tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$20.classsq~ uq~ rFh4m%of}ӻyt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap.classsq~ uq~ g gUp:@ta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/InvokerHelper$2.classsq~ uq~ HKƜrɑTitY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$353.classsq~ uq~ Vz`ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorMetaClassSite.classsq~ uq~ [Qnzm1E'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$975.classsq~ uq~ CX͊6mt`/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/dom/DOMCategory$NodeListsHolder.classsq~ uq~ z' jW3 tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$860.classsq~ uq~ 4 0:pX`tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus$LongFloat.classsq~ uq~ qQM6~{&Otb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/FieldExpression.classsq~ uq~ @qI1ML7tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$529.classsq~ uq~  L)$Ztd/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMap.classsq~ uq~ Fyg2_|?tW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$0.classsq~ uq~ O%G'x)Itb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/SwitchStatement.classsq~ uq~ ^FCr3cJtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$719.classsq~ uq~ 4v[ bgUHxtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$12.classsq~ uq~ \;N0&[ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$422.classsq~ uq~ ZdzmFt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/ErrorReporter.classsq~ uq~ PDq,L@!BZzti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/MindMapPrinter.classsq~ uq~ L;n !t(t`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/ParserException.classsq~ uq~ }]?g'N?L/ytj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/IntegerMath.classsq~ uq~ Ll$KaKto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit$2.classsq~ uq~ brFlbty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongDouble.classsq~ uq~ 7:ףm*_%(tI/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Closure.classsq~ uq~ w}=dٮtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$438.classsq~ uq~ LMNujrvtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$881.classsq~ uq~ LQepP\tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$126.classsq~ uq~ Gu?jm%WotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$830.classsq~ uq~ EBN`A@`6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$198.classsq~ uq~ ,"+KBkFx}ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/LazyASTTransformation.classsq~ uq~ ͙SI]tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1023.classsq~ uq~ 5 U$VE'ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$DoubleInteger.classsq~ uq~ '} C:0tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedClass$CachedMethodComparatorWithString.classsq~ uq~ 㥴8͖tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ResourceConnector.classsq~ uq~ ]5GuI}tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$788.classsq~ uq~ 'hᵍY"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$189.classsq~ uq~ U8EOmtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$339.classsq~ uq~ "m7ZILth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/SynchronizedStatement.classsq~ uq~ t07ف0tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$827.classsq~ uq~ U7C4LtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$243.classsq~ uq~ MtmYM!r6$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$237.classsq~ uq~ :$3 uD #etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$723.classsq~ uq~ lc Wc!2'-t^/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/GPathResult$2.classsq~ uq~ Ma7-cFvtK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GString$2.classsq~ uq~ x=yAtZ/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingPropertyException.classsq~ uq~  5*یS]8F)tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$FloatLong.classsq~ uq~ + ;aV_/"t tI/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Factory.classsq~ uq~ u U\Eot/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ 뢚Қ|4tf/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$ObjectBeanFactory.classsq~ uq~ (5 ^E+;tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayPutAtMetaMethod.classsq~ uq~ O~PEȤ4;tR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ClosureException.classsq~ uq~ UH6JaP'ݫtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/UberCompileTask$GroovycAdapter.classsq~ uq~ qwʎw3tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/InheritConstructorsASTTransformation.classsq~ uq~ _sAby3tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$671.classsq~ uq~ !f8Į|te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredNodeChildren.classsq~ uq~ _ Er^\ ڏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$789.classsq~ uq~ Dv_;aSC^Ate/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/ConstantExpression.classsq~ uq~ SA`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$499.classsq~ uq~ c3xKtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$749.classsq~ uq~ }KjQ!mtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$662.classsq~ uq~ k(T+t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType$2.classsq~ uq~ 4 i+HN tV/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$3.classsq~ uq~ &\AРK*Qth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/util/MessageSource.classsq~ uq~ "ȟǕ|t^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$15.classsq~ uq~ ?lqMSVG]mt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/StaticVerifier.classsq~ uq~ *a`ơtW/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$ExtractIndexAndSql.classsq~ uq~ ܏ e- neltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$500.classsq~ uq~ u41_>tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$64.classsq~ uq~ 爓HǣatQ/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/FactorySupport$1.classsq~ uq~ Q lOB})tP/home/blackdrag/coding/groovy/18/target/classes/groovy/model/PropertyModel.classsq~ uq~ s._֞{FL{UVotG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$17.classsq~ uq~ cj|h=;DHtQ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/AbstractFactory.classsq~ uq~ ,,Qc9ʣKhƛ"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$320.classsq~ uq~ P*goJb5p2ҙtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$821.classsq~ uq~ R*'֯GtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$760.classsq~ uq~ 4:+k01xtS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/GroovyCollections.classsq~ uq~ Fҡ(_ԛr@c/tR/home/blackdrag/coding/groovy/18/target/classes/groovy/io/PlatformLineWriter.classsq~ uq~ wZ Vt\/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attribute$1.classsq~ uq~ `-α@tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/GroovyExceptionInterface.classsq~ uq~ |m$*c2dFtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaAwareCompilationUnit$1.classsq~ uq~ USg۷-cto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader.classsq~ uq~ 3mQsEdt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSite.classsq~ uq~ ✨G*+cXR3tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/ClosureSourceBinding.classsq~ uq~  sDȏtT/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ExpandoMetaClass$2.classsq~ uq~ Ʌ:HnjXG=Ok1tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongLong.classsq~ uq~ ;%26`WKtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$534.classsq~ uq~ !e@,;:G/Ctw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport$RangeInfo.classsq~ uq~ uȴ{l˳tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/BooleanCachedClass.classsq~ uq~ cy #DNtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv$FloatFloat.classsq~ uq~ ydA$x!=tY/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ResultSetMetaDataWrapper.classsq~ uq~ xoKE?tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$877.classsq~ uq~ bt<ˉ2rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$833.classsq~ uq~ b]\CwZtw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.classsq~ uq~ &]sGݱitZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1005.classsq~ uq~ NN.Ü0tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/tools/WideningCategories.classsq~ uq~ ]RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$552.classsq~ uq~  y*+tO/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyShell$6.classsq~ uq~ ݷ>1{-umbta/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/InvokerHelper$1.classsq~ uq~ YOn3LӦ+| tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$995.classsq~ uq~ Zϭm$ /t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GenericsType$1.classsq~ uq~ diB7TIfxtr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/ClasspathResourceManager.classsq~ uq~ 㰸E8YHto/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/NewStaticMetaMethod.classsq~ uq~ i2 dtK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Buildable.classsq~ uq~ rjQzp~tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/UnicodeEscapingReader$DummyLexer.classsq~ uq~ Y9w|:td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/TryCatchStatement.classsq~ uq~   /55.8ti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ManagedConcurrentMap$Entry.classsq~ uq~ IQARЉJh]t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorSite$NoParamSiteInnerClass.classsq~ uq~ gyyk*bgI8t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/FullBinding.classsq~ uq~ Еf_&>rCÆmjti/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObjectGraphBuilder$RelationNameResolver.classsq~ uq~ pxF[ &sotY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$751.classsq~ uq~  08+w&~tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$ExceptionTableEntry.classsq~ uq~ sLvM(v(tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/inspect/swingui/TableSorter$1.classsq~ uq~ {1uxFqtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$63.classsq~ uq~ `/X&4φtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$207.classsq~ uq~ 2f%VvxCtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$278.classsq~ uq~ ރ]Ȧ 81tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$837.classsq~ uq~ @ުyM&_Vth/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyConstructorDoc.classsq~ uq~ Kf&LgSᵎtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$5.classsq~ uq~ pюNm3t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/HashCodeHelper.classsq~ uq~ \*I%tc/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ObservableIterator.classsq~ uq~ LQհ<.tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$249.classsq~ uq~ ޠ tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$222.classsq~ uq~ &f\L(_DtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$865.classsq~ uq~ ^)K6^TPWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$513.classsq~ uq~ +-* h]tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/GroovyCastException.classsq~ uq~ W V7J`gtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$334.classsq~ uq~ YLLdnj-3+Vx%te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log$JavaUtilLoggingStrategy.classsq~ uq~ 싈>"1ICuti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyPathFullBinding.classsq~ uq~ ћp?¤^ctY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$225.classsq~ uq~ qQz>zpjtJ/home/blackdrag/coding/groovy/18/target/classes/groovy/text/Template.classsq~ uq~ mglov6#7j;tv/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus$LongDouble.classsq~ uq~ K׵q+3E#tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$331.classsq~ uq~ g⠞t>TXƺtF/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$5.classsq~ uq~ ^F OVfccftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$546.classsq~ uq~ lNH T rtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$97.classsq~ uq~ h?c4?QtS/home/blackdrag/coding/groovy/18/target/classes/groovy/json/StringEscapeUtils.classsq~ uq~ ps.j@$tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$162.classsq~ uq~ Zaqlt+̫7tW/home/blackdrag/coding/groovy/18/target/classes/groovy/text/GStringTemplateEngine.classsq~ uq~ .7ﱎ)I^dAtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$196.classsq~ uq~ E:'\|~ρIWtM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GrabExclude.classsq~ uq~ /R*g4 m>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$856.classsq~ uq~ Mb㻩k(LXtz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply$LongInteger.classsq~ uq~ |ghk֏Rt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher$BinaryByteExpressionHelper.classsq~ uq~ \^YԾLFp8:_tw/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyProgramElementDoc.classsq~ uq~ +嘑$Lّtl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ClassCodeExpressionTransformer.classsq~ uq~ ٯIk+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$934.classsq~ uq~ ޒATXmqC Ptq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/NumberCachedClass.classsq~ uq~ yOXty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/VariableScopeVisitor$StateStackElement.classsq~ uq~ /,"~s=1.tP/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/GroovyResultSet.classsq~ uq~ Aм q"8y5tS/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ClosureComparator.classsq~ uq~ ږ)#ɶ(ty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MissingMethodExceptionNoStack.classsq~ uq~ 0-n#rk*K2_tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$121.classsq~ uq~ AHT5>p[QtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$25.classsq~ uq~ aIq~tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$950.classsq~ uq~ ><쯠FU<݅xtS/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/TrampolineClosure.classsq~ uq~ rr?y@)ZtK/home/blackdrag/coding/groovy/18/target/classes/groovy/beans/Bindable.classsq~ uq~ )k'OFtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryBooleanExpressionHelper.classsq~ uq~ ٯ*7}}mHtP/home/blackdrag/coding/groovy/18/target/classes/groovy/text/TemplateEngine.classsq~ uq~  "l?u^w:=te/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/VariableExpression.classsq~ uq~ @.y@Ertq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$BlockRecorder.classsq~ uq~ VhZYasDtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/syntax/CSTNode.classsq~ uq~ zw#I.tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$QueryCommand.classsq~ uq~ X)—kR׽نtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$955.classsq~ uq~ 1 7JKY/tk/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/ExtensionMethodNode.classsq~ uq~ o~~3YutN/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyObject.classsq~ uq~ X,.7KZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$326.classsq~ uq~ NφIe+l1\o^tQ/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/ExpandedVariable.classsq~ uq~ 9: K%tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$105.classsq~ uq~ պ"d*z?]tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1040.classsq~ uq~ K#e 4*it^/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/LazyReference$2.classsq~ uq~ plq7Mtt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/ConstructorMetaMethodSite.classsq~ uq~ /\zGwIA\tt/home/blackdrag/coding/groovy/18/target/classes/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder$Document$3.classsq~ uq~ xk3 dPrՓtW/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/MixinNode.classsq~ uq~ )ͯ[kE^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$242.classsq~ uq~ q(JC\~/֢td/home/blackdrag/coding/groovy/18/target/classes/groovy/util/logging/Log4j$Log4jLoggingStrategy.classsq~ uq~ 7d NƫD)e"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$170.classsq~ uq~ #(jt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/groovydoc/GroovyDoc.classsq~ uq~ )=a VFL*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$566.classsq~ uq~ h!4<ڡ{9tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex$Entry.classsq~ uq~ *gu}dG7tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/StaticTypesTransformation.classsq~ uq~ X֤w[M`tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$493.classsq~ uq~ :KvkN6؎ujtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1017.classsq~ uq~ SG)kc'2Bt]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/ConstructorNode.classsq~ uq~ KwQġ(:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$419.classsq~ uq~ Dz -htY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$446.classsq~ uq~ _]/)"Et`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/CachedField.classsq~ uq~ 7F҇=̑t\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/DgmConverter.classsq~ uq~ 2tE3!8{JxMtM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ObjectRange.classsq~ uq~ *ƒE-Ϫ.th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/SourceExtensionHandler.classsq~ uq~ bMMScmztg/home/blackdrag/coding/groovy/18/target/classes/groovy/text/SimpleTemplateEngine$SimpleTemplate$1.classsq~ uq~ CH{c.^tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$40.classsq~ uq~ `\I]Ptl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/AbstractConcurrentMap$Segment.classsq~ uq~ Ǔ{ hitZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1054.classsq~ uq~ ND_ q4tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$471.classsq~ uq~ ϴ#! /tj/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JComboBoxSelectedElementBinding.classsq~ uq~ 컐.SqytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$737.classsq~ uq~ fYqA sSy7ytf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/SwingGroovyMethods$6.classsq~ uq~  *GUCR1tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$605.classsq~ uq~ "Fv4ttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$143.classsq~ uq~ =nx,`R?rt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrap.classsq~ uq~ +/۲`SײwptY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$330.classsq~ uq~ V)i8uzITtq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/StringCachedClass.classsq~ uq~ {7K3)Sr_t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayGetAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ %+!jADu'th/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/treewalker/SourcePrinter.classsq~ uq~ UYCFwaatc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/stmt/LoopingStatement.classsq~ uq~ y]PPtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1039.classsq~ uq~ 3="m:\ftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$691.classsq~ uq~ FhDȩG]޼tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$455.classsq~ uq~ !H+sU>'V'(tq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/DoubleCachedClass.classsq~ uq~ sӚf/Iztq/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/MethodRankHelper$RankableMethod.classsq~ uq~ S :fɅ %&6tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$308.classsq~ uq~ t͝KJYtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/Groovydoc$1.classsq~ uq~  ajucz /$+@tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$345.classsq~ uq~ *^Ւ .@J]dtR/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/ProxyMetaClass$3.classsq~ uq~ ^xJq%QwÏ)tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$430.classsq~ uq~ u{^ASmDti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/stc/StaticTypesMarker.classsq~ uq~ 85A#gʤ@>tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$625.classsq~ uq~ *\mO@ |bywt\/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/util/ReferenceType.classsq~ uq~ YD۳`dtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$766.classsq~ uq~  /Bf@vltY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$590.classsq~ uq~ S63˨0FOtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$90.classsq~ uq~ {\yUtm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.classsq~ uq~ $6N!K*}tF/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Lazy.classsq~ uq~ {Ilm&t[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/VerifyClass$2.classsq~ uq~ DRNƈntY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$556.classsq~ uq~ '!< lg#Yt[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableList$ChangeType.classsq~ uq~ V2EŃC뉊d[,tz/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.classsq~ uq~  2>fF5tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$792.classsq~ uq~ p9drʀ!tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1047.classsq~ uq~ 969Gt]/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTableProperties$2.classsq~ uq~ IL`s^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$642.classsq~ uq~ qkTT B?jt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/Reflector.classsq~ uq~ RuQCdtn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass$4.classsq~ uq~ !`(#3j_ڊtu/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/CompileStack$StateStackElement.classsq~ uq~ tIf%JtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$31.classsq~ uq~ Xtx^E'Z]t|/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/ResolveVisitor$ConstructedClassWithPackage.classsq~ uq~ QLoJc:tO/home/blackdrag/coding/groovy/18/target/classes/groovy/json/JsonTokenType.classsq~ uq~ O2{[/.Y|tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/PropertyBinding$UpdateStrategy.classsq~ uq~ bq!ONGtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1001.classsq~ uq~ K\(S|-tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$272.classsq~ uq~ ݫHL\}7tm/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.classsq~ uq~ ߈>dHtL/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/IntRange$1.classsq~ uq~ =; Su$ҝtX/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingMethodException.classsq~ uq~ xA⾚~ 6_tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/PropertyNode.classsq~ uq~ X`A;rtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$720.classsq~ uq~ ]i8h2R6*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$951.classsq~ uq~ /dHJ/@tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$43.classsq~ uq~ +1ڨ2c[ytd/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JTextComponentTextBinding.classsq~ uq~ >98ֽEtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$911.classsq~ uq~ V"meeztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$631.classsq~ uq~ "D &*?-tG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$30.classsq~ uq~ vXL0 1k\et[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ant/RootLoaderRef.classsq~ uq~ u1tg+tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$502.classsq~ uq~ sH? Y˾tj/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/InnerClassVisitorHelper.classsq~ uq~ fK-Y۷tp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/typehandling/FloatingPointMath.classsq~ uq~ WoE9œ6tr/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/CallSiteAwareMetaMethod.classsq~ uq~ P d?ti/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MetaClassImpl$GetBeanMethodMetaProperty.classsq~ uq~ c"_Yu2itY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$413.classsq~ uq~ ?! SϰqtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$954.classsq~ uq~ @ADT-CtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$108.classsq~ uq~ G$6Fuv7^tt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/EventTriggerBinding$EventTriggerFullBinding$1.classsq~ uq~ MI̥s\1AntX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$36.classsq~ uq~ ]$3X ~d tn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/AutoCloneASTTransformation.classsq~ uq~ ( w䗅Qtc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$3.classsq~ uq~ )kb̰t_/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/JSpinnerProperties$1.classsq~ uq~ j}DM;9ts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ClosureStaticMetaMethod.classsq~ uq~ ] jNP37RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$124.classsq~ uq~ 1 q~q"'YtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$52.classsq~ uq~  ƢQltM/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/Interceptor.classsq~ uq~  5oK?LY:tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1041.classsq~ uq~ @*X$#pastK/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/SpreadMap.classsq~ uq~ i钟r6Z tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$307.classsq~ uq~ Hs^KBYtF/home/blackdrag/coding/groovy/18/target/classes/groovy/util/Eval.classsq~ uq~ ɍ{ qtp/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/stdclasses/ShortCachedClass.classsq~ uq~ Pf2)SXBtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$49.classsq~ uq~ -?1(~dH tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$118.classsq~ uq~ x&/6@ndsts/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/groovydoc/FileSystemResourceManager.classsq~ uq~  ~Sb yzUtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$646.classsq~ uq~ M!b_Rm)ltW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingClassException.classsq~ uq~ A_:έtb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/binding/AggregateBinding.classsq~ uq~ ,_CFtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$283.classsq~ uq~ FB&nn獥cftY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$757.classsq~ uq~ S"30TY$.te/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/FilteredAttributes$1.classsq~ uq~ y!qh9!{tb/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/shell/IO$Verbosity.classsq~ uq~ #EcM(2*:t/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoMetaMethodSiteNoUnwrapNoCoerce.classsq~ uq~ V0Oy Fpstn/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod$Proxy.classsq~ uq~ rb[tPXtg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/MopWriter$MopKey.classsq~ uq~ [j5( GytY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$826.classsq~ uq~ >t :t]/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/Verifier$8.classsq~ uq~ PFq!C` tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$851.classsq~ uq~ 嘆҄[0͉]*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$902.classsq~ uq~ l$Sr( WJt[/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/VariableScope.classsq~ uq~ 06cqSztY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$260.classsq~ uq~ ~4Y^5ːUTtg/home/blackdrag/coding/groovy/18/target/classes/groovy/servlet/TemplateServlet$TemplateCacheEntry.classsq~ uq~ VX[>},tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$949.classsq~ uq~ D \Cژu0tc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/expr/SpreadExpression.classsq~ uq~ ac3hN@^tW/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/MissingFieldException.classsq~ uq~ kbx lk(td/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/control/CompilationUnit$10.classsq~ uq~ VTճAU4md6tX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$77.classsq~ uq~ .Xk5sγtX/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$18.classsq~ uq~ 6Ȗ ^*AtZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1029.classsq~ uq~ /г}&\Ro;tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$137.classsq~ uq~ 0pEgvti/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/GroovyCategorySupport$1.classsq~ uq~  9+ղtU/home/blackdrag/coding/groovy/18/target/classes/groovy/lang/GroovyClassLoader$6.classsq~ uq~ [ $Ŝ"tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$341.classsq~ uq~ ʚ upn'tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$980.classsq~ uq~ bf2j84tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$705.classsq~ uq~ +KkR0 dtG/home/blackdrag/coding/groovy/18/target/classes/groovy/sql/Sql$15.classsq~ uq~  +Vtf (Mm*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$635.classsq~ uq~ `T_=(;tZ/home/blackdrag/coding/groovy/18/target/classes/groovy/util/ObservableMap$ChangeType.classsq~ uq~ FF YWIWtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$183.classsq~ uq~ #3e'3RtX/home/blackdrag/coding/groovy/18/target/classes/groovy/time/DatumDependentDuration.classsq~ uq~ >$V[mty/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/metaclass/ThreadManagedMetaBeanProperty.classsq~ uq~ mCP:|RtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$966.classsq~ uq~ Y@[^tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$919.classsq~ uq~ p93YxߏtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$956.classsq~ uq~ ID@$4ǩt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayPutAtMetaMethod$MyPojoMetaMethodSite.classsq~ uq~ wh /ir0to/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit$1.classsq~ uq~ J($w,K?$(tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$551.classsq~ uq~ >PSNQ]tl/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/transform/ASTTransformationVisitor.classsq~ uq~ 9cf*JZtY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$896.classsq~ uq~ >ax}vttY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$427.classsq~ uq~ 5R\:tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$371.classsq~ uq~ psqc}'r=ztc/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/antlr/HScrollableTextPane.classsq~ uq~ K8Цjt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite$StaticMetaMethodSiteNoUnwrap.classsq~ uq~ ki`uNA2;ʕ etY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$460.classsq~ uq~ wڷ[4̹,Qt`/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/ast/GroovyClassVisitor.classsq~ uq~ KofMz4CB"tx/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/reflection/GeneratedMetaMethod$DgmMethodRecord.classsq~ uq~ Ptg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/classgen/asm/InvocationWriter.classsq~ uq~  z!W% te/home/blackdrag/coding/groovy/18/target/classes/groovy/swing/binding/AbstractButtonProperties$1.classsq~ uq~ ? 9Xk4q tf/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/PojoWrapper.classsq~ uq~ tz[nt|H1tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1020.classsq~ uq~ w6>BS Tte/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/tools/gse/DependencyTracker.classsq~ uq~ ѹn _.tg/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/wrappers/FloatWrapper.classsq~ uq~ ^[ly}ydHt/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.classsq~ uq~ IEn77*tY/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$482.classsq~ uq~ DW }\tZ/home/blackdrag/coding/groovy/18/target/classes/org/codehaus/groovy/runtime/dgm$1027.classsq~ uq~ H1SEZsEt[/home/blackdrag/coding/groovy/18/target/classes/groovy/util/slurpersupport/Attributes.classsq~ uq~ Dct]D"e&DoN&{vhcX81\W|}=(I.>FCjvTz)~27O3xsrt?$8@= G.P}O^A{\ֶ͞cņ7.ω 9BnvgHruRg'qVp1hI:idPԌ}\BzbzTh.yhsB`'ez4$$Q@<^Qash &|J ;2,C Yu3 [nuFLyZpJ sr%Hю  j[8.zV"NeTPj\ >.p {@cW@yV/c1'(zT~"Jn:0P(  \i .LsbZ^rϊiz w:C-[vSHUxqkr{5avSj$t=NO~!|O%$L&hF*I>V+GTD\Z2,zSyKXUS\&-/@ ^vQc`8zSuF1P?.SȖj`2@>bM>c@18V(P0f9`(n>b_m%< mBAIfQSYO=d{x}o^o>6< u.d 6CCXHF*+7l,uY26F2@9]ʹKOd~a~nyL>(Ynb`F,MMpN oԔz 6 B7c4GF-b6˔5e5R$e0zh[ֆ34`ۼ: 5ufXEYi][VkfEiWeR]rEH9HDl Y&3e*9r-թL4:-F#? WLm!Avn7uuwJ`x!5Ú;W$HҮڮCLGiJm{rKn][^,]lr|SLVܨHO& vNrL]b#(7d6Wp _f8t?j=m23`H*d|Q:2h9N&f/[\QGa;TlI5-qtqH9|`FL[Xr`B+k@bxJ>*x-Pm,!@,1]lfa%a.w#{CZ=Tﲒ_ l2!Ӳ(F[+ MENJU cy>wb}) !UIqB\: V#O<,?p"\d]'(fz tl1p@4b>E_4Uf=tt$G^<y5q. WD)L83LQ`o&u+)b fG[_ܤ-D4If-A*@*@:'A":IO`X]~hYF\~7e˔7V/R(,d2#P';NW\ejTRs} buGrk-#?)pڏEL2O$F %7 5ۂH|sQ`L%}\OTrUi W\kߖ`UF+ FAj#xK@f1=Z$"yc'H(`LKT"VM|]N[Lh>\l/z{ 4hb&HҬF;Iy[xRB80?øǑjqfi^G B|ҩz *VK2YVJ4 6*)"F1N . Ϻ$e9"t[LR .03,$$DGٳTB&15~@63,$$|m$*c2dF5~X3,$$ٵa 4X'jY5~Xn/3,$$j+ pgfר5P>ꂎ3,$${fY5~ dXZ3,$$wC%pZ5~1}O3,$$clUl*`K65~?H3,$$EY=+6Y65~Z]3,$$eC#2_XN9n&5~33,$$~54MP5~RW3,$$ Q b B(P4_T5~C3,$$`%,N'l5~3,$$#_/VQ65~ШT3,$$kAj=s#HC45~}=h3,$$Sgt"Q൝u5~Cj3,$$zTdۊ&u5~Iq3,$$u1tg+5~ |~3,$$| ;Ly5~b3,$$y#Ci{k25~OԌ3,$$ ajucz /$+@5~xf3,$$.!߄8H5~ 3,$$pk ^(7X•~5~6_hu3,$$b ܾT{I75~T-I3,$$)o]*5~0n3,$$qwʎw35~ N\Y3,$$0 09uO}Į5~pr*3,$$d!-m./5~pч.3,$$G$wk8"5~ _=3,$$׽gFz_yA=#5~H3,$$ٯIk+5~@&r3,$$)ͯ[kE^5~pXJ3,$$?A/SA5)5~pL[3,$$ Z+5~uU{3,$$06cqSz5~X%:3,$$]K L/6[nW5~93,$$X`A;r5~p]>t3,$$#{3KKŀ;5~pd3,$$( (GGq|5~p5k3,$$ok[ݳ@73|5~@)-3,$$TJ^D5~pPF03,$$diB7TIfx5~pw/3,$$ ^%'5~p /3,$$bd฿%Y5~X cc3,$$,5ah.H5~4;"3,$$KofMz4CB"5~p$R3,$$4Pš C;5~\j3,$$H9FTk#ʲqX5~@?)^3,$$KwQġ(:5~pmp3,$$2eJ'If[5~p ?5%3,$$F$gC"q5~p*3,$$4 JpptqW5~ b3,$${j>@#lI5~p3,$$pw鹒W&a^Q5~p%E3,$$[۶gOnMny5~X##3,$$r%B? Iz5~p 3,$$z `!]/m5~p8s%3,$$}o KG#M~5~Wϙ3,$$13N^J6A.5~X 3,$$_ζ#iJdMT5~ XQ3,$$̌8d_* $ t5~Xue3,$$~ވr@t1 15~r/3,$$SA`5~X Ok3,$$[>a,5~X6n3,$$@.y@Er5~X 3,$$Z\rFKD5~X3,$${q2?k_t/5~X nc3,$$пOMp[D5~X B:3,$$QNҋfBi5~X 4Ҫ3,$$gO(y+D5~X k[3,$$А\j:in5~X ۟3,$$'l`;p o5~X d*3,$$q!"c?^#5~XtP3,$$_Ǣ$졥.^5~XSg 3,$$p ;C#n5~p A3,$$RM?_'T!Z5~Xo\"3,$$;y,\|5~X_43,$$3AD[=rǠ5~XYP~3,$$JXo >H5~X?Y3,$$6LpT ᆎ95~X43,$$4m.}Z!`ϻ5~X i'3,$$Hp_.\5~n3,$$ɋBrKƭ3o5~XFΥ3,$$H0ܶwZ ds5~XLVa3,$$`!e ?y-Y5~X9C43,$${\ÁPqji05~X '_ڡ3,$$ȃ٥R3`StH5~X (q3,$$j#:]Z^5~XSw3,$$s}_I m5~X x3,$$F)^yʥو5~X 6%3,$$6j}RL!-a5~X\3,$$ac3hN@^5~Xwv3,$$!o%5/ٯk5~X3,$$@qI1ML75~X ^ 3,$$IzZ!FxWЎW5~X 8L3,$$9,7ųa^`zw%5~XDR3,$$yƺa~Z5~X00/ 3,$$\8p;B 5~X C93,$$FuMqިr5~@9'"3,$$O8@v$G 5~Xn3,$$^FCr3c<5~X rj3,$$^ak9Vp5~X3,$$t07ف05~X,{3,$$ n@%ëS5~XY3,$$}aKhˈiĿO5~X$nwȠ3,$$ĴlIDCE5~XP|3,$$v E{ˢ5~X3,$$2‰_t ¹l5~@4Q3,$$݋!-Vo`5~X|MӠ3,$$  /55.85~X Yof3,$$pE`&{t%X5~XV3,$$OWEwgy0bkV5~p3,$$ 3! <:!zϐ5~XsZ3,$$y]PP5~XHw/3,$$u~~R*=T5~XB 3,$$htڥH%`">5~X^3,$$Ve+N/*ۊ 5~X %n3,$$ /QW:7Y5~Xh43,$$R[Rɡ_5~m[d3,$$xछ J5~X933,$$]R9z/Ѥ5h%N3,$$V׬H@[5hn 3,$$^ZM˧!15h/#3,$$kiAx a5h 3,$$O `n˝q5h*hPL3,$$/ d]5hW`3,$$)#ޡ2$Ba5h!e,3,$$!orك#YW(5~LYm3,$$oCƧ8c5hK 3,$$1~rHRBS5h֌3,$$N^_oq+; 5hH 3,$$ϩm¤85hF3,$$Hٶfbi̮Y55h>ut3,$$?SHRԙ3{5hx/3,$$5|b#!}g5hS3,$$bf" 5hdGޥ3,$$6N+`h#7s5hR3,$$XjLOO_H5h f3,$$B XЅ&?%Q5h- 3,$$+?SgJ12m5h03,$$Mʵ}$h5h#I63,$$sAZa\<%5h*ZW3,$$jƍݼdwW5hNj=_3,$$Q5腁џ5h!뎤3,$$|ND,[8}45hR 3,$$λcAE!nU5hF3,$$=NaY5h$ 3,$$~|+v45h%CȔ3,$$ 'id5hLi3,$$3,$$ip[R295hDiV3,$$xM~:[Ev^q {5htks3,$$I_%J)5hKiWT3,$$ԍvY,cJ 45h3>P3,$$V<3*>5~h%3,$$l(a@+g5h15;3,$$ DYUmbv„<5Qi/3,$$·v {OÙڿ5Q=j|3,$$L6QIhɎ '`5QpۑI3,$$w3^??pD3Bh"W5~i3,$$plq7M5~@`V3,$$L L45F42y`5~GT8;h3,$$(*#qwB5~@}jU3,$$@ myrAI5~@M&3,$$6_[u5~8  5[3,$$)a*^th5~c粥3,$$4K%dzϕ0U/5hF3,$$4$UAP4i}n!5~?m~ 3,$$ =dD!95~wJ3,$$t5ZV'yG7iwyv5~@zN3,$$12aGFQ%5~:3,$$r0?d 2:5~@ (3,$$7 zf9THѩC5~@ m3,$$>gu$4v5~@SLY3,$$FWAl5~@ ѠQ3,$$brbP_iq5~8 @. 3,$$G!YvX1@.5~8Oʹ3,$$IQARЉJh]5~@ n:|3,$$7dۜZ615~ RW%3,$$Gh:A}t35~Qz1<3,$$[ǂlދgxz5~8J83,$$EgP'Zc$5~@ N3,$$I>J5~ mF:3,$$}~2=F/Z΍5~P̢J3,$$mmC쵀v5~8 ^0U3,$$4úיa75~8`n3,$$x?+;#yf7;5~@ u3,$$dm5~X)=u3,$$% ,,T/N:5~X~%3,$$ѳt) 6e5~X#^a3,$$=+UźmԲ5~p1'3,$$U\/~m`j_stW5~XCy3,$$)kb̰5~X5QM3,$$ ĘkoVh5~Ǭ3,$$9e ˻}5~@5Ri3,$$K z5~XwK3,$$/Id{ޠ_U5~Xd*3,$$y)af*X- f5~XW=3,$$+SI\ -(W>A5~X‘3,$$I{F#s==5~p H,3,$$?wO9ߴha5~pE3,$$L6 kr=5~Xv3,$$_rƣJ+5~X[T3,$$N+"#:(5*w6j3,$$bo+uQ 5~X`5x"3,$$OZtUH7j5~X X3,$$5YϪ?,ٞ5~p)T3,$$Puvev Ov5~p3,$$flazH;5~|&3,$$VTճAU4md65~Xk*S[3,$$zQ4š2(+/%5~X%3,$$*p2nPX3c5~@83,$$|-&U%|5~@&93,$$#x/Fjff5~X j{3,$$ ֣r[2$L5~T83,$$^|'qYGH5~XJ$3,$$qF;!/4,I65~X>ZX_r3,$$QLoJc:5~@)3,$$`X5~X3,$$ӳZӪp`5~Xe3,$$;{Ht\x5~@Gjj!3,$$hUm7\ٕ̻%5~X,{3,$$'Os{d5~n3,$$꺎-G$kr5~X'z3,$$aUUG_z ~5~X pZ3,$$-äI8steڵM5~Xf-֥3,$$C׼ƄAބh5~p3,$$:yҧO!^55~Xd9&3,$$79!FܪN5~p%3,$$bMMScmz5~]3,$$tg~wanaL945~XJ<z3,$$KՋM^tk5~X ?F3,$$*i._\-<5~h'~3,$$8?0;܍v5h<R3,$$ !1_1m5~XL:A3,$$pn={2M69;5~X63,$$Q&evDU 5h=,63,$$gF3M 5"5~E<yL;3,$$aZwaU!+˦5~ .@3,$$Π,Ptr#5~X/3,$$Jydf%!y$05h3,$$]o S^)l5~PQ(3,$$,PEw5~PJ3,$$YLV!Con5~"@3,$$_+=#&G5~8w6!3,$$yJ]q{35hIxs3,$$HKDU»f 5~P}[3,$$!i-P73t.5~P3,$$G#N-?aO5~P1 3,$$==VьAnL5~/dW3,$$0Z̰`H5h}3,$$;>)@A.Fh_5~P3,$$aEn?#Ut5~PF03,$$/3y;8qe5~qu3,$$/WA1k1L5hcB3,$$35]Eg"E5~P*X'3,$$mu UotQ5~PFTO3,$$: Ih 9hΨ5h]L 3,$$j>K8Цj5~PT*3,$$M-c( c.} 5~P fm3,$$S-a; 0;>}Ҏ5~PAe3,$$͙SI]5~P)\f3,$$1g,gD_T5~z"3,$$9cf*JZ5~P5r3,$$_sAby35~PVIV 3,$$X!",@\5~8C9%3,$$xX@B̍=5~8#Lp@3,$$R2`ġ!NMhUsU5~8 WV`3,$$63_5~8J$Մ3,$$85A#gʤ@>5~8˨#3,$$wɆ]~! oU5~8Wk3,$$jpn)͇˃5~8 $03,$$B%o$Zf{v5~8 Xؕ3,$$(}$v:Wyt5~8)U;e3,$$oO]Eá c05~8[3,$$þ7:5~89OƤ3,$$o~~3Yu5~8 O3,$$3aUgQ5~Íg3,$$Vp8(fx=*=5~ zz 3,$$_.wbn 縲5~ ӱ`|3,$$D=|e5~i>s3,$$i]^`5~6I3,$$)΋,e5~#U3,$$f]?? 5~;6(3,$$fl~DYdv5~4aP3,$$Y9w|:5~;h`3,$$вg h&С5~"d3,$$nCf|IlwXA5~av3,$$ 6IͼR5~83,$$ƚ<Σ5~J3,$$\O";>1U5~L5y3,$$5h?yF+M7kB"5~js3,$$ (4|2F!s5~Aa3,$$\޽VbwZ g5~ 䨪Y3,$$ݬbS5~ 3,$$P̋a95&5~ 3,$$ۨS\}ލ$5~3,$$}p}OiB҄5~v/3,$$8,h-_yV?5~q3,$$auc 5~[U;3,$$} ߺEU88G5~6\3,$$+gL<v\z5~F{`3,$$D*6Z5~Y@P3,$$UYCFwaa5~` ^3,$$M MU5ǖ;5~EbH<3,$$ kBdH(B}5~+3,$$}בEg/5h{I3,$$-#*D5hK2؀33,$$Dx),35~Xڶ<3,$$sYDƜ5~'L,3,$$7ɏ0'i"5hs%3,$$X4OoN܄5P%M3,$$sF;+3,$$8B k0D]S5hz3,$$*, 9siD5h.=3,$$rTCO5h7n3,$$th#5S5~P ajM3,$$f&{!*5h'R9z43,$$Es z $ M5ha\3,$$OlİpAt5h'3Y!3,$$pKVo6a5hk3,$$#EcM(2*:5~P_3,$$Mna 5h)3,$$L_p{]#7ustE5hiM-n}3,$$^"cD8e85PN3,$$/1*87]t5h-7qH3,$$ĂtP#5h/=3,$$eYӢ10>+n5h #33,$$'%c#  掍5h_73,$$ s;M|D5h73,$$nwN9ގހRNţ5P$3,$$$ߌc۴VDV+5h PƆ3,$$j7e)if)sua5h&8f3,$$}vQ5ġk{ 5hZn-3,$$g>)BI, h5h g3,$$LSgCY,5h"!~3,$$(+0mD]7]W)5h#"<3,$$+~k!P 5h .3,$$+{1t/65h$ۛx3,$$Šx<3sD5h!"K3,$$h(hV65PMBI3,$$)) A6Ph5hxnUQ3,$$7@nCo'65h4#L3,$$ tАd~;5h3,$$z{w ̊XI5~P &O3,$$"ȟǕ|5~P 23,$$NVyjMQYz5ha3,$$"Ϋ4h|M5h{fB3,$$ mw* l5hjq>}3,$$^n`4G(5~P2wNRw0 (3,6@DI*=p xqx?2@"$ײt bgYx Ι+>.".?[\@LZO(gJ`Lz/lpƵR}LB@Ow0 'P. $IJo-MBH0oH4!*8$=?8T#Ʈ^zEbTdS ytpOЕ$fr<z 70x/]-;F03U47Gaw44XkD9P WΘ%JOX^M?sU 0+:a'l1 8pFJWZLEMiZEPdbthuTp:vc&7 nNQ}Q  S l JpxO[m3gg(*7մ:#9?"37h@q} 6:rMm ,jƄb [b^|dDwd\v'2kyum~.x J{ĞAro}|QWb.6&/7 JH3;0H&tM>aP}lSdo^Dme%(OgL`jᷙsJsDlJW~2#$<[ <Wp #X ?" BL( EzJc8 FYxX R`5 [@ e9 pR( ~jc& 6p 8֊ xS Re> Ѕt #f V4f ߢ}( g` ] yz 7uB   [ f: 2 fuX ju yfV  IY b E d0 1 |  < ϰ\!  W$ފ  4 5A eg tnB'D . b$ 2  gv x4  ;X ۥ%6 %   V):  #?& +a V ]^ b& yjls" ]. J4 H  ь ʴ{J 6  (7 ke R L' r9 J dz Y WJ6 E! h, T8 '6jEp?ƟTX}wJ\ }s;\jGe\Y/4@=766lĴQlfE1ߕX|f/guA"x& 4*F)7sq;o5H],u;yygM(}7^rxMxpfnP@a+X!0#JfM:H3D>9rBC\VGopY~XN0ǻ}T-R T/8XO[P,S5!WBZ~AΑEuʿ*+:0(!Z!C%^HiTfNcK|mnn,pSteCvl;6"|::Tlf v?uBFCcI:W6q O:42cva+w@ EUh0t6EKnK^8MuZbWX+\-_vwgRTrg#sH$t['GIUؐy,jP(w*^{./U2/k=ͲlO7(btNhgA^g$#Xn5ns08[Z`4{&X:1X )PKH&O9O|jOvPpyXT-VhK3֪y٦Mx|N:tP4D2 & Y)nxJHIEzբfH,g{8>)z=^u}"g3<GJPG]1p/wQ:bL`so4 p}z$jVڶLz›\uo6 dOA~e<TQ GcFbnB$u|&^<h6TTUSz{TOڕ.adൈ:C2]>V_,&'{)}pxQx|~ fdG3qx4ۓ޲u}l>Dli?9H sfZbB~@@A}I8S|[WR>pb~@T&/C|w30o$p#%/ъC RVQXfXFdVuE-4WQF(t#xD.Nx$nL;"8:0~S,03,$$3!tݣ%qƛ5h3,$$o]"+e5hz3,$$q"U!p5h]3,$$n<7_bAl5h h3,$$kꦉ"/5h*K3,$$hOQs2i6K`5P!3,$$|}GGB5P%)3,$$taz%ᛊbmտ5huo3,$$2tD#$Ԍ5h!r3\f3,$$|~Ѣ@2,5h@3,$$w/X8ܧŐaw5PkW3,$$p?M3,$$=_}Dv35h+iv3,$$MYz΀_&Gq5h3V3,$$9"LtyPֆ@5h-a3,$$Su_h/g|pu̐"5P^Š3,$$(Adz1W?5hG3,$$ O InÇvc…5h03,$$pCx$c3YΠc5hBCuL3,$$֚Z F.75h+[JS3,$$J>`S Iraz5P(3,$$P;Mf+Eo5h[dB3,$$Dc / a5Pt8ײ3,$$6yڢEUD@?5h[(B3,$$A2F/)5h23,$$_Iζyomq5h#A3,$$]sHFugivª5h$q:)3,$$t1cݘh`5hc93,$$Qtr&?95hP?w3,$$9poKy5hAS[3,$$=j;.N=,q5h0z3,$$]oRGQo5h43,$$Y %Pt?5h+U3,$$7O3J1S# 5h%1Iع3,$$Qwm .5hS*Zy3,$$wgiP>qYP5P3,$$h:>k6x5P# 3,$$``u1d+e;5h?(3,$$ꐼ:VAZ<+5h́3,$$ ǀTRR5h͂w3,$$1f5D[&pl5h(5C3,$$[$z}F455P'z3,$$Ԥ| _85P&DQ3,$$/nk!޷Y5hf'3,$$Vʦ$0 x1e35h*]3,$$Jߚ択g|E5h3,$$$r ·%5h&(E 3,$$[㭄l 5h,u3,$$Q1^ @j5PO%3,$$WI33Zďv 5P@ֻG3,$$0*df:̇5h-:3,$$N +4}?%-5PQ43,$$v PC~5h3,$$qxW>) .+5h4eab3,$$-(ʈ y]]v<5~P(3,$$e#)yUR(i&%.;5~P3,$$4X)^PURsN5~P9w3,$$S,JVg?Z5~POg3,$$g{h*y$v5~P, ?ް3,$$Lx;*Gʉ$5~Pd\3,$$$6N!K*}5~P42P3,$$Q&1Ik&5~P8'Y3,$$1o@ b;+5hL:)3,$$hAf?ON)y5~PD3,$$( e95~PM3,$$X.B!$EL5~(iP3,$$`4o?25~P53,$$9@mX YY5~P 3,$$߷hu5~P[ *3,$$ɞn毞U-5~P?#3,$$,p&/5=?qu5~P;^sH3,$$bz2H4x5~PIO@3,$$56H6Ӎ75~P~3,$$FģLɉGֵ~,5h~ 3,$$ ~Sb yzU5~PR3,$$% H5~P6ȥ|3,$$KX?7 d\ 5~PY+n3,$$P/y.(֤i)5~P3,$$\Q r5hD3,$$+嘑$Lّ5~P X3,$$֋WV P! 5~PM[\3,$$+2& HAF#^ix5~Pᆥh3,$$o`c}#C5h Zh/3,$$㰸E8YH5~PM3,$$aBUa`J5hQh'3,$$dtL> ʃN'5h-3,$$% j)q?VZU5~P"\ڪ3,$$FYjK: Ux}5~P-S93,$$k)6z$%s5P W[B3,$$#'E֘"YJ5~P$I ]3,$$> /Bf@vl5~P3,$$w0jw?d|D5PTWB3,$$"N ԙi5P993,$$"p͙?}jK5P-3,$$ ӾYP/&5Pح,3,$$y<*Ă5PB"3,$$jdU<5PT3,$$2v<5h*C`}3,$$Y֢s=75P(3,$$#;ȧ;Fgs5PX'3,$$>jIR(5PJ3,$$N#{ 5hf3,$$B|JHJ`C%5h~vX3,$$4 7o;O 85P3,$$ު-x 5P}h3,$$@D\) #\5P}5U3,$$:3X#vsz5~85~P0W4yW3,$$~Hѥ5~8}3,$$].-V!Z 35~8zY)!N<Qw 5~8oŌ3,$$a-K%g*ZK5~P =3,$$J.BԾ-l5~8u`3,$$Gx*![4htS5~8Ec?u3,$$k^c#P5~8X3,$$t}ZCeR|5~8 3,$$k]4Cr5~83,$$X~膷|5~8'83,$$,jLx5~8M3,$$"Ow45~8U3,$$!qCSgfT`5~8tz3,$$Uhe5~8213,$$|<Z" >˧5~83,$${W[^{{y# 99~5~P:33,$$Xދ}5~8%3,$$hbjح5~85f3,$$XJ/kd5~84D3,$$T =Fs# 5~8 L3,$$x .ɅȄ Y85~8쎺\3,$$_]/)"E5~8oɇi3,$$PP4md5~153,$$tib{F=>a5~8]3,$$cJ,5~8 j3,$$+CL5~8lOS3,$$k s|$5~8(mQ3,$$ţ'kb5~8Oɏ3,$$zXS;+5~h'L63,$$]щl3>9]5~8y%3,$$X!:5~8ƿ(3,$$I.@`^W5~8nG3,$$4J0wbtlKѦ5~83,$$Z"OlSk5~8V 3,$$`/X&4φ5~8;3,$$_ q,Ơ"W5~Pu׫3,$$dRrOph_?y5~8/j'3,$$%tk:wv2T5~8ጵ3,$$ \b2XKݤ2Ps5~8~3,$$A$ȟ5~8Z3,$$ ~l4 ~N?5~8"=3,$$2% d1/ 5~8?3,$$-!+5~8PK3,$$' ʟ(5~8D e3,$$jvϘo<5~8|3,$$Qk $Fom5~8+F3,$$]  L1Nɢ5~PQ03,$$4:+k01x5~8  3,$$0G5~8~t3,$${TBlX(Aw5~8t3,$$aOM^0R5~8|Ɖ3,$$G(x {кR5~8пCS3,$$_?jP`93<5~8c3,$$ o=V&ֵ5~863,$$K\(S|-5~8O 3,$${W3K=5~8?Xv3,$$Y@[^5~8k%3,$$HKƜrɑTi5~Pbx3,$$ƲhhnAi5~88743,$$`2&| %z5~8p3,$$`q,#tmUE {S05~8K 3,$$*)x$$5~8k3,$$F6d$8E5~8.b3,$$ΪY>5sγ5~8?93,$$7Y6xFs5~P>3,$$ЌTVꗝiA_>5~8tI3,$$tZԁA6FT#5~8X3,$$֒jr^d5~8ƌw3,$$Зcx۹)5~8?3,$$-KRG@5~8qS3,$$ Qr+5~8A3,$$!CuV*w5~813,$$svH\J ɮC[5~8-g3,$$B.0Πn565~8'G3,$$;F 2UÚho 5~8@^I3,$$ \` ̓ӕ1]5~83,$$ehvBE5~8a(o3,$$26w.t5~83,$$vZٜƼ75~8FZ3,$$AigA5~8<(3,$$L"@޾5lNM5~8O+3,$$ãJةͳì5~8G3,$$S_\ʞ-5~P uL3,$$}v`*̻5~8 3,$$2 {njmet5~8ޕ3,$$so(t3\v5~PLf|3,$$Ưڮ1NjRҺ5~8G˶3,$$A'[L 5~8D.3,$$Ŏ9LFš5~8 3,$$6j"c15~8Al93,$$/}+qX*5~8>Z3,$$T:ǰ&̯y5~83,$$}kE>WC5~8!C 3,$$ϴ#! /5~8:J3,$$r[Jr5N +~[5~89Dy3,$$iسs[׊ 5~8͐&3,$$|Ɍ3w; " >5~83,$$< Δ1&5~83,$$8nxUd窶yjQ5~8DV3,$$۪` zHr25~8h3,$$GzQ|׸rT5~8޵]3,$$(?ˢKߩwI5~8Jl3,$$w5j 4~5~8F_53,$$ݫHL\}75~8J3,$$lc Wc!2'-5~8SAA3,$$g'NÕij5~83,$$΂aD vh5~8T3,$$>t :5~8z@ L3,$$gkZRpҼ M35~8R-3,$$%L4͠cX*1i5~8~3,$$ 77݁CL65~8<|3,$$lQ(r5~88-3,$$!vM6Zl5~8%3,$$Mg 8E7 >$C5~8%3,$$w6>BS T5~8.L3,$$; ^QYXi05~8̥y3,$$Ha[BR od95~8+`3,$$;N)wo5~83,$$iVڌvCeQ=g5~8ZX&3,$$ø)گj!O|5~8OJ3,$$$&\mˏ1Hq5~PzF3,$$&f\L(_D5~8|]3,$$!k}95~P R3,$$f֪;9Q5~8nXX3,$$pvBVWs\Hl5~h}3,$$lڸ'z$ 5~8}|z3,$$(o55$Ex _5~8(b3,$$HkncV}5~8v\3,$$Gn+^s b5~8T<73,$$ϱtV5~8 ~3,$$Լ%}id5~8*B3,$$_2cb5~8K93,$$H1SEZs(ZV_ύ5~8O#,3,$$X;t?E22>5~8W%E3,$$YgUjSz5mA5~8H3,$$(f#h5~hȯt3,$$ @NX5~8ola3,$$JJ{ vyW5~8u3,$$IQBNRy5~8K3,$$g⠞t>TXƺ5~8µ 3,$$p9drʀ!5~8u3,$$&Kzz'8; {5~8{ƙ3,$$q2$weZ@5~8!3,$$S :fɅ %&65~Pӫ3,$$kfdY<;t)5~8Rh{U3,$$;AG,r55~8Ԡ~3,$$Z);y?ˍ5~8Z|3,$$U )u Kv5~8C3,$$o\c75~8FÉ3,$$4ד)8':ʩ/5~8rF3,$$`o Kgv1"5~8ί3,$$O+s-k%?5~8}|3,$${XؐWNq8{5~8D\3,$$#Gp%ƑA'}5~83,$$U8EOm5~8tW3,$$|k~ kW5~8O3,$$azgvQFxՕ5~8Zx3,$$oN%^5~8)83,$$N^ӜD˳x5~86,3,$$pSPK"5~8,ε3,$$*sRU[C<5~8Ҳ3,$$_PT"4h5~P;p3,$$k0O&G Oq 3qh5~8=_3,$$dA\cR/05~8ղ{3,$$CU(빠5~P13,$$uΑu_&TlM5~89 p3,$$B)JOЊG5~8N%O3,$$?g<66Z0F5~8C3,$$PO뉓 zm5~8je3,$$ j7Ku5~8&3,$$MJnOOE5~8'r3,$$H:IȺ65SI5~P!I3,$$7nzZ8[)5~8>3,$$M!b_Rm)l5~8 ȍ3,$$P~ɜ?3[5~83,$$Lذ\pAtF5~83,$$}KjQ!m5~8y(45~8"3,$$bNVu>4,tu5~88-&3,$$NϮaa[ 5~83,$$ BrjqzU5~8=}3,$$08.xN82z5~8^i_3,$$s/qwmv$u5~8~=c3,$$G:yFQz<5~8Kb3,$$~4Y^5ːUT5~8XL3,$$xuIJ;v>5~83,$$P{ɅWVCn5~h!Pl3,$$Hs^KBY5~8hcI3,$$ 񷲟] ץ5~8[3,$$+''! l5I5~8D3,$$dPC4z (5~8p3,$$$zuUq"x)G5~85rs3,$$o֐]%(gx5~8}ή3,$$.XkFp8:_5~8\!+3,$$s8Wg5~83,$$q^'Բ2LԄZ5~8@3,$$Dp#~[OKT5~8!q[3,$$j'dxNU5~8B#3,$$#(j5~8K3,$$TNH=g 5~8*3,$$o箎Ŗ)ڙ5~8.3,$$(Y{ Ts/5~8E3,$$&Z\_gC5~ n13,$$4z. 5~8JzY3,$$=4n!5~8!`N3,$$v q7?B5~8n3,$$҅ ٪ᗠsG]A5~8+ю3,$$U7C4L5~8Ί 3,$$!o\׉5~8d3,$$ZdzmF5~8C!3,$$ KtѦ;g5~8g3,$$5gJ9l+5~8X3,$$[ V4a5~8|H3,$$[6R7xpY 5~8J(3,$$c *DIz5~8P*3,$$!ƝB&JU5~8J3,$$xv0.~0%6"S n5~8%b3,$$Uy \f5~8 (3,$$Iqԥ5~8|N3,$$!g V<5~Pڭ3,$$)%yl{X"5~8CDZ3,$$7agkq5~8$E"3,$$@{ ~08J&5~83,$$NφIe+l1\o^5~8r3,$$!A;oG%R5~8Ha3,$$"iEe E5~84>"3,$$b]\CwZ5~8" 3,$$1 7䡠n5~87s3,$$h}Qz`q{5~8o_w0 ?w(d?T~? `z?)\?<}H? W?1h?5P&?Et?"l?jD?I„@\>@ .&@a; @i1@| @ @#@92az@Kh@hf@}Z8x@m\(t@>6;@N@Pq@'@@Ĥ@ª`H@{!F@< @&K@]P@At"A.@A3A< AA}A_AhAVmA'@ADAWonAAA9hkAɟA B8BLB2BD$B"CvB8B:d[BELGBKt1*BeBj/.BmBpNBtX`Bw|BB4RBABrB@oBBixBtC7CFC%6FC9> ,C;ϟvC>pCbCozlCrY\lCw.rC|1yCS) CQ6CT.C"CqwnCBQe,CCTHCUeCUXq~D˶$D{DZD?E:DLllDQDR"7@DZkDZD[|PD_VrDcs0DfZ#DnDVDBGqGctGt dHjHϾ{H$V(H$:H%H65v<H:vG H=PYHL=HT}HiV.gHQ lHq@HU bHh8HA6HDhH)4ICI7UiI :I /=IJ(IQ.IW:yVIZI6&II~IlxI~hIث_JNܨJ%P<J) kJ/uJHJHJ25JX|JXJ|JQzJ"aRKLgȸK [_K-r|tK9rK:0ƘKBh(:KD,1"KF9:KJ KlWK{<KKKhK+K 0KKq<JK@ KL xLKjLj|L;p8L$mjL% L,7~L?u&\LZQLmL0LčLu>FLlO@L :HLs\M$^M)Q)rM0C#CM1ZMM5T4_M:MVB=[JMWBjMq@,Mq)MMd\RM2nM#"6MܲM9pXNBNN\nNt N d.NksʈNJ3XNVtNN 9NSNPNѵbNՆ5N:NN-%O qO"1>O$njOF8>OOO_64,O{ vO~LOrO|~OOζOg6 K1RI8$RR RYvSSvzGSzJS#SaVS2hS<SbSxTlT\zbT)0-'~T\&T=ITcIT} T4[T~K4TtDTUkU+@XfUKޓULFUO+(UelDUien?VUyJU+*$U4UU|y{UMS@UG7U+k'Ub U[VUh~VQ|V*jrV? `V?VVSrtV^P>VXV~2nVO V_VA<VɅlVܬ?1Vʀ%WgD"WkERW7(6aWP7~WTdWXc\WjuW{ W~--Wې W*~W> WgW X)+,X )TXX *VX({0rX,@(X0Xff"Xg#OXqXuXvDXlX4X(XԪRX؉&X9%ZY WTYȗVYHD_2Y^Y"qt Y'z,dY)+lY4 Y>}nKY?@YCɎYX JYPTYsbYY1Y!Y-oYߴQ&Ys}YshZ"KZ#4ZDcp0ZS(Z]xrbZ`RDZb'.JZd,UbZe3rWZnk6ZN`Zp1mxZeZ"fZuPsZΖ |ZoZ{*ZKdZ}d` [[J"&[!_j[+BWS [+![/1dV[2 8P[8'T[G[Q[h=<7z[}t[-[~2[߽5[Ԁ[C[\ oP\B\&Z<\L+\Oi\Tn\kVZ6\x\\-\\Th\p\>\\"2\@t\#{]w~] V]\wL]-f]-b]YBC ][]c ]{x] ՞]]?E=].^]k"]荳]y^*^^7uGV^;FrP^ZŎ^igrH^zW^^4^:^[r_w&j_ wQ9J_ )_ H+ _)M|_g O'R_n"_p'd_hB_i*_P{}_-f__ר0 _S?`i`c`&l `C`F<N`Ps`R\Q`UȼF`v*`R9`~`"]0` `J~`S!3,$$ˌe[&/vs-5~8x3,$$͒<$y|5~833,$$3"`<@k5~8n[3,$$E(Yi\Lkf5~8QP3,$$-o@Q5~8I$i3,$$ 9+ղ5~PҖ93,$$E:M r65~8эG3,$$nk]- ^Ng5~8C3,$$#3e'3R5~8#3,$$鼙@*5~83,$$$[,qMCU5~8_w0 q9 \sR\͠vwՠqX[x!;9Т>>Wj(B1| E OP m[‡M`TŸ/j¶DeP֙@3OZ[]0Z o66@^q/fEڞPPF[W8_' Dk3GDÊ ^÷`ښø&QTZʻ ?\M0 f-X1) wąpĆ6ćp-ĊĒj3ğƑxī`Y0ĮIĻP0 ĸl.䤗xɞ* > Z6:^ Flo$Q"f-'>.-HJq]\nsoŏDśGŬ3dW{w@sQR67GY[i=Ɋv5unwJq{OƂƲP:'V`B03Tu FVU, ;F 05bzEs"H7.a*DžbǗK]+Ǘ}ZǩBoK*kxPef$+3$Q `@m7Da hOvtȌw8̶Ȼ7zȿMbũiprpjpپX6%3sr9K<`LdY8[>]pa1"6e! y{0ɉɍ9oɐHɤgpJ,),+J3i Zms"u.u\?x9,~˂_Rtˉ@˓9/$˴lH˹8 RU{b<&u+B0b6IޮH5HZJtZLD OpP^WB.f7,̔|̙l"̬VḭQY̵*X̵nQj̸}gy w$ jL1m>;EINnW.~\9w_9c1gD*o0~=L͂SO ͎h͐'2H͘[B͚-FͫgOͬqa;k3}Fjt <5V5Ε$&T?\#BΛkΠf Χ|^lHε4=f^ٲmB^mP[(e$D]9<1?G5H0xB{XzѡXQ<Ѳ, %2 a2$1V_F i{8mxEҍ ^ҹҽȼ;jYc~RH|,z ǀ(rv)zWl-Ky*D-HWSej<k`Ӊ"ӍinPIm~;B|XM:W^M2 4 =($YV[_? _^uԨ2z7 ԃ-ԍTZԮ~Բ(fɭ7-6ʢj~@Pv72S7|ZeP4Eo a7Ek\bE=tՄBbՅթETնF(^r({i@Q\2,#4H2OSOV4Q!-[JT_g֐p-?pִָǴRֿ|Zړv+)2LV6Y@9~}\C~uwy.܂FQL@܆o8ܑ)ܧKD>ɠˣnA LVZPw0nSQQPݛ; 0ݟ_~ݵx˨ꪯHJtd l` ڀ@(O )z4GwQ,b0eQ,i^m"GH gw(o?/7 ;j.;?¨@NX߆Z$ߊ,ߎy@ߓpLߜ|fP U=XٗOD\q!4`$(btHmgu JB{n<63,Ѓ (t..j&M9' v/*PB-bx:3,$$?-$sIj(5~8? 3,$$fYqA sSy7y5~8AD3,$$gNx\gbO5~P#Ź3,$$'}x֡OAjk5~83,$$&u 05~8P.3,$$ϼ".yʭ5~883,$$f}nEv<-KQ5~8Lau3,$$s~aiphE5~8׊3,$$>ax}vt5~8U 3,$$ҹD @CA5~8/3,$$t.#fL{,5~80PGi3,$$ZQGk 5~8H'3,$$hK @_r5~8>'3,$$Q)bJ/ HI5~8O3,$$Uϼx=1Oe5~8a3,$$<p?85~873,$$]Ƽƚ};v2V5~8}3,$$/B[J5~8"$Nz3,$$ݼ=Vփ)Z#5~8\*L3,$$HM5usyŕ5~8w%p3,$$q0>5ӫAh5~8(m3,$$"m7ZIL5~84VJ3,$$ _nnihe3":5~8*f3,$$R@*5~8[V3,$$D \Cژu05~8 %3,$$K#e 4*<5~8ݩc3,$$g g׽30,{$5~P?+ Y3,$$Qdu`5~8k3,$$E:'\|~ρIW5~8/̜Px3,$$"TI+7byZ|?Y5~83,$$q(JC\~/֢5~81a3,$$|9+XYg֓5~8'3,$$*^Ւ .@J]d5~8T*k3,$${nu{ލt5~8Aɫ3,$$U05 Gd`15~h>Qx@3,$$ޠ 5~89`8D3,$$b9b߁!*1,0&5~83,$$GDW < R5~83,$$)hT?1w5~8 K3,$$a7n,k iӋ5~8 3,$$~(P JR:m5~8q3,$$%|ݠ'zS 5~8N 3,$$b^@ajM5~8z%V3,$$!7y5~8w3,$$&ؠ9'5~8S 3,$$. TWq5~8@3,$$ kXL^/25~8[$3,$$~h@|VT~-t5~83,$$qJw "VQnvg85~8HyU3,$$:fB` 05~8b?<3,$$;S苶D_5~8s3,$$qjkEvn5~8s3,$$r9qP#c䊿b5~8֊>3,$$ҟEG,s5~8Х3,$$A֫|@5~8tPu3,$$zAs1s!f5~8pR3,$$8t9|P WW5~8{3,$$^)K6^TPW5~8x3,$$Jv)ujKdWI5~8x3,$$wڷ[4̹,Q5~8J%$3,$$V"meez5~8:x3,$$ޝŕojqA5~8 ;<3,$$<,p($95~8y 3,$$Fp'4R}Ķ%5~8)H3,$$tA^ v^[f25~8"Gc3,$$A`P o:5~8b3,$$.555~83,$$q]!&k5~8Ke3,$$s/]b"t '55~8/s3,$$pKWs& ȟ5~P+[E3,$$Lf'xy2fZ3 5~8'?3,$$Sna.Žm85~8^#N3,$$t͝KJY5~8J=3,$$X#`5~8(SU3,$$0&XI W8*5~83,$$ߡĤ;f`85~8F23,$$Y oXٻKRA5~8j_3,$$z{ k5~8 i3,$$jZz kah3,$$YʤO'ˋg5~8sB3,$$:N9sɁj5~8;.3,$$(,0rp[Q5~8,3,$$Fu 5~8n>3,$$vw%MPH|(.Sh5~8P3,$$O,|m_T5~8"&i23,$$3SZEULT5~PE͟3,$$=/)i0l-Ua>]5~8;3,$$+גAT5~8T3,$$p:\"?m;f5~8}oV3,$$]UWma~5~8/D3,$$U&zd ~45~8$zت3,$$'hᵍY"5~8v>̓L3,$$Izx%l>0)a5~P/ x3,$$/CdN`Oۆ5~8So3,$$46[zoSe~5~8f73,$$TU )5v5~P0|3,$$`\I]P"3,$$6a0`5~8F[N3,$$&imBۈᝏ5~83,$$,~:C bh5~8G3,$$o:xwo|b5~8AH3,$$:$3 uD #e5~8x# 3,$$S%+~a!D!-5~8<. 3,$$U@~jWk*5~8d3,$$d!쉸`-j5~8=3,$$m Jr45~8~63,$$+ː}ox]5~8x3,$${;%+?׭;5~8K3,$$MքSȣS@5~8|3,$$c3xK5~83,$$@*X$#pas5~8_3,$$ܒ'<ʜtڂ5~8L3,$$ۧ閌15~83,$$8Ē'ZI5~8/1`3,$$ q,VkWa5~8"3,$$MtmYM!r6$5~8E83,$$v ( dҦm)5~8t3,$$Bf0mmD>5~8|<3,$$cpBꗺ5~84hFf3,$$-}[hh0#XcFュ5~8v3,$$`e@Nd=E5~P(UܔT3,$$ID@$4ǩ5~89RfV3,$$;K?Z'5~8=#3,$$>PSNQ]5~8]!3,$$e2;v5~8 b}Y3,$$\{tL*\O.;25~8883,$$nQfHK5~h𢄿3,$$ʊx(gFp5~8{83,$$?y\T9ms5~8;>3,$$S"30TY$.5~8(zz3,$$cܔEsP/2:25~8`w3,$$ZʢeJ?5~8t$3,$$LEVxv5~8w43,$$!H+sU>'V'(5~8ᝀv3,$$؋f~L5b m5~83,$$'r5~85~8m3,$$aYT̢3~&5~83,$$oŚ+qg5~8vr3,$$4Y6 I:ys{5~8Wm3,$$x cM[&5~83,$$2/ev#5~8~t?3,$$,8"PG smӲ5~8>j3,$$P.";5~8$23,$$/~te%Զ5~8(yFr3,$$v0w5~8A/{3,$$)gn,qB5~8 3,$$NUp`Z^5~8-}8 3,$$׹3\0 03b5~8"3,$$@gX>V֜Ə)U5~83,$$!UFR:W5~Pש3,$$ *lFB5~8ܼ43,$$?'(|$%tW_5~8Jr3,$$ VD/Q㪑%`5~8a3,$$bg [z95~8by3,$$` B 2!w5~8v֜3,$$ yؖ5~8oC3,$$#_y/J5~83,$${dFkF>E5~8!T3,$$4¾uaChX5~8!w\Z3,$$[BPBҐ柺5~8DW9l3,$$ly7;0I5~P 3,$$$Gcknq5~8C3,$$&*4KTL5~8R3,$$p93Yxߏ5~8#oq3,$$bTǢ g2vcxb( 5~8~3,$$쨕ѣ8DE_<5~8|3,$$CX͊6m5~8x3,$$?a`Qw @5~8,3,$$1>S%!Y2#g5~83,$$pZLXd0Z=_u5~8}3,$$?ey},-X5~8,3,$$7&qI5~8\3,$$~|5e"~|;|5~8(;3,$$R]wF5~8)p3,$$J]3}`M5~8ѥ+3,$$psqc}'r=z5~80Ԁ3,$$0 r9Uq9h5~8z 3,$$hCcea5~8 p3,$$'aшpSe[|5~8hY3,$$Vm9Rf?5~83,$$#Qg<5~P3,$$jlLV86,5~8~3,$$Gj a5~8T3,$$iO# t)ɛ5~83,$$SG)kc'2B5~83,$$\Ьb8 M5~Prrߒ3,$$d$S%5~8Ι3,$$ uvP6B5 5~8>ϣ3,$$x]J+@{Xb5~8r3,$$C3H`0S`ļ5~8Z3,$$&= p)5~8`%3,$$-tn=׵km95~8}Jd3,$$0Mˤl5~81D3,$$+ 27a5~PD3,$$4+a5~8l3,$$4@r&ڠzpj5~8k;3,$$.Kfu?i5~8{0~3,$$1Ο i5~8x 3,$$E:^;krE5~81,3,$$Y'=C"5~8' 33,$$Dv_;aSC^A5~8v 3,$$dXOA5~@P3 3,$$Tá ^qa95~8\33,$$]OJ;5~8.j`3,$$-|I82~ڠZ#5~8'3,$$u{^ASmD5~8s}3,$$R_(u""NM(׉a5~8X %3,$$@F5)È5~P193,$$]WpOYmdR5I5~83,$$ݻ>lg'5~8%3,$$=G!a WQ5~8'`)3,$$G&^„5~P Z~3,$$Wrc ObcCf5~8Χ3,$$ԇ?fzz`!5~8 ?Mq3,$$3T㵟SnE )5~8\3,$$}WL<5~8QeB3,$$!8uoy6}mR{25~8$$u3,$$> Aj5~8/Z3,$$m݃vQmŗ@5~8?Z3,$$[GnsK?5~8@Ҟ3,$$dLX]p-V5~8l<3,$$YLLdnj-3<5~8&3,$$[F%M÷5~8,f3,$$a~7[pt5~8K?T3,$$֬ KE5~83,$$-'9X 5~8'՘3,$$eCw7U5~8\:3,$$Pjudr33,$$e3zZl5~8У3,$$kӃyeO~5~8k3,$$ޫ^W/ڋM{h5~83,$$Sr`&M=s5~8Fi3,$$G/"_9q5~803,$$ RȻر9ǟ95~8u3,$$UN-9(5~8 3,$$UpbRܨۥ5~8෍L3,$$]m9 >35~83,$$><쯠FU<݅x5~8&3,$$dK~zl5~8ԯk3,$$lNH T r5~8P3,$$& u\5~82b"3,$$^j׬gTD}5~hj#‚3,$$,"+KBkFx}5~8@3,$$~!r~::5~8 3,$$C`Y+bg5~8Rk3,$$ 08+w&~5~8ϊÓ3,$$jș(>G=5~8"W3,$$9O'agP*5~PybW3,$$&u8 dn"5~8Z3,$$xcW5~h3,$$q ILG|!5~8v3,$$19o4{]&*bHH5~8S3,$$"=Q\_l6]5~8]Q3,$$ tL猀o5~8@hY3,$$Vz`5~8d%:3,$$@rS 3\}5~8t1*3,$$XG;9{ʘwg5~87UC3,$$4 0:pX`5~8Kw3,$$͂~[z{!5~h?t!3,$$gp$s 5~8y3,$$p{r<ޮ55~83,$$%Q1"GD5~8s3,$$sH? Y˾5~83,$$A|* Kf׏5~8_3,$$Z_{-5~8x`3,$$2~B|1iYn{5~PQa3,$$f+"[F3u5~P,!3,$$FR6f5~8623,$$I@"-x5~8fQw3,$$"Fv4t5~8<73,$$eoE$g IA5~8?qP3,$$^ý5M5~8e]3,$$U&KbE[5~8 >3,$$YҠҾN 5~8wQ3,$$^>HrC;5~8І3,$$aruCxQ5~893,$$f, O?Y{D5~8tK=3,$$="bʎƻ(5~83,$$}#( J~K5~8z3,$$&l ƕe5~8bm3,$$#CV*vl5~8313,$$MCAQc5~8ÿx3,$$?>PTd6u⑸5~8$d3,$$NN.Ü05~8&-3,$$܉@&8NCn*I5~8T'3,$$16W]]i5~8,3,$$<^;vi>5~8z3,$$Kk\v/¶ 5~8`V73,$$fC"2EEkB5~8]-3,$$2f%VvxC5~8wP3,$$A4@>P5~833,$$Mh9ĸ-5~8"B3,$$~A&ڹcE65~8I3,$$gMg6hgI5~Phc/3,$$Z^:-}iC=\\p5~8d3,$$۪ph I5#j25~8~3,$$x"D:A5~8HIa3,$$^?FR_~5~8$3,$${!,iԻ2̈́5~8w3,$$pV7s::pu5~8@&3,$$KyɃګj }5~8[3,$$o8wZy$%zL5~8l֯3,$$T@-dh5~h  3,$$]i8h2R6*5~8!G"3,$$_*N&VA¬5~83,$$8otU>r_5~8(pq3,$$cgG:fޕ{-K5~8gv3,$$gµ兼(5~8z4\3,$$Dz -h5~8 +T3,$$&kH9ou5~8$2(3,$$E'D%45g5~8p3,$$ i9}8n5Nno5~8zָ3,$$^A3 K 8Mf5~8 hsE3,$$evDgbDb5~8*eu3,$$hm8 1^O5~8D3,$$癒M|š`J5~8Si3,$$5m٘}|:(h5~8]3,$$)< 2 5~8xh3,$$._}r9BX 55~8@%V3,$$qvNCtp`5~8!^T3,$$gJds/{E5~8}C^3,$$Z|aAOc5~8_83,$$za5~81I3,$$4)AP ^e5~8YQ3,$$YtΒ]}5~8$ FU3,$$ɣg9U5~8E3,$$hp4a.%DZ*5~PQ<3,$$ҫ1rt~UwD5~8-3,$$'HEۉ+߷C@5~8v3,$$!e@,;:G/C5~8leR3,$$Zϭm$ /5~8 w3,$$S63˨0FO5~8߳3,$$0:U4ϲ5q5~83,$$` i&pP5~8ϲ 3,$$.g.蚒dtΣ5~8!m3,$$Fp+D5PIU5~8 Va53,$$\xeS4'%oG>5~8>3,$$@Nrߑ}>-W5~hak3,$$hp=B*`5~8 P3,$$C6+Se5~8&A3,$$4|Z4i25~8-B3,$$#)W1=jĿ p5~8C+3,$$-?1(~dH 5~8r3,$$LMNujrv5~8OM3,$$+m g5~8{3,$$W&g2^$5~8UO(3,$$oP:/#RT_5~8٬:>3,$$AZ :b-e&5~8΀-u3,$$X-Oʒsa%5~8Q3,$$E\6 u0ngz5~8"3,$$O';@(ʳ 5~8 fXz3,$$y;Eə5~8P 3,$$8;j(.o5~8@ո3,$$?j sZ25~hGj3,$$l;&xy҆J|5~8f:^3,$$JjPeb5Nx?5~8?_Qt3,$$,/HPϨDDF5~8ϒ3,$$ʚ upn'5~8:3,$$ }Tܷ+a|]5~8$j`3,$$ƺM\]: +5~89Y3,$$plkwU\5~8eo3,$$VZ[H4225~8V3,$$/dHJ/@5~8RK3,$$uVU[(5~813,$$1]qW}5~83R3,$$qkrr5~8Dvc-3,$$qgVqa*\)5~8U͏3,$$',a%5~h';q-3,$$oYȔ;%C5~83,$$BObr0ZN5~8-P3,$$rМ4[mt5(>5~8(3,$$KR`d5~P<@E$3,$$E dCKRrL5~823,$$V4g @V/5~8C|M3,$$74qE~5~8’ 3,$$gnX{W Bh, 5~863,$$ )RL5~8(n3,$$$J𫰀 r-L#d?5~8#3,$$kQ7{隫[lD@5~83,$$;lMrOp5~84SA3,$$xX kyT5~PH.73,$$ ō: /JK\5~h;3,$$ HZGˡ;a5~8F3,$$:C=d9+5~8Þ3,$$|1.5~89O093,$$oTׁD925~PC#N3,$$^GMvG#5~8+H3,$$a i "R5~8W3,$$sG@:tA*5~8tk3,$$dRQ?=c|5~8/3,$$ s>w|m]>5~8%l3,$$g!n"8ˢ55~80^3,$$+&zkZMb/5~83,$$7=U xWxfg5~83,$$*(*ӓ?qqW5~8E]}3,$$}4#4,6>ou5~83,$$ˑhâ_"<5~8sky3,$$V.t/Ij E`5~843,$$5w_. F¹I5~83,$$"%V$6ŧ5~83,$$k(T+5~8@93,$$Baf[(@G5~83,$$K?D!?5~83,$$EK0y*!5~Pu3,$$¯M `r{u5~8BTI3,$$eG/čRE7oI5~8ep3,$$'ѴB/ В5~8b&3,$$k;$:5~8 @r>3,$$6Ȗ ^*A5~8yC3,$$)`|`$*"5j5~8}3,$$;"oX5~8ր*3,$$`hy[po5~8b" 3,$$?! Sϰq5~8 [3,$${&Β-tD̝5~8@&@3,$$u<Z궱5~P Km3,$$X8;!]X5~8 43,$$aE'AT@5~8X3,$$T׎Ҕ|8/W5~8.3,$$Ltč5!"y5~8ƺ3,$$kR=Mb5~8tX3,$$<Zі5~8,_3,$$Ul16y~5~8u3,$$^z8[㳇5~83,$$E|32FZ!5~8Tl3,$$OrIzCeL5~Pp63,$$۩CԡzNl5~8*;·3,$$W+~ڌO5~8ӾW3,$$yxc^{ )iy5~83,$$XfՔ ,b55~8EP3,$$Y"QҪOP5~8W3,$$rY=8\Eo䋻 5~8q3,$$OO=>T >h85~86L3,$$˾GkAܣ+a5~8z<3,$$glnBjNoդ5~8{3,$$`gH5-5~8B3,$$u^2M5~8(*3,$$cڑ+ p5~8mW3,$$LO O&ef5~8<3,$$vkLn&s c/5~8<3,$$nzFV6r<5~8? R3,$$p& D:Gm.5~8Tx~3,$$x&/6@nds5~8UN3,$$UXo%4 a5~8~3,$$28mn:i5~8L`3,$$*\mO@ |byw5~8)\3,$$1k15~8M3,$$",cPr/#5~83,$$Ⱦ3#r`kl B5~8}3,$$_MZ ;725~83,$$4ThM#5~8NJ3,$$.5~8v I3,$$EBN`A@`65~8|}g3,$$r dHEv5~8 H13,$$eagEL%-]5~833,$$*V'؉F`w5~8M}3,$$Y|'΢r |k5~8[3,$$DW }\5~8н3,$$T5t6Z 35~8&3,$$n"ӑ%؞ƕ5~8v3,$$ L)$Z5~83,$$1 q~q"'Y5~8BD(g3,$$7ufoA ,5~8 3,$$˜j %iP5~8T V3,$$"D &*?-5~83,$$6>/w R5~P33,$$pE܈+Vx%5~89g03,$$qrc7NSj25~8;D$3,$$=e4{*!I5~8@3,$$Nl{O''X 5~8EP3,$$#y\LC,L5~8's3,$$ uc ܗWE~)5~8lT3,$$s?B@N`mo5~8!M3,$$m0ά;K{5~8X2y3,$$ؼ6~]5~P1Gk3,$$zȩAoWy[85~8UR3,$$ú:>(CSp5~83,$$Ѫa7.o5~8a3,$$PWhm[5~85d3,$$kҊJ?!5~8[8j3,$$Zap`5~8g3,$$gZn~O7'$ 5~84a3,$$\<֥r5z\5~8zU3,$$d4?m]Q5~8m1;3,$$xWm}nE5~8JWu3,$$_B jQ5~8p3,$$9?+YV$5~8h3,$$0pEgv5~83,$$>(zq6}k5~8| 3,$$p>3;1Ƕp5~80l3,$$bGO;d5~8q_c3,$$lKv1*C5~83,$$H /(j?y5~83,$$䉸 N 5~8U"+D3,$$V8/GvDV]h'5~8 )"a3,$$tS5~8C3,$$%ҷjZ'fp5~8a3,$$کXi95~8Q3,$$Ł)QJMpOJ5~8 d3,$$:- 1@jG5~8O%83,$$=nx,`R?r5~8 3,$$ kLTS)p5~8M(3,$$&,x?'A5~hl 3,$$L x "I77)e5~8;>L3,$$O%G'x)I5~89G3,$$ b0O0oI.05~8*@Ľ3,$$qjćkf25~83,$$Mb㻩k(LX5~83,$$ɏrhEJL>5~8Q53,$$u h!~!5~8i3q3,$$l$Sr( WJ5~8_Sп3,$$F1FavNۻh5~8^>&3,$$FA*5~8kL3,$$K?cC&*P"5~8‘3,$$ ȉ4sQT85~8-v3,$$Eu󜤆5~82 R3,$$3:>6j5~h<3,$$Y;&Z2_5~8 #3,$$T4l$RZ5~8َGM3,$$u,ss`"`%5~8g#23,$$Y|EĚYL +9K5~Pt`3,$$x 45y9B5~8m>3,$$ sc[|p;_(e5~8t3+C3,$$SfPv*|g Q5~8u3,$$t o&UdC^5~8 g3,$$$\0'A?^5~8l/>i3,$$6Vʡb5~8*s3,$$Mfȹ(5IK)5~8 63,$$5f3`&R5~8 3,$$Z$耭3+05~83,$$\X 'IأO5~8G"3,$$VͥбkDPG5~8#3,$$YOn3LӦ+| 5~P]ۏ"3,$$F^PC!‚5~8 3,$$iqd$ZEz25~8='3,$$@Y~˞5~8V3,$$ p2Z5~83,$$80Vn5~8/!zH3,$$џ>5~8ץ3,$$7~=\K0@5~8p3,$$3,$$9?C~,35~P8W3,$$y1aRʁE!Dv5~P‘3,$$vFYO45~PR3,$$S'3tǒ+5ER5~P3,$$([㹲D]+5~P!%3,$$G2'4f!e5~Po]h3,$$X!':xFcUS5~P,3,$$[)>N$ 5~PFX3,$$"EyާM5v5~PIa3,$$3c9 /;5~Pׄ>3,$$qdÑ^Hk+35~Pέn3,$$Vki|ns 5~P۸'3,$$docgl*5~P3,$$UpEl)9AE5~P+3,$$Er8 ſ5~P;3,$$yq~w6qV5~PסS3,$$F$(9_5~P[3,$$~oZrZq5~Pb3,$$y\ :45~P&߃3,$$',@2׊5~P3,$$k[%1G H)i5~P63,$$;%26`WK5~P 3,$$D7&;][@O5~Pa?B3,$$^W%B2ԉTbVr5~Pz3,$$ISb>ڥp5~PF3,$$fJJe}"$Ol5~PRE3,$$wUjhT?5~P3,$$y?Obî϶ʮr5~P`F3,$$e/pfdCM85~Py3,$$oWw.'6X5~Pȭ3,$$N9Ben`d5~Pec3,$$CځP5~Pr{3,$$L}xOwҹ 5~P 3,$$w)à3b;I[{w5~P43,$$H:'j7X'5~P,΋3,$$qQM6~{&O5~P{z@3,$$֢2RUxJ&5~PQE33,$$5m4y!#5~P j!3,$$dG/~+.Q5~PgI3,$$KZ6Օ( +5~P#f83,$$+ ;aV_/"t 5~P3,$$1\."P{5~P<0!3,$$'} C:0t5~PS3,$$n`d@}ǏAz.5~P#3,$$4B$5~P3,$$W[+ذEs`u5~P5~Pq:3,$$^mSFvW5~PDm<3,$$AA cŤ15~P "<3,$$Jr 65~Pu3,$$%+!jADu'5~P=3,$$գ5~P1\3,$$OFa+5~PtO3,$$뢚Қ|45~PE3,$$ű@nôOJz15~P g3,$$ /L-E;5~Ps3,$$%2YTk1{\5~P Z3,$$QY\%z~D5~P s A3,$$:㡬TSP}I5~P 0=!3,$$G@HO)*5~P 3,$$vf $Dȏ5~P g43,$$Vahu:5~P Oߍ73,$$H;3TpX 5~P J3,$$~ sIv*B{5~Pi`y3,$$sRT&{hGHy5~P!r3,$$~Zox4ծ5~P T3,$$Qw+ZVrQ5~P3,$$*$*}5~P Z03,$$IğNTwk5~P Q3,$$}s}z\?S5~P|3,$$p9dw.5Z|ϫ 5~P u3,$$~85$O[E5~P13,$$s"ygqVa5~PgW03,$$6ixFBF~u5~Pn3,$$z"85~PW{=3,$$~%0K nE5~P3,$$|RVԫ665~P z!3,$$O~PEȤ4;5~P yJa]3,$$F:X-Z5~PC-3,$$0"Bߚbfx:5~PIf3,$$PNK**D'sb5~P B@b3,$$*=gAXɚ1E)5~P ;3,$$Ll$KaK5~P M3,$$Aۋ\Dvx^zs5~PK3,$$WoE9œ65~Pwk3,$$S[*v0ڵ#5~P 3,$$W V7J`g5~P $J3,$$aO$5~P3,$$L)оkb9î5~PG~3,$${Z{̄ Uyܥ5~P3,$$Si#ӊ~\u.5~PSC3,$$ҕh85~P -3,$$hqegN4 3 5~Pdy3,$$$@ilo(]dy}Z5~P3,$$MDptx 5~P%_/3,$$3Ҳ5[Ni 5~P lΩx3,$$aG&L!fTN͸I5~Pu3,$$> ŠyaC5~P9.3,$$WiX.9:5~P G*5}3,$$✨G*+cXR35~Pb3,$$ܺӸK k5~P&6$3,$$,SųtE5~P(ɸ3,$$P d?5~P`A3,$$V0Oy Fps5~PM5r3,$$g gUp:@5~PR˫~3,$$9DTHM[ 5~P< C3,$$WK_-5~65 x3,$$K/db{(y冽5~)j/-f3,$$* %I;q3)1v~>5~PJly3,$$/\zGwIA\5~P"4D3,$$Xo\b(5~P1Qw3,$$_{҇@i%aW5~PT~3,$$5cp*5~PX/č23,$$P0ԃ`}5~PW^3,$$P6D엘?U5~P%D,3,$$Mcㇸ5~P 1S3,$$ki`uNA2;ʕ e5~PHВ3,$$=B킍5~P [H3,$$3mQsEd5~P o0~3,$$ t~iVGF[C5~Pv3,$$[Qnzm1E'5~P;3,$$t3`tQT5~P.3,$$Δh^ʱ͋5~P^qm3,$$ pY :IEg5~P4M3,$$ ,Ntu V5~P3,$$sп <ާP|+5~ ?:G{3,$$m] Hߘ7W5~Pe3,$$5X-͵ء! ;5~PK3,$$IEn77*5~P%dw3,$$#{uf5~PVJ*3,$$TYUE\;a =5~P(g_3,$$7㝳+I]oC5~P+Q3,$$V'nAs~&Z5~sX3,$$2rj^(z ,hr,= 5~P +3,$$@g5KDI&U5~P ln<3,$$ROpEs!= E5~P |&3,$$TŽ&l2Yg5~P)41"3,$$@3U595~Pi3,$$*7G,=>/5~PS;3,$$&S:Mgj5~Pc3,$$!`(#3j_ڊ5~PX3,$$yjdtg_ -5~PG3,$$rʛ5~P p3,$$ h/Oa%zT5~P~[3,$$m4+ɦoyA5~PـBK3,$$;!δyY>i5~P Xu3,$$pюNm35~PA7/3,$$jNpKpiv5~PzV3,$$i2 d5~PBο3,$${ʪ-oEx5~Pp3,$$a؈A\&U5~ۍ3,$$)J 4;&75QQ*5g3,$$d*1vDT85~P+V3,$$86sunm"5~Pe3,$$aڳive;5~P.I=3,$$331i5~PF/[3,$$mCP:|R5~P%ȅ3,$$Ah$,˺5~P 2p)3,$$\\ˣ_( 7<9h5~PaKK3,$$2Wܞz罽q5~Tߢ3,$$lȼApP[,5~P9D%3,$$|-7]ruq85~P s}93,$$eÐ +3YH ټ5~/' )3,$$DaJ$Cn rR5~P}M3,$$_laX˽a= 5~PNL3,$$DyL,^5~Pv3,$$OaS}}5~PQ[3,$$wӌ|5Ld 5~P3,$$ت3]tPN5~PDh3,$$8w1Eih5~P 8JcPG3,$$*gu}dG75~,_3,$$p EUfk5~P RL[3,$$0-n#rk*K2_5~Ps3,$$0'5a S5~P#-]3,$$K1&+ 5~PRa3,$$qe.$:jSo p5~P*m3,$$GElTskΨ5~Pw0 `^8aa+r#aKS+aRSza~a 6 aq4awa[~aț98a%+anNa­A`a\ab`b]rbٸ~bbYt#bkbs bvAzbv;ߚb b)BbRbbHb .bqpFb覨 PbrbDYsc`c1c"Fc)vc= cVÐc[_lc`cqyc*ZcVZ"cYc PcpLc*ecy\cñc(ccЬc<c`pc9dNd8hdnd&0d9Vd:dHrdf +diXzdqf@d|d4dad"Zd dhy2d d`d%!ndK<dە-did;dZ3dad(eYaeZbPe%tOe(8>e.3e5H=e6dr,eANedhet̙ eep :e=weUCe~e&ee6Veelet6eׂqDeeFe".e0f !pf"]~f1 fTfZ/fxzffb8ff3nf3rfntfDg4g+pRgX&gfX|giCgm"`gmIgqz[g{>gppggy|g5>gv?Gg2&gߗH|h,h#Zh,1^vh?Y?hC3Phf6vhk` h%h_eh6hRhÕrhOt;i?i1i#Li&'Ei&i;wi=΃iU,Bi\E/i]n<i`Vib$idfNipOiwz>i|J 8i:i'iwi|7i%iӥeieQNjJCj7Hj+4j, j/cj1L|2jEjO!]jgς}jG5j}"jӹ8jGljS\jZqj?~jΜj4j6Hk k-k;>8k=V.kGakLBkgkudk%!k/Bk4LkPkl'*l~@lOyl Sl l-MCl.̡ l5ol5|l<ZlQ0lgDdlK4lǓ:lhlkllml%Fl~l{dlylX4lQ2&m9τm)!m$¾m3Hm;9UmS(mf6t2mhDvm m.4mR0m3m62;mG(rma8,mBm. mxNmXVndn i8n5XnԒnQnB?6n@vNn Oq@n2|enQC2pn]nF"nךXnb*oq o%Oo:5oSoto|ojoB o˴;oҒofK26o5.JoBr:owoos]p;E@p%bp09pShȢp] psa"splHtpps6pʶ|lppxjWrPr-,rF(Xs $sMs(Vr4s=J$s[Z/sm]^s|^<s/pss_s6Vsvsds sFLs^rs&Bs1s9< ss`:t4-4t\pt\`ʾtxڕ2t*etwntHAtt]trRpt,,tR+tM*t˦uu Iwu DwWX,xzx$x(n&x)>x8(x;yoxA=xSIFxSx^JxsCBxwx{}x~xۧxxW@xfxxMxfM'hx64x +xlxUx/Ny2u|y"1hy*42yEݗ>yIq yyvo*y^yVWy[yy}1*y^3y ?yȵ.yRySyb y7zAJTz3{zv.z&zzD<zSN{|{@{>{B{_dh{]b^{ȴ{Xj:|(=|,? :|6|;t|CL&\|N?zx|Q|R|U_H|d[|u N;|v4N||Ez| |׾B|xn|5|(hF|,*|Z}pmjx}Wp\} Al2}$}.]iV}Oo}dlz~X~gkn~i~@~Be(T~,x2~5Ctp~R~h~|~.0~M~0> Z*\4 -7ZXE:BGR#oHK Tt-76K!&֡k&ټ9?.ݍb] p63,$$V"F<;:5~P0)3,$$꧶_n@15~PX3,$$+lR-*/;<5~P-3,$$hrGqrˌ?5~P 3,$$hup 5&j5~P%3,$$t"* KVmd'WnVd5~ 3,$$] jNP37R5~mw3,$$.d5pzL˘k5~Pg3,$$tz[nt|H15~P 43,$$fKװ[Sb25~P[)s3,$$^[ly}ydH5~P!e73,$$|nh5~P&K㜻3,$$@֗d{S5~P#3,$$3U3wD 5~P&(J93,$$AU- ͡~`y5~Ps63,$$Eˑnx/f{5~Pj3,$$޶٣\!S5~P@tܢ3,$$ޏWn, Y3l<5~P? 3,$$s QA5~PIU3,$$ȥ)L>Mm*5~Pca3,$$\_DO_G(45~P q:-3,$$}i|9II45~PL3,$$-=W0m5~PH3U3,$$s|0.=F5~PXM3,$$,] .ց >r"5~ *lZ3,$$2 Ԉd(1+U5QNs33,$$v/6hb5Q,03,$$A][~ޑʒ{.5Q4|3,$$Z((9yӋ315QAl3,$$/?_izv5Qm͌T3,$$5.Ҡ+-?5Q21!3,$$Pζ B{B5~@8P3,$$ tN`ϴ5~@QF3,$$u3SڛE55~@0m63,$$.[i-5~@BC3,$$(^5R`3 `5~@!,3,$$Kӽj@5~abw0 ňq  Z %4 (Ⱦ + +X`n 1+\A 4X P; eRp fW YSF *-h Ұ {U S A8U κR: g ^H &!Lz! Q.!%B$!g!G]!Xx!j@!k<!o !rw^!BHf!!kId!ض!x""%s"&T"M:>"O"P<<"jX|"nsj"rD>4"~""E*"5u,""l"[z","6#=##*f#"#0j#6_^#:'#K7n#Z#[P#ljZ#{5#EJ###]nl#5#~D##Ir#ֵ*#Scr#m^&$$=,$,$!$({z$4Vd$<6N$A>$A5F$Ys}j$]Mb$i˕dZ$mZ$n$)b$X)$v2=$$ $Mx$k$`$t$o$$3$ol%8VW%2% w%8QC0%w8%,%0%7l8%8%?\iJ%?pT%A%B%t:%v7L%wx\z%zd%+%>%p5p%:Mt%I8%.%}M& `& `6&&.h&E,N&H?h&JxfU&L&QgU&QJ&jgj@&}&&&-5&Ol&G$&6&;V&Tz&f &:& ,&z'7N''*'@6'Xe'b^`'d&'eqz'iC'04'1Rp'F'j1'd'^ 'նX',)*'Ã_'徵b(ϙ;((KP(4!Q(7mc(A(F[/(U\(\UX(vH2(*Mx(%|(1c>(9&(+$(~(˗E)w)Rrt2)7P)4y)Q:W6)RT6=b)U 1()_n)f=)h )v,)Ae|)W))XX))<)0nR)U)8)H<)NT)匜)<)tB)y)*kJ*k6|*#<v**#l*' D*7yp*D*d9*vf4**RԶ**kR*:W*=*)**z*`d*l*H+@+<3+@TFn+q+}+r+`|+++J+G8+X+.+\+, Vn,%,Vj,OGZ,=,FZ,dd,lT,v5|$,&,Z(, ,4 ,o~.,v,'d,ܶH,܀,l,";,CKr-5-r-s3?l-A-`r-` -a-'-òR-!-Ԙ-Vx-0KI:/ܡ^4/// 0B0ZM~0[wB0oUS"0wA`0x4r0~x0XX00ds050eD0040ZFw0oQ!1C<1F1 "1Em4r1Ik1W><1bxM>1nfuhX1$|1Ͻ(13vN1Y2-i2n2r-2o+2_#292#2dU.25/A2 s2 2S\h3 [j3M63Y3\lBjb3^X;3L33z(4+ 40@46(94B(S4`rH4vH4zl^&4z[ 4~Th4J  4D12D4@o$4hKB4x54NJ5:^\5Dj5Hʕ>n5K5ZrR 5_v5Pj>5R5O?5 535x5t56w^Sj6t]6m:6,f~63E%6B^6J6P(6eYm6yHeB6|v6|un66(6~6~I6N6߂"6,6*C70C^}7487N.7Qnq7VYz/7f)b7`567`7R7718Ep 88Hؔ8? 8zK8%58/X#8TZ8lO8}I@X8)8d8 8ɛ8{-8|9,989]?9#.9,L93h950m9:K09x<$9ex9R-9Ez9F9~69펺 9_9Ky:Q B:a:)#z:6ZbN:H/e:TOH:y3::|:s:xa<:Ʊ:;(Z; ~Q;xXc;*V;3" ;8.2;S`y$r;[q.;^}px; j;1;;@K;]tl;ڈmx;ܩ7Et;zV<D#z< b<)c–<.bv<[ .<:n<|Vʬ>y">#J>+K>9$>B1.>F Z>W>W-,>"y>#y>>>>yu>ݾJ> %>x>Ű??6r?+_?4jD?;6X?> p?R!V"qao3,$$J::3"/$5~@<2!3,$$ 7)0S5~@A3,$$Qп6H` 0֠5~@ed޾3,$$H>|xݷ5~XO3,$${4◆30(L5~@3,$$e][VU[Xs۲a5~@jWY3,$$rb[tPX5~ qq3,$$@;0Y!1SB5~@u3,$$ )ʹ&5~@.E3,$$,uR)ky5~@=3,$$ߝ݃q5~@.o.UA3,$$;W!WE1ɍa5~@%M3,$$3+Bo 5~@gS3,$$)~dim5~3,$$eTNL ~7j5~@7:3,$$o)Xz݋5~@,.3,$$Q,%z5~@(3,$$u|[7n `5~@ a j3,$$ 2eJ[67IGu5~@_`3,$$'ǮPJvd1D5~@k3,$$oj(挆'35~3,$$I .H1-5~ !P3,$$zbc $5~@Lі3,$$prgsȯO5~@RUd3,$$6'x]?N-Tvr5~%ήM3,$$#~ګEN5~@Q q3,$$㥴8͖5~@:l3,$$7F҇=̑5~@[jB3,$$Udm,8t5~]E@ow0 77lJKwWuYUf Ru_ǒm0.λYҌs+|7!tX{%P9S2JvZJY:`,uZ!3j9-9o"V>r?,|ίo]N7^&^ʄf/ٶ*fR>INE ]YIvIC~ <k~*QvĈ˧K9Lp8M~cX0:j|*$Yz@N*J_׬jQhlu6`fTxFڕ"P6itcqN4Xv!`^ b^O N>H/Y 0o}QtUZn qt@mwHlVűr=,r(L;: r8jTZ (n|rVvo0F|3øּQ@3d4c" zi6+$G6&8LX<ji@t'KJx_`b:TTzJuU(hO'HB7:0tUOKjno{9TkX T8hW Ǚ.JR5l 9:Y*7i8x9N8d\[,sb+š_ *-Xn ]4f :p0hzPt .> [4%X%/#PVX9nI<\oMؓ#T&ʶ " b>t*<"zXIn*Fo9}T@ȴŌ0#`.r,7{:8/RG[OKSNUGPYN)_Tkz vsSF,t ~NM.8@HgY[F<H3.9/Z w_æ1 JL-pZZnjn1#rEc2E8>Pf+.i--J||tk&K%]Kmc{voLpny v]F0X-Cef7ػ_.SD v #'v)h 9nv;Iw(ATRŽk4WA&^_RY_\<}_b0uMj"GK~sd ocr6vz- rJ0@ NFseVT"Pom6*t0+ *V<Xz2{wFr)Y8Nr؄K8|~L(<1> 0lv+c '3c7Lg>k{{`:J!MwKwCU[-2 v35To3=d7JW2Vd2L1h?/LQő8RW2Vax VŎ* ZCJez~ Ҳ0h !%;$mMNBF8W\_J ]gv^$Pb3,$$Sʉ<D5~@<3,$$YHjѨU|5~@:X3,$$JX؈VZcth5B 5~@q ?3,$$-!Q߰F WH5~!>3,$$6Ъ69|{5~@ "Y3,$$c^ ⤑7-A$5~@V+33,$$Ju[Ly5R^፦8č3Xp.յ$_F^YD#:aGtZݙ|⍋d8x<XO& ْ:$MS8(y T$Uf&d)\K Q Xe RY-e *hݲv㐀KE8W#4,]3dD<@Qᯑ.xfd$VN(5x\+P )v/l1N3=7::&n nlOVq,h228 ӔDȁG$n?pz:rhN2T'U%h.F# 80O^;2)"ncoz<.1宯 Frytϟulq:83/Z6"X4I`(\HA,[b5iH;棙C݌&ɜ3}3m\Ѷh9U(z˪Y;R7$-CALP+Fa}q |F َ*aɳFׄ纉4纓T8羹Kޑc Sx+  ZrmFQ3f(Ժ0]86DZx6zڣ:Ҷ{8ߣN ;$$1&7$H]oqůT鹓VC;`'rz T\/bR+kfvӒGYb3ξ rP-$n]. X(DP$Xg0\5 s-,hf&}M8fWy@W맆cōO5\..\B n ]boDId5g :<EPg:lqUlr>޿(N<@6Q"&ْk`<_ xa"P>T?ޏ+\Nb jyg2l8E~J7Rh:Ony̎ tT,(4<7 2'ST 4rTl[% mDyd QSvv"-G~ArP`3OMRHS |^UW(bދh|oXs2W wS iRxbrpWn(1ZK7Ho2GBԏۆ9}f Vf1M^3~3j]xnpw.qhAj!NX0!>QRȒ,~Ab~ "JE9/}B=Pc{34jK{_{QXL+J% (FӘ5yJEc622QnQlV 9%ZM%Uw^wo&JۈqR Rd$T@&YU9V(\2e&vq'B\ {@#/2V(.Tm۴T<4vGfN Df:A"@5| [d*,10C(5D)nIE@\>meJ1djE^nqtOf4NEݸfx y xG) hV#Ͱ\pXl\2oQshDt6hRSV){NpqYd԰Kl~Px^0C}Xv? +.ro?Q }R+4B:<Ίn~`5<ŸT~we[+v,<GYDN>qZĦ8jsCr) /P ) n, bF4st@s͚9RY3x0$lRW~ ]T&XA<*8N Qd|`<"2B|J)8EjVt)#1C-^.!gL~v?6Фb3,$$ef.\ZPx@5~8I5$63,$$`+A5~83,$$$bb 9$/55~8 S3,$$&x`2 5~8j23,$$;8Kb[5~87田)3,$$}* \ZGMvut5Q}Z3,$$=WXEz@5~Xz%2c3,$$Չ+WSy;5~P=Z63,$$~wō=5~P}3,$$#8ynnʟzӲ5~:3,$$2X!ۍ?v5~ 93,$$M`;Ɏ7y<5~z3,$$A4<~gH~5~P{ Lq3,$$ a\95~ n#3,$$L`@ 5~tW3,$$F\j8-cg"5~ :3,$$>v1VتG5~=03,$$Fﶡo0a5~3,$$CrCr&$=5~O`ڝ3,$$iH %2jj5~> 3,$$MI̥s\1An5~S 93,$$wD뭝HQ_5~k܅3,$$Y(+*:_)&5~oDÛ3,$$g oO?(5~3,$$Еf_&>rCÆmj5~e3,$$GH{q673L5~%F3,$$Gqpr޹T5~ 7i3,$$ћp?¤^c5~cQ)@3,$$[n@em?Z|5~1.3,$$eȃ3\"l \5~3,$$,_CF5~`3,$$qqr& C:]5~ Ӿ3,$$ sDȏ5~Sf13,$$9M  DNn5~1'3,$$/ݚ#;57.5~s3,$$-:j#X$5~(cu3,$$bq!ONG5~[3,$$e%ayF5~-H3,$$@ͫWdk5~8c3,$$Mb?0u2 ^05~9}3,$$E8agdܝ]5~@k3,$$4x%:or!vT5~F3,$$LVh~m @^w{5~2;3,$$`%[^5~Rj3,$$%8гz Sb^\5~@>3,$$/,"~s=1.5~~{z3,$$!ӑ8lvy5~H=3,$$ QDJq!5~XU3,$$uLJ߿{5~@`Y3,$$fK-Y۷5~X3,$$"rGymck5~=A53,$$ "¯S׼@3.5hS8D3,$$Z{;5~ j3,$$4p[QM 5~@F4W3,$$>{{{13ܗ5~Vo3,$$(>a`ơ5~<3,$$4-O5b 05h#(~c3,$$r#gde^y9-5~@@Y3,$$R c+BmFV}Y"]5~@R(@3,$$|q[S$My5~/x3,$$x%S$d5~@ 3,$$Pank@dI 5~@Q3,$$ ᰾#!;5h_C3,$$ZBV&Nm}}5~త3,$$+as~ )5~QEx3,$$n{@un=u5~@HN3,$$Ȱ7۲Vs5~@Nӷ3,$$sqw}*'v1"g5~I 3,$$^HiV8y>st5h$O63,$$(f .ʌ-WgE5~$nD3,$$gB:)tZV 5~N63,$$U ݔ<5~@?H3,$$wx KD(K5ht3,$$!RVҊ$yvk5~A3,$$xԸvږyO5hEM83,$$"$A g<"I5~@.!B9H3,$$&M*>>p 5~l3,$$PFq!C` 5~@Г3,$$STe7 /}vb5~1pSn3,$$RۛM2prZo#>5~RD53,$${l<áM765~XC3,$$XQPU:#i5~Y 03,$$?lqMSVG]m5~@ ~ 3,$$墂En=OEl(Y5ht3,$$P_}jdޞƠu5hCH3,$$_a$o.C5~@ %s3,$$@G gb5~@ 3,$$~H/-8D/5h u%3,$$0\%'45~U%3,$$2 ;B=7-5~T,3,$$)58Ve5~@QC3,$$կ3ק5~3,$$&9( 5h,uU'3,$$j|٢ [N,75~-g^|3,$$}N3Bj)15~Np3,$$3{ "G5v_9b5h/3,$$ˇ}KOjX5~>3,$$*'I7?5h4_t3,$$$\GWGH&TF5~@jlC3,$$tu{P5h 3,$$?>m5~+w*3,$$<ڐaoZ^%>xW |5~Gș3,$$?N\ '=P5~ ]r3,$$vgTI x5~4$P3,$$ѩu#m-oy5~X\]3,$$*s9//l5~<WH3,$$ V=#_t`R5~3,$$v{`ЧWK5~@(s]n3,$$&8 *Y=K5~XdĔ3,$$e%xvȶc5~X6H3,$$R7V8澌OKt-5~X$ l3,$$nIٍKe5~bIQ3,$$ z!W% 5~>s;3,$$ BM3T H5~ 0-3,$$R'A|>Q)5~ ڪ޿3,$$߈>dH5~XP/`3,$$,/Ki(k|W5~X ex3,$$WNz5~3,$$r0*;E=W5~Xb;<3,$$|.بj$yl"Y5~X|L3,$$ 2>fF55~X+KnD3,$$;O܉"OI`$m5~$kRC3,$$VhZYasD5~X30"3,$$tʳ.Թ07u5~Xpք3,$$sLvM(v(5~X <3,$$pc(}5~@ ,3,$$[j5( Gy5~I$)̟3,$$"QNzNv5~X ny6T3,$$Emwz (*5~$.^m3,$$Qּ 1 sj;5~@ V;3,$$efh6.5~=^P3,$$+ ssόu0d3,$$hd M\(15~X/ҍ3,$$u+oC0!5~Xu)[3,$$%}=ވ^5~V?3,$$7WUg*c0},c?5~XNS 63,$$(C t_`a895~X\3,$$\^YԾL<5~X\Dute3,$$tIf%J5~X3,$$=)'}O5~XN_k3,$$uzL& /$5~ kZ3,$$[ uw[Mwi5~43,$$?Z*yyV5~X iO3,$$[Mg?'$! 5~q<3,$$ӝ B B1[5~@Kv33,$$O 95~U}3,$$ ;:c GF5~03,$$wZ V5~Yo}&3,$$sxo¾^x0{_5~3,$$ gLu)I5~ ߶3,$$yUFB9uhh2.5~Q&J3,$$'eq5~A3,$$e֛lˁ5~ ULCT3,$$S\d3=5h O593,$$~"`zï5h3,$$fdc3!Mr5h[ 3,$$&y5 ~\5t'3,$$q} 㚔z.)5t8.ܜ3,$$`s}WBHC5h p$3,$$: | ȧí>5p y*3,$$RIפHyZ]5h+3,$$~ϚG독5h)T3,$$-ن^jO5~ I@3,$$Q7eϞOF?@z5P}(^3,$$dݕ]Qn<59y5hIl3,$$0%[?ꎢ5h P3,$$ Ωvrn^8DO=5h 1.:3,$$AacOsyh5h:a3,$$ āOqݫfv5hj3,$$/בy@9S@5t[(3,$$F7pS *p05h5p3,$$ (}DVU$,VS|to5h [lC3,$$}kϣM݁ΐԧ5h]=E3,$$Xsd#4 :b}P5hbOE$3,$$\^HZNyh5t&3,$$8Z +V͕Jw;͔5hVm3,$$ڕ)ӹ}Y0Z-d5h#vn3,$$9 ,XG"r5hUƉ3,$$U}R_8g5hx 3,$$a]\S֑U 5h 93,$$@>0Iߌd#5h~3,$$fGKw>>W_b>75hXw3,$$CJ^t!H$s5~ R3,$$2O뼋&:,1l5tqR 3,$$f DZU5h883,$$"]InQlg/Z/5hL43,$$Mk'20E`x5h d,3,$$f6Sy},5h\C3,$$/R,{} AƩ 5h y3,$$7v12>o5hZD3,$$K(7p~hX15~8tZ3,$$@!JПly5h3,$$g CShyS\5ta3,$$_1iFÒl=5h i3,$$|[[5hDDa3,$$aZ$^*շ5PӣՌ3,$$je'5)5t O3,$$4uE y5h,E63,$$/)øL5"5h $3,$$h+Ϧު$R$5h~53,$$8[R YU5h mV3,$$6)ĨpaV5h 23,$$[h.6H.5h ԵR3,$$M]bi6,5h 43,$$_1&b<~΃C5h <3,$$^˪7\5h  '3,$$,ci#6`]_5tq*3,$$gjv\.?.=]5t-R3,$$%qn I 5t43,$$f 3*5p5t , 93,$$x.z7#b5t$Dp3,$$; 8bDy/5t 3,$$|4JJ(R5t N3,$$K`o ; 5t$Cw3,$$GYF"r"15ttc3,$$_zGj>"5t)<43,$$|Qi]}6p^#5t*5C3,$$LzGqkNX*F5t9 V3,$$/tHyQ֗5t 3,$$D-u.vl|-u5t3,$$ ċ[J5h$8>f3,$$J4LJԳTW5t9=z,3,$$%1v~ji5td3,$$뱆_PQ\Vl̖5t V"3,$$ѼwmqLPMp@5t%!3,$$ɉZSMt=5t kjD3,$$t "yH G5t6r3,$$h7hZ=*˶L \5hk 3,$$34 }5h }Z3,$$} 9T)!ͫoy5hc=3,$$iS/l·Hs5h%:`3,$$– S_/~5h!ܟ3,$$m" q6jT5hHl3,$$`%r+=<;5h7J3,$$Habԫ[5hJNN3,$$hfM% FhHq/5hl;3,$$% &ѿAc{Z5h7oQ3,$$}Y(69"ur5hV3,$$> ٮOn=5h#m3,$$Cm< yqЍ5h#v3,$$/.q"~ Dv33,$$Fi>}>/e;5PY"Q3,$$++I1KDP5Pڍ3,$$lx6vlaP5Pq:3,$$QT0f͢'{)5h'ye3,$$C0~{@^'5Q<g3,$$m!uO[C@{5h#T3,$$ 3Sm݄35QS3,$$NC΢`n5hqۨ]3,$$>­hy|y]wE`%5h`3,$$UA|Y&]Єv5QX93,$$kj#icmb>5h+O/3,$$gk\v#%,+5h%@s3,$$VRq& Ա5h pc3,$$Ҥ@]@8oF5h 3,$$AToNJ]5hxD,.3,$$Zۉ)\j II5hL26*45h~ S3,$$V"_+Dhx tS5h?ؘ)3,$$z݊!PiPtEw5h*lj{3,$$,/Hҥ#ԟ 5h}O3,$$0!1'ji"wv5h&ː3,$$̍14r //=s5h 3,$$lѷEjh^5h3,$$X޸y~͔:15hT3,$$V{Q̾'/ R5h] 3,$$_.!!Tī5h(3,$$0Ο ~ZK!5hW^3,$$ÓxQ+5hKAkX3,$$h-[d'A5Q |!b3,$$02mF!3A 5h@d3,$$OEe=;r5h# 3,$$w;4aQ85hl 3,$$(T85Q+„3,$$GO߅āU(;&5hk$3,$$5eySTY:5hng3,$$v|qLκ2H5hq<3,$$ 5hxHf5hx%+ 3,$$ 1ȖJ5Q#uj3,$$k:fݑU%5hS"3,$$] D¸| ]? !65hDM3,$$|pv5h^Ũ)3,$$(n3!TD5h5L6+3,$$:n1CH5Q(s3,$$?J<5h8 oS3,$$ +Vtf (<5~la"3,$$maQ~l5~Y}3,$$_/I }Z' #j5~s3,$$]q/S5~,3,$$Y,CO+"Wޟ( 5~3 T3,$$"Ur"Z.5~$3,$$ͺ՞"*ʜ5~ 3,$$B$CD5~M(3,$$Zb|ȩ_Â;h-5~ 3,$$NkJ|5~<3,$$-_ o5~Ƕ(3,$$4=w]E4&5~-3,$$ku<[5~ll3,$$ɾf_KZ5~nY>3,$$4BOWl5~ n3,$$R.K?1(l5~ lXo3,$$^F OVfccf5~k3,$$#/Q 4.5~XpR3,$$X*r3]a5~#)3,$$cj|h=;DH5~Uj &h5~ 3,$$xoKE?5~ V3,$$ G8I:,`5~z3,$$vXL0 1k\e5~X?3,$$9: K%5~Hؖ3,$$X)—kR׽ن5~b`3,$$N3S? b5~ y3,$$v󼶦a~'5~wvVr3,$$\;N0&[c5~?3,$$I%k 5~.R3,$$nm7 5~ ;3,$$!;o\<5~!݈ 3,$$%~SW!~5~ۛ3,$$JT;ˑFF:9]5~qt3,$$/&E?@5hd{F3,$$499T9J嫇5hx3,$$cZ8Wd|xV:$5h3,$$.q Eq1dl5~c3,$$K%hs^h!5h/3,$$Õ\-0ܝS5hP.n3,$$ٍq.Sv85h\#m3,$$\t!+'M(@@5h<.3,$$,b/ 45~b6t3,$$7~h67 H73W5h EG3,$$P&/y5h j23,$$ <C"FW5hb3,$$\Nd5CGZFv5hZ!,3,$$?ub"|x`>]W5~ɲ3,$$݄Y㗒h5~$`3,$$! *EZ*5h퐗3,$$v3U HVa5h(;1R3,$$e41jmJ/vF5~<\|)3,$$pd_&f|FWnR5h}p(3,$$pDn] 5~F3,$$m" B}K<\p5h0H#63,$$p? 3G5 cb5h.A23,$$Q lOB})5~rj3,$$Aq)#`yi5h}l$3,$$Yn3<&, %5h3,$$CKkʥux'5ho'K3,$$ml?C5h$L3,$$P 7mP5hI3,$$«ng5~|Ð3,$$C2=IRoS5~]\3,$$j&\$:WmBú5hJNy;3,$$^>@O #ǽ5~6JU3,$$ f.4vaI,9a5hxS3,$$PU5>("5h Q3,$$VS޵ZV\pS5hx ջ3,$$^c[os4*y5hҔ3,$$vx.Q`xN>5h*$Ո3,$$Xht{MiMxrP5hΔ 3,$$x+M@5~@3,$$oEŧg.T3 5h4503,$$ ;m4Zw6 *͟S5hr93,$$3sni*fW5hsws3,$$܁.g4 5hU3,$$ж-j65hIO3,$$:&f.4Ǥ5h@} -Yp3,$$(թVdi5htX3,$$ʍFF?5h ^a3,$$#i5hb~3,$$ kxuNV5h^t3,$$HbZ:2 BN,v5hOj63,$$f܁5E 9EAL"u5h#`Y3,$$vkW}؅`rE5~[3,$$9J2ja$3,$$G WV;Ry(%5~K 3,$$0 (_T)].TB~5hHu-3,$$ Bf6\i>Cq5hɫ3,$$CE]9n'5~m@eD3,$$Kq:}akw5~`z3,$$ w&(5hAx3,$$Sa&Pm^y;tVv5~$3,$$l=Uf6"5~I%e3,$$5Ol-POyN7C5~MA3,$$9BQM5h ?3,$$ex֯5~ ͧ3,$$V*4R5~Xwu3,$$Ai (nuZt"5~?3,$$cÜ&kC5~3,$$X,.7KZ5~@O3,$$]yew !{05~E3,$$rr?y@)Z5~駘3,$$uyڄH׹5w5~;3,$$ph 5~_3,$$׺@\<45~V}3,$$^xJq%QwÏ)5~lȲ3,$$#1b 1,s5~lL#3,$$ m  5~ 3,$$9>dx\z5~p3,$$Ho|"贡Kϩ5~ _3,$$\a4\O~~5~pN>Y73,$$aHzr5~=8G3,$$K gj 5~3,$$W/FT5Uߩ%5~ @73,$$Na}+jBf5~F3,$$xA⾚~ 6_5~a3,$$ΕkJ5~'-3,$$KŇh6\5~O}3,$$$#FQԪ5~ ?3,$$hHBN1̤K5~wJQ3,$$U3Cw5~57A03,$$IeaR]__A5~ 3,$$i钟r6Z 5~ 쫰3,$$NoAjI5~/3,$$ǜEӔe&5~s3,$$N&m%w 5~X 73,$$|%aP85~p kx3,$$Ʌ:HnjXG=Ok15~ N 3,$$ )sYM5~p 8eS3,$$?PT߸5~ MvCq3,$$p PKq$I5~ 4cyM3,$$1 B΀xBE"35~p$[3,$$̿-C8p5~ֆ3,$$,0('5~MMkG3,$$(qx@%x5~Hj3,$$$/_T_zv͖vʔ5~цχ3,$$ѦTrG+?-Z!05~Sc3,$$}J%x톏(5~@:Z1)3,$$x=yA5~hz3,$$O a8nFf5~;pC3,$$1b{fHX5~ Ǟ3,$$W4]#[PTa‹5~i,}3,$$dG.D5~@'_~3,$$yOJ$?J-5~_:3,$$1wbԢ~͏S5~x83,$$ 5*یS]8F)5~JZ9j3,$$l2џ3!`!5~pgsu3,$$Dg*pX5~ ](3,$$x#ڇrLO5~Fiw3,$$.+5~M昇3,$$}{]~ F/+ 5~#XW 3,$$Rm #sBNL:5~p e,+-3,$$52d)$!à5~3,$$Heub" 5~apOj3,$$g\d}UW5~N3,$$Ԏ͜B}5~ f3,$$>ֱN=35~3,$$Q̲zw25~(73,$$orΰ+5~,3,$$dJ K&BedE\5~0<%k3,$$D/+kZ033,$$ߺg)9^=5~E3,$$T$(;rH-~5~VxP13,$$I֤ Ph5~c|>3,$$ 5oK?LY:5~g=3,$$U(&t"T5~W^3,$${d<~5~3,$$ fBU3S5~lct3,$$ݷ>1{-umb5~3,$$(?zlC_5~(3,$$rjQzp~5~:S&3,$$2!Ucc5~`O#3,$$_s{*\P/j~5~=]} R3,$$ѣM[C|5~:)3,$$x4>vG-5~t3,$$kbx lk(5~q3,$$ ?ӼFR&5h(`="3,$$ҋAŸ1Do5~7L3,$$dgd}Ĥ5~~E3,$$enPu.5~@a 3,$$w}=dٮ5~@0}qZ3,$$`7#ᦖ5~qt3,$$:ht_MW&z5~WHT{3,$$)Nf + U5~cY)3,$$9bnS$vesĚ5~X@a3,$$ 07*Z/$U5~4)>3,$$4^# 鈴 5~TT03,$$hgj9O2a5~Ӈ3,$$΢>i5~hEa3,$$'g  S]]5~zwR 3,$$sE]? 5~\H$3,$$\9)]U 3bt5~@EvL3,$$*s o5~@{#3,$$=; Su$ҝ5~\3,$$1_z(ƒ5~.p 3,$$; *־w5~ë3,$${Ilm&5~S3,$$ۈH_]s 5~pҍ3,$$tJJaܖ$ƊNG5~-63 3,$$ QM'd&5~X6D3,$$r1:%@D7el=5~ܧ3,$$WlW RD5~ l^`3,$$23= ﱛq35~`S3,$$1pኡR K5~MN3,$$/R*g4 m>5~>YO<3,$$3piL8LB 5~6 3,$$ 8La־)5~Ai3,$$A_:έ5~I43,$$ʝJ-a%5~]pD3,$$H~.LaO5~8J3,$$1CjNa}5~:3,$$HgfbˏN5~fJ3,$$]jXNގ!h5~6u3,$$ƠTJ{5~'3,$$\JW4T:5~mĺ3,$$ai3wP45~426=3,$$*ƒE-Ϫ.5~"Kzi3,$$[B |ڄg5~XS3,$$_FVW5~g3,$$kո =O;R k5~'+o3,$$.7ﱎ)I^dA5~gn3,$$ "l?u^w:=5~43,$$Ⱦė9PVŐ 5~ 3,$$e]&h<a_QEo5~ f3,$$mglov6#7j;5~h&^3,$$O0DԾ(AI75~ q23,$$.SKIל8T3 5~pY3,$$1V.30~5~ce3,$$([6`~Q3]5~63,$${SSTA̾m5~Ļ3,$$>$V[m5~ [3,$$@Y͌c{ !5~'"3,$$84+f)ԗ[45~L3,$$Eue}uCs5~Y3,$$me| ˄l!5~ }q3,$$8~!XQ [h5~ vъ3,$$ee.܉À~5h3F~3,$$7m3Y}5Q cV ش3,$$ B0?X5~ T3,$$暚Osӌ`bB-;5h91R7D3,$$i LqU=D:M5~bU7i3,$$u U\Eo5~Y1Ƃ3,$$"å`䠒O5~J3,$$&~٫+6Q5h Q3,$$?N]oVS#(5h2 3,$$ƈ׺[DYg5~'U3,$$g>1z@v~5~#2]c?3,$$I) )l5~_|#63,$$/DoHT׆b;oP5hd0i3,$$/ 9@c5hW3,$$u>Ӵ.5~jQ3,$$(5 ^E+;5~ j3,$$:I,-6&5~iE3,$$ޒ2 P|RI5h 3,$$V2EŃC뉊d[,5~߉3,$$ɍ{ q5~3,$$[)"Qw6`5~  3,$$""_6dU5~2ʱ*3,$$,b_~ g05~w[3,$$<,+ŸO?\Ui5~ ^g3,$$P,#25h><3,$$kdQt}FG5~"3s3,$$< ,I_3 5~n3,$$U4Ȉ5hPbD3,$$Z2oL ?U z5Q''g)03,$$|nvRzA(5hkh3,$$}`Bh5~\>3,$$#4,y_H5hR}B3,$$|)/5~!*3,$$6=ƚ BZf5~iL~3,$$26n,K/5~2%V,3,$$Y,5~izOF3,$$\ qd5h*]x3,$$5m){q>x5~+]T3,$$*j !dć5hQ3,$$o&A~4/5~^3,$$# drl5QX_3,$$&¯}{m5~lk&3,$$9Ωv|d45hyJ3,$$0ν`^)fV5~23,$$]5GuI}5~zO3,$$pxF[ &so5~3,$$UU#!aVWF5~=JMk3,$$f\9#Z~ 5~cM3,$$y [{nц%&A5~3,$$"I\O}97ߧWB5h>d3,$$ Me;+5~As^3,$$6V,삃u(5~~3,$$ \dm(5~(i3,$$Ϫiet3,$$9=05h}g3,$$d,y[85h8t3,$$?~c=5f5hIHt.!3,$$$G UA$Q.5~LX>0R3,$$db|+.5Q(b3,$$_#,P5~}*3,$$Q *Lt5~Lf3,$$= e,s?n5h% 3,$$nGG[Be5~3f3,$$OTͭ l6!cF?o5~Ҡ3,$$d9a"">G5h_l3,$$weeorZ|zc5~>3,$$ӫGWq_2z3*5~0@$3,$$Fҡ(_ԛr@c/5~\'?3,$$^C6BaF+5~.,}O3,$$Ѿ'@:-N5~Yْ!q3,$$ϭ-'fղg 5~03,$$\gے +giq^wad5~0We:3,$$c3"Tf}dy&5h-pBX3,$$U2 5~63,$$R䦎@Ÿ AD05h3,$$&\AРK*Q5~ y@3,$$65Y_,5~ #3,$$M5~8C 3,$$ hr Y5~[*3,$$bl(72Ut}5~*`+3,$$FWBXnuM5~ۉ3,$$`@&xi85~u3,$$O!.r5~OҊ3,$$EOA)j5hiJp3,$$-TiG55~MJ3,$$ :y n[=,n5~RKj3,$$yhdD5h?m3,$$lZg<<5~!A)v3,$$_b xX-5~-SpG3,$$'X{gEq5~pI3,$$ږ)#ɶ(5~;3,$$}B&Xo)% #a.5~Q&xM 3,$$Js٬']U/Q5~.>$3,$$Iɑ܆:+5~X%$3,$$RFxmgwwb5~ B%3,$$I. v(45~pR93,$$^IW0P]h}5~F@C3,$$νI: Һ5~CSY"|3,$$$5~73,$$G05~23,$$oPeYȧ,qF5~3,$$LQհ<.5~cG#_3,$$ RH=bGEa5~Tb3,$$EXOXn{5~ 3,$$FLoaY]"N5~3,$$ŏ^Wl]5~$(3,$$"qbA[Ѣ5~ Hcb3,$$6z7{Tv%5~Lp=3,$$,,Qc9ʣKhƛ"5~X'O3,$$JUvs\5~:K3,$$>ӻ6Od5~3,$$}/Ȩ7,5~.`c&3,$$V6)]*S845~!=Y3,$$?/ZF|vp 55~0tX3,$$[[xmBpPPy5~}3,$$'L !W65~?3,$$o1?C`5Js5~":{`3,$$ꥁ/ |615~x3,$$T=IK܋p5~* S3,$$*-.\8a_c5~l(*3,$$Dct<5~3,$$oxZ?5]J@5~#3,$$h~9|~|75~$#2X3,$$i^rn S.sR5~y9.q3,$$ZTd/#5~sQc1)3,$$1>n@O5~]3,$$` gh*m5~ _3,$$> m~*0iM#>5~i3,$$`-α@5~J3,$$}o./r\oq5~ u3,$$l W~Ȉ7X)O5~I43,$$@<ӹ"/p3L5~3,$$_ Er^\ ڏ5~ Y[53,$$2Y4uRYtC5~>م3,$$vJ5~|jS3,$$y!qh9!{5~e(!3,$${E$p. 0;45~fR3,$$"y}a㡨u5~C9fD3,$$xU.Xwr|u5~]Wo3,$$c -^];u[~Z5~=3,$$עT-3I;V5~(K3,$$Ma7-cFv5~N3,$$sU6Rrݳ5~L3,$$-ׁݭ<McJ5~z3,$$=n ,:й.5~U23,$$D]m1셃babd.5~HrL3,$$E*6k@Nx(6AN5~G*H3,$$싈>"1ICu5~ 3] 3,$$EFn{c495~ = 3,$$/*:Ёf{\R5~ FkUV3,$$7d NƫD)e"5~`Fq3,$$|2>^ՉdLK&?5~G3,$$t@U n,o5~-]3,$$V¬p5~y?q63,$$HM83,$$ B). _ m5~0t^3,$$TBS;oҜ6;5~z^y3,$$x?GT9OoPNp5~_K`A3,$$wd^T?y`5~ 3,$$R*c+$ʗ-5~3,$$\-mz{5hq 3,$$*VMdk5~g,3,$$aŞL=ALm\x 5~Bx3,$$Uf)$mƩh%5~SJ3,$$0CgSls5y5~BbG3,$$ua5Ŧw?EԛN5hx'X3,$$ ;}&7 Vc5~3,$$O/(OUeSaEc%v5~=3,$$"j^ `5~|x3,$$ s;=4bi c5~I(:3,$$ 1kjZP5hA3,$$]8|CHJᏙ5~$ 3,$$)k'OF5~$3,$$ У1x(VY5~1fA3,$$4ЄȜk &C5~kV(3,$$Vf|iV 5~+ 3,$$u!E>e'l]iw5h[?93,$$VY(X FA=25h{e3,$$$|s{i5~D3,$$j+,\y65~J3,$$Hxe6KH-ɟ5h.3,$$e$l,РC\c5~/Bϭ3,$$Qu:_f=Yc"5h[pg3,$$;SsIߒR-;5~ {3,$$w7C_5~*C3,$$^֓MDS75hzU63,$$5#JD,ҫO5h#}3,$$_/Io}(Os;5ho|:B3,$$i/YxGQ"5P4^3,$$p{e,Zw 75hb1+3,$$ gxļ0'{f5h}z3,$$Ir=hvKӞ5h;E3,$$!m2Z& 5h9@I3,$$}Ȍ,zyO5~J3,$$txNo{~5hQ3,$$o+I5w5h-3,$$^ПC kɘ5~G;"3,$$IXN:悋05hĬH3,$$R 5I$5h}3,$$p8R65h[3,$$z1>:RJ;]5hz3,$$j ^mGa5~.3,$$>cJ;em&5h3,$$T>@ gl!!5h^U3,$$!N6:C̙/ї5hkR3,$$o;RbҝC%Ӟ5hS3,$$0p'܂5h;3,$$:Gc'\c#5h/b3,$$rm`VJ5h3,$$*y =ˢÛD"U5h z 3,$$)7oA !5hj45S3,$$;ű||d5~kg3,$$~CŊN5~Y3,$$?w'!1E2:n5~ G3,$$s._֞{FL{UVo5~TQ!3,$$ckSoJs5~(93,$$yh&5~O33,$$b>5`+٭`>%ɖ5~#V#3,$$6 }b7F<5~e3,$$UcU!V5~e3,$$Forf(F\5hY3,$$Lۤ!5h3s=3,$$yΡ@2͛LI[5h6 3,$$~9'BbaN0v45haE~3,$$AʎS/݂5h~3,$$fӷ =wm [?w5hW`3,$$K]J$M3q/5h3=3,$$S9{+[5h Xh$3,$$q`3 U5h<3,$$zu`U+_5h&4 M3,$$];+:v 5h aC3,$$-h&[5h 3,$$)HQk^ͨhPCL5hz3,$$iJ><@nw~5h @3,$$p(NhS5~w^3,$$#`TbN_@ G5~H3,$$0,9\."#_wWam5h5,~3,$$7|"]d 5~`3,$$ib;&ᵓ٩5~/{b3,$$͞5: Lge5~lbG63,$$)Ѳ/m:;5h8sv3,$$2=;)K n'5hƅ]V3,$$WMO J965hF3,$$H7zuO n5h) >a3,$$08%5h+VvE3,$$I#&@Y՗|gp5hd&3,$$6gGkȱR'5h#`93,$$[X95h!#;fS3,$$WM3MD5hLVq3,$$a"5IFKx5h%3,$$7>$&S,3j5h")(3,$$h3b {W)G5h zS~3,$$.[dzzuZ5hY73,$$qoܛ)v5hwP$3,$$lZ1;XUp5h93,$$$Q϶F=m;5h1A83,$${x>U5h$dh3,$$3m67t5hh&3,$$v, A5hK3,$$SmSׇG\5hș)@3,$$2k'Hs85h,3,$$dA?o"^%75h"Aݘ3,$$|>D`UѶ5h  3,$$%vn #c|65hIz 3,$$ziPR545h>d %3,$$v/wvVi 5h&'& 3,$$|us=C=5h+j3,$$RqWׄh5hR*̴3,$$斞]BA@c5hS!3,$$ n_cu'_PM45h RРo3,$$8 VF5h 3,$$WDf,v\a`05hn3,$$iSZ2ʏ!j5h5qaZ3,$$$?9!5hfs3,$$0h&@lQo5h,3,$$+Zu4:@uJ$ʏ5h"O 3,$$yRh7LZ+:h5hݙF~3,$$i]LpСM騽5h]d3,$$KWxrE0f5hL4g3,$$OJb3T5hOЃ3,$$G(uW XN 5hpF83,$$l9AB&5hcy3,$$},mYv_5h؎ 3,$$V K^3* 5h#~Vsx3,$$E5Gtb_n@r5h;e]G3,$$+s`*Mc5hWU3,$$jP5h ,3,$$zF"#C^n~S5hB^43,$$nA/5sk}5h%*"a3,$$]>ㅋ:ġ:95h&}h3,$$0`djyژ5hԹ3,$$W+z()ˆ5h!WK3,$$7iYCf `5h33,$$YsL+徊M"5hA3,$$3||Jbk 5h#Fu'13,$$qs'󲞶_#!15h=a v3,$$όR)J l?R5hkF3,$$"@!h+5h :3,$$2#&mvJ *cA5h'7R3,$$? 9Xk4q 5~X 4 g3,$$Ӄp#/ .r5~A} B3,$$kf ;Q`B5~<FE3,$$[_h:/'٤~'5~0$)3,$$8hs"ٽJ5h@73,$$fuyp=OKx5~ W`3,$$2KE5~ǂ3,$$27[ot{ቩd5~e3,$$m w {5~Ma3,$$78\?k~E[}5hSq3,$$Ԏ[zy"5~<=F3,$$:w1М!ȓ5~D97G3,$$i_FvG<긆5~K(Y'3,$$(W\ fhh5h( 3,$$X2W/5~ ?@3,$$IL`s^5~`C3,$$~iLnUd~%kQ?[5~>+#X3,$$|!@p>KMra5~ST3,$$!}¶V|t5h.}3,$$Fy"DH5~(\3,$$g7qZVAkp45~69!3,$$TH#FP?05h 3,$$= "c0`CN 5h !`S3,$$9>%&*5~<A3,$$.C\s!15~,3,$$&+28 Nג5~2E;Q3,$$p \<\CEZ5hh3,$$"3"Bl/5hj|3,$$q^aD_m1~ǚ5h!)T3,$$V J'Fj5~| *X3,$$Ti𧻓őG5h&*3,$$J%yEe5BZAm5h꠳3,$$֒^FFE0.5~T!3,$$YBm/ XU05hLH>>3,$$j}DM;95~7-K3,$$Q]s:R5h y=3,$$6%%y(8FLLM5hU3,$$[,tXEr5~Mf3,$$C،[ sOs5~S;3,$$pVfDk@h5~H0l3,$$L!i$e5hg>3,$$컐.Sqy5~?ՒC3,$$5Nc?:塷5~d"3,$$awBm"Ub_C5h>=3,$$MTrdy.PE5hIO3,$$gc1څT]5~ \Z3,$$JXa#MM`T5h t3,$$ FeFW)5h yr޽3,$$P7d5~>U*3,$$Iht`N 5~㐆3,$$+ /65~AF3,$$tnzm7 5h{83,$$JF5h\3,$$>98ֽE5~ [I3,$$XX<^5~l3,$$qxP{V#25~l)3,$$mQ!%BaJ5h /Ne3,$$2B9?J05~Zp23,$$^{* n$5~u3,$$KX|#w)<]B5~l\3,$$!߆ӊ$*6},5ha3,$$FI gf MiTFѻ5~XI3,$$b3a[5~o=I3,$$VX[>},5~3,$$TH933בO{]N5~!M?3,$$;@(=[ڢ5~ )9к3,$$c}$kJ5~Y3,$$/ XvI"1X5~~"3,$$!4tZ35~ĸe3,$$@LV&&|5~;`3,$$%ɘn5~^3,$$8}HjufgI5~|/h3,$$1U1 X}~5~f!] 3,$$y^Z<5~W&B3,$$\-bWrՒ)5~ T#3,$$PKcTR1 5~. :3,$$Z.o:s5hfQ3,$$y0_ބ/<5hl^(H3,$$r";j!s|e5~6J 3,$$@\xjmS5~%{ge3,$$rRf:fa95h 43,$$Pn?g FOuIP5hx3,$$vm;u=!5h.za+3,$$"ҍBw5hz3,$$*#X1=02`5hl3,$$8@H(u9kDv5h!3,$$f*٘ }FI5hVQ3,$$Z0'h5h7Y8~3,$$4*--4 杺65hC3,$$ QJ'O/?UHD5hW3,$$ Im'x ;R"z35h{3,$$KNOh6:nk5h#U3,$$6+խhb@pMX5h+1D3,$$GEs,D1Qpn25hm43,$$U&hRgł1AY܈5hQ,3,$$(v/$apPr?5hc~3,$$eJc`o%,5P+A83,$$th&N5g5h0$C,3,$$&OGd 5hN13,$$d*>5h.bOx3,$$KmZ +5hcV/3,$$s&7~ oYe4EL5h᮰3,$$]"нo@V5h*m93,$$]y,* |5hr쑠3,$$$s#ǐS$YM@⦌5h>3,$$ۅX똪XKb^5hq5r3,$$}Ms 5h33,$$IKB%\4E-@]Tb5hm3,$${:.iҰ$ 5hh(3,$$.Vm`TЫ*`,5hP3,$$fG%B\ )5hYj3,$$Ӝ^ M\=Dd5h : 3,$$\\ʸ+5h(-3,$$w|^0o*5h;3,$$~2@!.5hɗ3,$$=%ש 8E+5hc u3,$$uYyq:Te5h43,$$g9wudЊ5h*3,$$| EijDy^~5hF53,$$7b6_7bg5hW%3,$$Rtx?&_>5hPӘ3,$$Џ9;WKы5h3,$$Є|`;j5hn3,$$Tr-r?Z65h%5a3,$$<[u)) b5hsA3,$$RLX8.5h3,$$3g]uO_6N5hVA3,$$Qv2 5hV3,$$[szaH`5h!f03,$$O5،+Q4>5hXʛ3,$$@xonRN5hFZ(3,$$D|.RGQB]h5h -3,$$i[jmD5hO}3,$$Ν~R5h`b3,$$[TxNa\ Q;5h3,$$!#T妸5h,;;N3,$$Y>YE"ys5=j~ 5hr٨3,$$R\o5 -25h 3,$$RPrs&5h{3,$$c>s`pғ5hV#3,$$yPfDsܒnP5hw_ҽ3,$$ [oRD5hB3,$$ȥ?k9z5hlY3,$$Rs#wѼAN5hY52aS3,$$"Zkc` 5h<Rݣ3,$$I %Ib76I5~\|3,$$.D'5h;3,$$- Q>,om5hCVg3,$$"-6Jԯ5h3,$$"dQk)+co5h냪3,$$6-:վƁk5h%l3,$$4bW>2Le| 5hYT03,$$u>3DJFf\ E; 5h+.3,$$7!?b^h5h6 3,$$%XE05h>]K3,$$xXև1 45h>p53,$$>kZg#5hِ3,$$$x٬[1d5h^3,$$h] dœN5huE3,$$44qv<\0 x5h9Z3,$$J~{93A i5h#Lظ3,$$Tُ5h3,$$̾B Vw~U3R>5h' <3,$$' \y5h{3,$$, c6h js5h]>3,$$/(jzP!r5h3,$$>}B?BIG3n5hA3,$$$"˳|/U5h:'3,$$X( >S}s5hFֿ23,$$>'숝mA$5h4@3,$$0Օ#1y'h5hmo3,$$SIkmVH x65h!3,$$/r(jZ\|L#5h'X3,$$_}\bt5h.f 3,$$ɨN6[$s!~z\5h13,$$PS#U5h!N3,$$@@ 3.kO5h\f&3,$$t^YZҙ5h93,$$;lE%S'W@+M%5h҉3,$$xf QU:a߹5h;3,$$~Em[w{5h9t3,$$yfpq*ffn5hp>3,$$vDX)!IJ6t-5hC`O3,$$/jOj-5h*X׃3,$$kq2O15hGk3,$$dzYpnT DX5hTRI3,$$$5cW* w5a5hTZ! 3,$$!z4.<`5hIK3,$$!˞\ 5h>3,$$kTO'8,:+5hؒ3,$$‡$*B3P5h'۝43,$$Nok?Gch5h9Ư3,$$s3Z 6IM҉5h_3,$$qٜT:t5h$Y#3,$$#uE0Cl,N5hL3,$$`ɸ ^ß5hyB3,$$B4&pHБ 5h{3,$$PgѓmƁd5h}/3,$$.-1 8P*s)5h [3,$$DNM{}~j*:׽?5hNv?3,$$UHvR[C5h.?w؟3,$$2~-@Xԏ>>5h^KE3,$$y/:D*n\D5h_zS3,$$6C 35h 3,$$y(%CAO5h!"3,$$k3gs TJ 5ht3,$$`oY8Cf>5h+3,$$Rj:Dŵš@5ht3,$$X}-'qޞ[P5h,+?3,$$PdՂPBt5h rck3,$$0#h\Des/5hYA3,$$0]5&zu"5hL3,$$k˜m@M@T5hY3,$$_(95h$23,$$Z|.0؋=l~ ;5hNtw3,$$X/JEv}5h 03,$$zTpļ'A~u5hBM83,$$}1d\*S5h13,$$j|{EpcaU5hd-3,$$Hm>5| 5hVj!7.3,$$ut_ݷ8rZ67v5hF\3,$$-IFL2N5hm3,$$JS|%lH՞5h0eI3,$$V/UsL,>M5hp13,$$p_:hYwV5h "t3,$$3z)'l*5hw3,$$Nk-IH+5h;3,$$D=M<85hm3,$$p}a^qlk5h3mv3,$$U0 y.z&)\5h.3,$$Z//0H35h 3,$$<|\"t5hԙ3,$$}r^V5~|b3,$$snCf75hlٝ3,$$637[M5h3,$$;,4H5h+:4s3,$$N^R:5h33,$$m )w5hE3,$$?@9)lpE5h᎖3,$$9T?Z#w5h_Cȵ3,$$RL-fLl5h]M3,$$C3m5/#0Pe\5h2143,$$}~@rPK[5hvS3,$$ QLJ|`5hW3,$$GT"أJф5hG3,$$gF [D05hO 3,$$@$w"+Q5h83,$$`TD 7r`5h}3,$$R+LL@5h+3,$$JmU+n>5h* 3,$$CrI- 9U^65h~ժ3,$$+] 6y O5h$`Y*r5hvY3,$$ EzR@0E5hX3,$$g$LnZL75hq3,$$|/LFJLa^5ha3,$$F\s]+,8n`5h!R^3,$$e VeH,i8V5h8̪Z3,$$T nU P\5h3,$$rKؗN45h13,$$fKVd5h:tsx3,$$TOzrS{%5h`/3,$$}KN45hu3,$$^36 5hGPv3,$$iW;Ct֧Ԩ5hժ)3,$${)., ߫:]ͥ5hQr3,$$`'u 8,j,5h,3,$$;~ &%꒩D|5h~ްl93,$$NA5ht {3,$$տ7'?Z΋26y5hrv3,$$dM$5~8 JHb3,$$7Bp0fCD0+5P{G3,$$;)V:H1Z m5P53 3,$$%9z T5]70"kg3,$$WrrP4"5];h3,$$ NdyK_s[4b_h29a:R3,$$i ~c*ǹV*ex58 C33,$$LY'Ip2?+3,$$*P0tza 2N3,$$C+OR 2M"~3,$$,Oj2?%O z2 R3,$$fPQUSLXd58PC43,$$LSiQ艼2>z!3,$$4Py(PJ4=qh,=3,$$PVw#/pv5G*Av3,$$ϹJM#~8r 2SN3,$$W8iՅE.2 8k3,$$s_~WGKr@58խ 3,$$7/_QY|82R}3,$$ .Zb>P.#5G*<`cԲ3,$$_h1BsHWq29k3,$$X)T\8X4<2Gf3,$$q~& p$58|3,$$cSAJ>|58;53,$$ȏG%̻58 mw3,$$g4ZJay?,58nt3,$$x(z$42 J^ZD3,$$wty8a&׆c58JwPr3,$$*PuYk1ӡ2z3,$$m.ApЦ958`R3,$$@q)$2|2C3,$$^zyg2a3,$$nVSϒC>2 ?~3,$$3_?T0sw1c|n2L3,$$A$bxzxNJVQ>58f3,$$,u i58.3,$$hwe_p7Y%j58 |!{3,$$&R'kcܹ583,$$=oeQgV858 VMg,33,$$ƌ(;| =ki58nу3,$$U/t J)583,$$>w9P݌58 z3,$$3,h?vb58w 3,$$P>d쵡t58H3,$$YZ'ml58[`3,$$6_~}Q¾V58i!+H53,$$nF<:LBd58 3,$$艂FqW*@58=j3,$$YۥgZ58 H3,$$5}xξez* 2DY3,$$goZ,RLRp#58=f43,$$/id5P658VZ3,$$]եF8&58e]Ym3,$$-Hm C5G*=3,$$DO49^8@!58]I3,$$YWSj}l*58 BOd3,$$uf1?Wȧ58 g>e3,$$m`;<%Y58X3,$$fꛥ#DE2<$3,$$?g  :58b~3,$$O3=c' ӂR{58 RdF"3,$$C^~I%@\s58 ?]3,$$%f93/1S62 +?*C3,$$|s~tN >B{58[6/d3,$$Zu#'OͿ58403,$$@9peQ.Z58ўq3,$$~O[hS(+dy58 M#O3,$$auyE_N58eJ#;j3,$$ H-̩,9t58z3,$$ogt0[58h3,$$m$&5A%_58[Zc*3,$$+wJ=х+N\958U3,$$Eg6 'JH 58 N3,$$m$ZTS58r3,$$\$_>@tS58dx{3,$$aiU[ ˜2$в3,$$n IC))$YV 52"n3,$$%ސB 58旼e3,$$'0m5,6 2 i&Kn3,$$U"J%dG58 a3,$$TUP2?ZyZ3,$$[ 1rB+Xӕ\2RVAo3,$$7jgdw58~,>k3,$$ή d(A㾺32G|׹3,$$/EeC;82E,3,$$>p#8`{2qF>3,$$e gz[`O7E2 )3,$$9ϑoHẂPA58 F+3,$$YsǠ \*2JZg3,$$>x CY`2G3,$$xI2\˧* ]2:eJ3,$$eNH8MtVY25DĿ3,$$L0ͮΜx'e2 e3,$$a1ZRg58A^3,$$5?0D Cn 58B(3,$$8O#s +q~}5G*cP?3,$$lfGL)'H589 ܀3,$$=|3!(2 El3,$$V*-"&2 %(|3,$$q[8^;w22 I|w3,$$N S#` 2P3,$$ӝv2[9=24)3,$$f̃/2#+Ņ:2 ̂3,$$m3UTƁ+2׿3,$$t Tdƥ2T3,$$*: Q@3u2 yGl3,$$>,S$Vd#YfO2!X3,$$Sx>@c,ex2O3,$$V)`11syo26եF PX253,$$NY}"c52' cL3,$$2pK2 sn7F3,$$P9Bir*2 :s3,$${zAm%02}r<l3,$$7Z׈:޵ʮn58ʸi3,$$9՟6W;65G*G3,$$x_@ bj2 n13,$$ÓlO܅u_64 ?58 ]3,$$8]:72~4 3,$$'!~:`py581Hv"F3,$$W %~3oyD2͊Z3,$$M̯rvxJ23,$$L6>6 %+2ʌ3,$$dJX':ש^-e[J587!-3,$$73+c)Os\58)3G3,$$ }.U58_D3,$$LE v,58iPr3,$$)vy)R58  j-3,$$ eL]58*3,$$l~&p6I5G* #n3,$$@UQo˳2y!3,$$b ^dW~w/.c2F3,$$`aX%r(y?RyZ2@3,$$puRkR~X29E~3,$$}aJBl28:3,$$j~RH2 #P{3,$$0o~ -8P,2Z3,$$~g0Ja`۸K2-{/3,$$E vt+۔<2-ޞp3,$$$ԡc۷F2 7K3,$$l˵ nlC;2 :wFE3,$$Tg#U](""nb2/fe3,$$8D>WÚPf2F3,$$G 'xo6++3558vU3,$$E>~zy2S583,$$1˶"Iq$58G w3,$$[EDU5K_H58 U3,$$]&b|3,$$෧'\ml58)|̉3,$$x꘮99np5580/3,$$Qmh#XB58*l3,$$HT “M!do58'9ʿ3,$$+:x2É\~-h58V^m3,$$Syޠ |dtS58ZṚ3,$$xW.p2ϊ3,$$g[9ك58g=3,$$tnEF58#$03,$$j{/'s2~83,$$)`; `y58b3,$$M'rIaf#_58+?f3,$$f2Al2:;{v58"wN<3,$$q>MT$\R58 Ȩ3,$$92eDdЦd58%d3,$$/-'Q $2a58//3,$$ESbsa>2Ha$~3,$$ì58 ~3,$$auWR=5G*3,$$B`0QX#X:YV5G*`է3,$$F*B=#rNA358'P3,$$Z{IR`i58DTJ3,$$L=Kɵ587%k3,$$~R.:Ȑ45G*|-3,$$ua/G'HŌ2Q3,$$##P2"3,$$i`t32[z3,$$۳퍵9;58ܓi3,$$Fw|f7/-1!58 iz 3,$$WFcfɼ2S3,$$'PjqJOU<2`!3,$$+X lū-23,$$d=v/v,% 2.2kw3,$$bN:TTb'2'/>2=3,$$@ 583,$$JMrԐ3,$$CU[`g358Ug3,$$g%1yLe58&(o23,$$2aU;:煪58C0+WL3,$$Mmiuu5 Pp*U|3,$$XC4BTHuU`:/5 Pk.N3,$$F_pܿ1S5 P3,$$`'gp!5846 *3,$$GG_l P32j2 nN13,$$ D]1+.58Y`=3,$$ZuF`*wO5G*&avj3,$$FkxSiP23,$$wi(iP>2BZ3,$$ o3א}2 ۥS3,$$f{g0/Vy2\3,$$ ^T q$2 V}AX3,$$FXoA__Ti5G*83,$$3f@h5G*im3,$$x|y>'12:L&3,$$6s MAЮ3ۖ58c3,$$?VK֗58b3,$$ѣu1NMR58 ҲK3,$$ u(ru+2 C3,$$Y:_}|&紅58 d%3,$$Ca~_B2mW=3,$$Q)Șkax2ʓ3,$$x,>R R4Ąag23,$$p<7ɐB58VaC3,$$+SxlKH"B28I-h3,$$fP1:%58ts43,$$ `ɴRyu'2"3,$$v4x12tAK3,$$D*×:ТG23,$$|#2qbD3,$$H $$bڼ{`|1589\'3,$$hh6Zv!2?$3,$$o:yƪOſ2@~L3,$$:aCuC=ey 2BR'3,$$S$&[/ZuL2 3,$$=+Lu3a#&2CNH3,$$BlP2y[2+3ZO3,$$ u]e\=n2 3,$$ πd⍌&Vn921U&3,$$HY?D{SeF;58&b3,$$82Va̢-58C93,$$` y258}13,$$PN?CNw9?58p3,$$D=E%)J{ 2iQX3,$$ۣn?a+Y2 ;oz3,$$Y7\{.\;my2#^Z3,$$+1QS#2x`3,$$8%J9CߓV1y26z33,$$&<)uRC@H2IR3,$$1#2ςY+^5,432E@3,$$HOzI k158 x13,$$f\ ڊ! 58$ C3,$$8B޾K2,@ 3,$$PI"?$58 G3,$$CI;;58,X3,$$vt"e:S{fn21 83,$$Nh.ҩS2&d3,$$Xإˁk5G*1p?3,$$Ոiɮ$Ӣd58#$3,$$.ٰk4'2D3,$$PT}]t223,$$:a+ǻ>26V3,$$/eP\w2?,]3,$$>{>E!L584\3,$$jk6).EZ589M03,$$@YY$*Ău2R^F3,$$f9-Yvg2 53,$$TfB{,qoi"58PX"3,$$Ȃ|E*r: h27 {6S3,$$}*QEW&i6558,3,$$= P&[ 4.l27pp3,$$aѤu..(k2*!?T3,$$Itߞ P2W3,$$5:t yX`2 k@3,$$R٨ 2hR3,$$A;ғeg:5G* $G3,$$k7V6.4n2-L3,$$%Q+%583,$$j()s925h&3,$$\|ݣSa2<8s?3,$$I-8.^'u 22B3,$$foS}e2?] qvB3,$$Z~dL/m58>53,$$ƜޖYv&2 r&3,$$ UPݲq_r 2=E3,$$ 8Q,ټycc2 ɯ3,$$+! rYY: 32=nl3,$$+'tfG2~G3,$$R_T8e2i"3,$$DI)r9X32 $N63,$$ nힷ!2=x3,$$`@V}K2 b\3,$$78cKa "pRG2I,3,$$Mq.b+vԑ@2 3,$$;ܘsܟ)23,$$E҈SvI A2 Uú3,$$;:(S]2)R9E3,$$vGi_4Bs;{2  o3,$$@x7 2QG3,$$Sy *D_k2 x3,$$R+{EM0?wk=2 V3,$$ƶ3g0N6{2rNgA3,$$epk 9HQ[58 K*3,$$x8r/58|~#3,$$n%@^DES58 3,$$ȠȤ0[D &58/~43,$$ E/+lZ, 58cU3,$$; 58{+e3,$$J YW܋pڋA58 a3,$$coW7A3 a 5853,$$OВ#q`H5583,$$MLBF";J2 F!n3,$$Z~Z8U2фj3,$$0`b058.(3,$$J]#4<&aE58a73,$$cj'M T 2 5gS3,$$<=XOtUX22 P~83,$$~aEI2l 3,$$0EE!QkgK6渫2?>3,$$?Vy:h2\&3,$$o_1 2ӯ~3,$$V)gdңE7h)5G*:eY3,$$M/JZp2J3,$$(,;:e5G*1P3,$$vNcr)N̓58$T3,$$ 24_WϺ2T!3,$$GvRfQ 243,$$,"s\+h~P5G*Fud3,$$_;J'gk2i2*3,$$*x١0W<_L2Y 3,$$Xn%ۊK58ye 3,$$[Rsy2 r=3,$$UŔ%5'158H@'3,$$6}Pjaz)2BV^33,$$P, j8k2>e3,$$h0:I2K`n3,$$cms",q 2Gsu@3,$$DBuź q2C힄3,$$'yj)s5803,$$pUG DŏT58]r3,$$K:_'ѕ[۝58+3,$$E#SZYjQ58~j{3,$$6Sc5873,$$wj ~2!rE@283,$$fťLN2_l3,$$nZ`=22?_3,$$%$q"ڊ458G^3,$$< A[:n58*lk*3,$$:Ҥ?f|2 sL3,$$T+\Ţ/2 "3,$$?‘11Ӽ2")zH{3,$$PG Z9@4rH-58*c3,$$msڗ3i2`M3,$$TiV׊+N2qs 3,$$Mc?D2 3,$$szG\,w*2 3,$$,5X;\>E558$3,$$34z׬2yn.8\5G* 3,$$Β#1ՈM6Л-58?3,$$2=B$3,$$K@58,r3,$$4l sb>Y~u2O[^3,$$:/ehQeq58.3,$$7ʊQUmoV^|58]Ow0 .29.C].U: 2.WbTg.l|H.l.zs.|l.~`h ."p.OX.=.w.<.a.!J.5ZL.mf.ϡ@x.v"$v..}0b.i.p//7/)d [4/PtM/g}'`/x9N"/y?=/ܡ^4/// /u200!Ȕ0*u0B0ZM~0[wB0oUS"0wA`0x4r0~x0XX00ds050eD00040ZFw0oQ!1C<1F1 "1Em4r1Ik1W><1bxM>1nfuhX1$|1Ͻ(13vN1\(1Y1m2-i26`42n2r-2o+2_#292#2dU.25/A2 s2 2S\h3 [j3M63Y3\lBjb3^X;3L33z(4+ 40@46(94B(S4[ܒb4`rH4vH4zl^&4z[ 4~Th4J  4D12D4+h4@o$4hKB4x54NJ5:^\5Dj5Hʕ>n5K5ZrR 5_v5vX5Pj>5R5O?5 5yOl535x5t568T6w^Sj6t]6m:6,f~63E%6B^6J6LAL 6P(6W6eYm6yHeB6|v6|un66(6~6~I6N6߂"6,6,6ND6*C7mJz70C^}7487N.7Qnq7VYz/7^,47f)b7`567`7R7718Ep 88Hؔ8? 8zK8%58/X#8TZ8lO8}I@X8)8d8(8 8ɛ8{-8|9,989]?9#.9,L93h950m9:K09x<$9ex9R-9Ez9F9~69펺 9_9Ky:Q B:a:)#z:6ZbN:H/e:TOH:d??Z:y3::|:s:xa<:Ʊ:;(Z; ~Q;xXc;*V;3" ;8.2;S`y$r;TSa' ;[q.;^}px; j;1;;@K;]tl;ڈmx;ܩ7Et;zV<D#z<`,< b<)c–<.bv<[ .<:n<|Vʬ>y">#J>+K>9$>B1.>F Z>W>W-,>"y>#y>>>>yu>ݾJ> %>x>Ű???,P?6r?+_?4jD?;6X?> p?R!V"]~D3,$$UaBxK~23,$$eMݎD[%n58NFq3,$$,;0_J2oq3,$$-, ST2D53,$$ּb@Z_^2h=O3,$$V9~\;S23,$$Z?2+3,$$-wa<1ؐ2$3,$$RimX$V2UP$O3,$$ W(0ZqR2 y3,$$}_!CԼ6[2伆T3,$$A%M;2B 3,$$=0vY?72;3,$$h7=Y ' d2s(huq3,$$1X IFdy2|tw0 "| M4J&5̰<]r<0ZEn&Ft\<W6s0X]w\WԭJ~&I\Ԗ#b&b 6'f5$)}+7pH>0/T2S2~_9za2 J".>XƛDRuU(hO'HB5J7:0tUOKjno{9TkX T8hW Ǚ.JR5l 9:Y*7i8x9N8d\Zci$[,sb+š_*p^s( *-Xn ]4f :p0hzPt .> [4%X%/#PVɋdX9bbnI<\oMtؓ#TyP&ʶ " b>t*<"z(b XIn*Fo9}T@ȴŌ0#`.r,7{:8/R=׾G[OKQg$`SNUGPYN)_Tkz vsSF[8]2,t ~vNM.8@HgY[F<H3.9Ԣl/Z w_æ1 JL-pZZnjn1#rEc2E8>Pf+.i--J||tk&K%]K*'6JS@mc{voLpny v]F0X-Ce&]#Bef7ػ_.SD "v #'v)h 9nv;Iw(ATRŽk4WA&^_RY_\d ocr6vz- rJ0@ NFseRg@VT"Pom6*t0+ *V<Xz2{wFr)Y8Nr؄K8|~L(<1> 0lv+c '3c7Lg>k{{`:J!MwKwCU[-2 v35T7ggto3=d7JW26֜Vd2L~h1h?/LQő8RW2Vax VŎ* ZCJez~ Ҳ0h !%;$mMNBF8W\_J ]gv^@>3,$$50i/23,$$VJnC|jԴp2_{3,$$GtfE/yF6j25*3,$$ 91p0S&X=:B2 G{j3,$$2aC_$M923P3,$$rEɜ<ߓ=$2!i[3,$$`_|]2/ n3,$$S,d`=b\2r&3,$$ d#Ch(B62 !3,$$}rs^;58 .1d3,$$9n;ݧ2j23,$$j-QCblC+Y2!.+3,$$`H%ͫ58#oٰ3,$$?g[tV?58 Ѽ3,$$i00 [2$3,$$jGi!RĻg2c3,$$A~#Q^#58p3,$$`C4Kղ~ڞ2]0M83,$$Q)*?͘2:[щ3,$$J[:Ɛ^U2a3,$$ $^x0M&rΫ2NPPaG3,$$(O/ާ/.G58%1w0 Z|8a-Afpy!2 R:P23ݐ1^(*TfI0f?*^ Q0!D-SǺOw3dhp%.AzaÂh5bƇP>qon"8$@.&+t~2~6qGLT!ME\)cg^t"|-H|VA87!z0ǻ}T-R T/8X =O[P,S5!WBZ~AΑELruDbʿ*+:0(!Z!C%^HiTfNcK|mnn,pSteCvl>߬;6"|::Tlf v?uBFCcI:W6q O:42cva+w@ EUh0t6EKn@p@K^8MuZbWX+\-_vwgRTrg#sH$t['GIЪUؐy,jP(w*^{./U2/k=ͲlO7(btNhgA^g$#Xn5ns08[i9Z`4{&X:1X )PKH&O9O|jOS,@vPpyXT-VhK3֪y٦Mx|N:tP4D2 & Y)nxJHIEzբfH,g{kp[8>)z=^u}"g3<GJPG]1p/wQ:bLQ8ئ`so4 p}z$jVڶLUlz›\uo6 > dOA~et#8<TQ GcFbnB$u|&^<h6TTUo.Sz{TOڕ.adൈ:C2]>V_,&'{)}pxQx|~ fdG3qx4ۓ޲u}.A5l>Dl@tDMBLe0i?9k(H sfZbB~Z@@A}I8S|[WR]>pb~@T&/C|w30o$p#%/ъC RVQXfXFdVuE-4WQF(t#xD.Nx$nL;"8:0~53,$$$`g6^Um245N3,$$G\p=}2 (I3,$$*_.v(U2A3,$$ RR} {*584-r3,$$x9He2h&3,$$Bl+E2F2p]3,$$nRbG62`3,$$Fu5Fu82. w3,$$ Pk?q6~'458EaQL3,$$J*&c~BP!D\58&hi3,$$^)P58U3,$$OJtQ։yye2J3,$$U7΁M+<[58{ K3,$$]xN`YD4=qh z3,$$#F=' R5K"58$t\3,$$3A)58^x3,$$<;O4 55y58Y6sv3,$$xr'w58%I 3,$$PyPS7558Cױ3,$$\f58=3,$$ =!'l#|ݧ58 eD3,$$ىp7s'uRM 58 2֬3,$$ZOC9P[p58 JZ3,$$F#C#@v'l58 j3,$$C$` f7i1+58.Ⴇ3,$$ T3a] 058Z E)N3,$$TK4Hsu7e*58& bZ3,$$ſwyXv =58 dD74U3,$$U%س@ s58nٵ3,$$_$߀l58AbL+h3,$$g%A㋡O58\3,$$=6$kFjX3WF2eN3,$$2Jz6-x/u2 L%O3,$$gOC&g2# 3,$$W`@o469Y2T;t3,$$+>9!2F'3,$$|\o>E=z2.3,$$JrH58.3,$$G"[?Q58K&_3,$$).Kڸ(ı58fzC3,$$di͆o!2%3,$$44WNw2Õ3,$$|"%T2i3,$$K,dV_5A23,$$0%ZBM2h$X2 v켙3,$$uZǥf#(MIF2I |3,$$/V&gQn2f+3,$$ ;; QڳL2.K^'3,$$mk9F' 58IJ3,$$td=@W1-2<)($w0 peXphpt p5_pqj qkxq OA<~q/H0q0q1q5'q;XqOzqj rqtWs8qz- q V~<qWq1_q<9q qvrrXJ+xr/mr2r66$zr7W.rr $r܏rx"r.ZrPr-,rF(Xs $sMs(Vr4s=J$s>>8s[Z/sm]^s|^<s/pss_s6Vsvsds sFLs^rs&Bs1s9< ss`:t4-4t3_tR!t\pt\`ʾtxڕ2t*etwntHAtt]trRpttjt,,tR+tM*t˦uu IYgwPkwQIlwVs8wZw^dY*w^w{wS[2wowLw_nhweUwħX5>wu DwWX,xzx$x(n&x)>x8(x;yoxA=xSIFxSx^Jxr9xsCBxwx{}x~xۧxxW@xfxxMxfM'hx64x +xlxUx/Ny2u|y"1hy*42y+=\yEݗ>yIq yyvo*y^yVWy[yy}1*y^3y ?yȵ.yRySyb yy7zAJTz3{zv.z&zzD<zSN{|{@{>{B{_dh{*{]b^{ȴ{Xj:|(=|!N|,? :|6|;t|CL&\|N?zx|Q|R|U_H|d[|u N;|v4N||Ez| |׾B|xn|5|(hF|,*|Z}pmjx}Wp\} Al2}$}.]iV}Oo}dlz~X~gkn~i~@~Be(T~,x2~5Ctp~R~h~|~.0~M~0> Z*\4 -7ZXE:BGR#oHK Tt-76K!&֡k&ټ9?.ݍb]R3,$$"򓎗;]2Et3,$$XA]g{OX^2'fT3,$$L+n>D/ l2/3,$$:b'"΄e2 _3,$$z)HҕT2%3,$$kqxC ]s32Y̋3,$$JRFz.H2 dg~H3,$$=2ۖ衅qwyp2)N69'3,$$VInA=B͈26*3,$$ dz2phX2">3,$$||aJk23,$$=E)vn;;ry2 3,$$#AJdN=2]23,$$ dc8 weW$Q2_T}+3,$$؍"Q':J&2ܧ͒3,$$8{P|Er`?&58!=nQ3,$$i6pW&58E&D3,$$[8p0W̓d|2B|oU3,$$'ރqh%58LV6/3,$$g[n}2 uێ3,$$U᧿e h2·V3,$$w8?γ)=ۯM58v3,$$q\+r@t4gږ58 6 03,$$10e5|58(nɅ3,$$n~FvQ58#veI3,$$@1dccOQzKj58=K3,$$IUSU㧥58[Թ3,$$jI:I0G݀ I2)~3,$$L< Q螥C2(S<ׯC3,$$̷ӿ0"26q+3,$$LSHu\:B&58]3,$$U w 'n.* 58 .3,$$OS|M$"x2('3,$$,'#ݡT2sݧ3,$$'pM02 [3,$$B"cO1O2c3,$$3 1k'Ǐl2JC3,$$}C>PXZ2 N3,$$VfiVE2zB3,$$ wer31g2Gw0 Oy<OP,P\PjoP{ZPIXPtPoPEc0PsP~sQ XQ մKQTVQKDQ\TQimFQz>_DQSlnQDQ0tQ8:Qr&QXQDQYDQ3 QRmsNRAZm8RM$mQR)<RI8$RR R0bRYvSSvzGSzJS#SaVS2hS<SbSxTlT\zbT)0-'~T\&T=ITcIT} T4[T~K4TtDTUkU+@XfUKޓULFUO+(UUKK2UelDUien?VUyJU+*$U4UU|y{UMS@UG7U+k'Ub U[VUh~VQ|V*jrV? `V?VVSrtV^P>VXV~2nVO V_VA<VɅlVܬ?1Vʀ%WgD"WkERW7(6aWP7~WTdWXc\WjuW{ W~--Wې W*~W> WgW X)+,X )TXX *VX({0rX,@(X0Xff"Xg#OXqXuXvDXzIaVXlX4X(XԪRX؉&X\J5(X9%ZY WTYȗVYHD_2Y^Y"qt Y'z,dY)+lY4 Y>}nKY?@YCɎYX JYPTYsbYY1Y!Y-oYߴQ&Ys}YshZ"KZ#4ZDcp0ZS(Z]xrbZ`RDZb'.JZd,UbZe3rWZnk6Z? ZN`Zp1mxZeZ"fZuPsZΖ |ZoZ{*ZKdZ}d` [[Nej[J"&[!_j[+BWS [+![/1dV[2 8P[8'T[G[Q[h=<7z[}t[-[~2[߽5[Ԁ[F/2[C[\ oP\B\&Z<\L+\Oi\Tn\kVZ6\x\\-\\Th\p\>\\m\"2\@t\#{]w~] V]\wL]-f]-b]YBC ][]c ]{x] ՞]]?E=].^]]k"] ]荳]vs]y^*^^7uGV^;FrP^ZŎ^igrH^zW^^4^:^[r_w&j_ wQ9J_ )_ H+ _)M|_3g _g O'R_n"_p'd_hB_i*__P{}_-f__ϸ^_ר0 _S?`i`c`&l `C`F<N`Ps`R\Q`UȼF`cs`v*`R9`~`"]0` `J~`Sum3,$$XhJ_oae{2)˫3,$$5NXu e;cqU2DJߐ3,$$&NitNϛ2 63,$$EYg- &඿x2p3,$$]o[I*V&͘58%33,$$1`iț›5n2uA3,$$>Qז:T#A%2MP~x3,$$159GU2?83,$$<Ey꘷M6?@2V3,$$ { ؂P2 2n3,$$~;I THwkZ2]3,$$/h'2 k+3,$$3j*Z?UBةH2,9^3,$$QֻRGC#T58R+?3,$$^p򷍎D58 @3,$$ʻQSKޠ>l2'3,$$~+_U1J458i 3,$$+%,HK2A3,$$ +Bs~o42"3,$$n . zH2{I3,$$DqZ"`Jpҷ58t{83,$$brpWn(1ZK7H>o28GBԏۆ9}  f Vf\1M^3~3j]xl+npw.qhAj!NX0!>QRȒ,~Ab~ "JE9/}B=Pc{34jK{_{QXL+J% (FӘ5yJEc622QnQlV 9%ZM%Uw^wo&JۈqR Rd$T@&YU9V(\2e&vq'B\ {@#/2V(.Tm۴T<4vGfN Df:A"@5| [d*,10C(5D)nIE@V6\>meJ1djE^nqtOf4NErCTݸfx y xG) hV#Ͱ\pXl\2oQshDt6hRSV^fg){NpqYd԰Kl~Px^0C}Xv? +.ro?Q }R+4B:<Ίn~`5<ŸT~we[+v,<GYDN>qZĦ8jsCr) V/P ) n, b9e|pF4jst@s͚9RY3x0$lRW~ ]T&XA<*8N Qd|`<"2B|J)8EjVt)z#1C-^.!gL~v?65R3,$$ Z.'sD,958bQ3,$$?)n#.KxN2k|C%3,$$*,  583,$$l0EB;pFRm_Ś58*3,$$߰ZG$&Ht@58 #i3,$$ pl'L/]2j7l3,$$d@4p9p\g+9w2!MC=3,$$S%^mfQ.<23,$$2_&d5G*8Pi3,$$A4vkD2 #=fo3,$$?..΍%58@x3,$$_P;)Ƣlo213,$$Uz\1:58 +'C43,$$jXwk%MP\S58-r<3,$$<&+rKdب7584i43,$$U+r'K@˜%58^ 3,$$ πn]88 58'Ǹ$Y3,$$]{-<⺘I2 (3,$$OII2g3,$$e&pe:jS585X3,$$։%SU58R`3,$$pCϟt=k]g58.\0y3,$$Y,~BUwH58-R3,$$mZKW^ Q5853,$$I!Ϫ,ѝW2h3,$$3O2|9PA58.B$[3,$$юAI[ЌzȐ&Y6 58-e3,$$2p.uld2cHc3,$$@5.ٓڴ.c/2-h3,$$o ۋIrL58.O]3,$$ΉS ɩjt`J583,$$?]`Ax:2O2c3,$$̵= +y!C2z3,$$w_DqN5#~2A3,$$pb,8y2 H<3,$$!T 2!O\YC^2=oS3,$$L Jr~=25 @3,$$ .vS4m@2X3,$$X5ޅ /Kw[2:&^3,$$xMKM@r'u <2&ah3,$$_ߤn `2x23,$$w9W"+MA{٩'GS58 !3,$$O= GUt_Q58 3,$$HؕL58FC3,$$){P@hA95G*X?`3,$$O*x+sr-Pm, 69v!@,1]lfa%a.w#{CZ=Tﲒ_ l2!Ӳ(F[+ Kg5MENJU cy>wb}) !UIqB\ǣ #O<,?p"\d]'(fz tl1p@4b>E_4Uf=tt$G^<y5q. WD)L83LQ`o&u+)b f+G[_ܤ-D4If-A*@*@:'A":IO`X]~hYF\~7e˔7V/R(,d2#P';NW\ejTRs} buGrk-#?)pڏEL2O$F %7 5ۂH|sQ`L%}\OTrUi W\kߖ`UF+ FAjf#xK@f1=Z$"yc'H(`LKT"VM|]N[Lh>\l/z{ X4hb&HҬF;Iy[xRB80?øǑjqfi^G B|ҩz *VK2YVJ4 6*)"F1N . Q8 ݢϺ$e9"t[LR .00yI3,$$kYEu o 2.\E3,$$9)t03p} 2T3,$$&!{ڠ3,$$240= u2DE3,$$ އ|].xA2J63,$$=dy+A28>!3,$$P=p I2!3,$$HA1d ~̇+2m3,$$剄SyA.6-58-GV3,$$Scf؇k6Z uH223,$$$i jإs2'R3,$$Q2p]Y:2M٨3,$$Al4{Pu28K3,$$eSʠvۊGf858,bB3,$$uMy-y/!R0*58[zp3,$$J 'IuE58wK3,$$R(/f58[X3,$$!ψ{>rv5859 e3,$$_e VS58; (3,$$[P.nZ*58sמF3,$$>YJR߫O58 3,$$iYW*+U58f'3,$$Gg'gq[r58ND-3,$$x)& nPx 58A_3,$$&$z.#~z8:=58R3,$$;RM=Q|H\58Z;@3,$$beӹChvE>-58 2wS3,$$̼E}c58S3,$$xQM~p58$3,$$e[JO؈$]58\k 3,$$c^9yU58%y3,$$ըqAuJryJL58G3,$$[U+;(d"58 *"S3,$$LrcjH-258ca3,$$Otx>Ͳ~58 b@3,$$1P RUZ58S,3,$$ƹYZNM{ɩ58tߺ3,$$z6Ku@AD58a 63,$$?u/{)ܼ;583,$$N"ӣR-nI58]2|y3,$$ьJj:"1ymc58%3,$$ny5+Sp?585U3,$$#(ѡ5}.WR@58B3,$$b!, cIyar2qp|3,$$JgۍQ@C58A G3,$$/UٱAtF358d^,G3,$$J3ʐJ0&¿r26z3,$$6T*{jXIP4&2ik*3,$$DtcJ2 >v8u3,$$[7bH@D-2 T3,$$z_sϵ2 CMY3,$$k:ҋRWB24K3,$$K[)()bj2 'j3,$$/ ]ȇLia~1h2 #(3,$$?=w֕l 58OBf8"2Sm3,$$8\:2 "3,$$GTskZvIf2b3,$$B_[}֦A2 1W523,$$ 'Rn h2 td{3,$$Z3a<|@y0>%2PX+3,$$Kis!I\58:p`3,$$7[3eAN.2>%3,$$[6V w\u2 U3,$$J Gάu5883-o3,$$C? "d&22^3,$$'rbiQk L25YR&3,$${~[y58,TXH3,$$)W]\)ܓΝ58 ?X 3,$$DRNƈn5~3,$$]& *}d/58 ^b3,$$NTVY58 ݛ3,$$|"AQwmalw 58w 3,$$.PxѫfH2< 3,$$ZhG58,$DK3,$$tͯ8ι[H6z8583,$$"33,$$8$r_f58)j3,$$C#B-a58Do3,$$[4H)BEa283,$$SZ_.;ͥV#D=2A5M3,$$)XB. 2 FPm.3,$$dZ~-_l< 587 ϴ3,$$f@qM}s~Ĵ,2 H3,$$IgeJم2ف.Q3,$$DV&}T@U2-{3,$$.;\@Q>2O,3eP3,$$vm-E-)2꽮l3,$$c4 jto758 07s3,$$\{ %<ն*Z2tY3,$$/"׉pb}2 3,$$hR+=$8ڸN(ˢB2#43,$$]%)5G*Ty)3,$$$Քp>!%2  3,$$ՠ!}6K+2 &{3,$$MSɈH$U~58?3,$$^KA}yl%`2` t3,$$tLָPl@b58$yA]3,$$ mAq6)N`U2 ET3,$$v)._TyeYŴ58 R#3,$$ v.\EƱ][q\<2i+3,$$e Yv ɺҴ2qz3,$$tpF->&@SB58$53,$$KJ+Kty2Rh2{j13,$$AlMrیb58 Gc3,$$O\ OX/q0.2MO3,$$Wu.LnUH2E33,$$Y#58LcL3,$$m%~[(2Nڳ3,$$>HԜ*n2z83,$$8QA>vJ]c58 $X3,$$C{t62ӳc24Ab<3,$$LSQyN<583,$$F_q7m2E;3,$$᧻WӐ{58 =3,$$))azԤ2a2;3,$$Czn[_= {6ՠ2 ;b3,$$9xEUz]u2 t3,$$4E7'WPmo2 \)k3,$$D*[)}\58#X;Vy3,$$47cLZ2t[?B<3,$$KԹ1q޷w\2y3,$$eRLS;v2=mUb3,$$-<ՑG(ge2 (b3,$$a-"d\o258%~3,$$zvlNڲGn58-Sv3,$$Iv=W}cŞ8"58"(3,$$z=2C?:aꯋ58_W3,$$eEvck; G58 =mf3,$$ $/Q߆58$f>3,$$ X[nF-z#58PD3,$$U֣ C58SYl3,$$QE]bx5e/23:ͪ3,$$N]mHFF*[z +58IcQ3,$$aeSa [58ڷ3,$$qhn) ǧr̪058#3,$$B6ickWvN58@02v3,$$Ŗ4'&58)3,$$׋~/ ,;} Ω58\y3,$$HtK)l2{x^3,$$*.Ƽ |58T^:@3,$$ZH4f(5G* NO>{3,$$tu  $o2~n3,$$۬r, Iq 5G* F3,$$}{82KQ0|/2^["`3,$$)%i[Cn58 %3,$$iGH씄'52+3,$$fRs$Ã58 (3,$$/j2OӖ3,$$O\q֢_W|e23,$$y;!RNt昴58!mZ{3,$$%M Zؓ?24?3,$$B?Y\Z92;sgw0 ЀfЍxЯOPдfп<#m>kw0A Zo:`">0xB{XzѡXQ<Ѳ, %2 a2$1V_F i{8mxEҍ ^ҹҽȼ;jYc~RH|,z ǀ(rv)zWl-Ky*D-HWSej<k`Ӊ"ӍinPIm~;B|XM:W^M2 4 =($YV[_? _^uԨ2z7 ԃ-ԍTZԮ~Բ(fɭ7-6ʢj~@Pv72S7|ZeP4Eo a7Ek\bE=tՄBbՅթETնF(^r({i@Q\2,#4H2OSOV4Q!-[JT_g֐p-?pִֵ!9ָǴRֿ|Zړv+)2LV6Y@9~}\C~uwy.܂FQL@܆o8ܑ)ܧKD>ɠ@-4zˣnA LVZPw0nSQQPݛ; 0ݟ_~ݵx˨ꪯHJtd l` ڀ@(O )z4GwQ,b0eQ,i^m"GH gw(o?/7 ;j.;?¨@NX߆Z$ߊ,ߎy@ߓpLߜ|-79fP U=XٗOD\q!4`$(btHmgu JB{n<63,Ѓ (t..j&M9' v/*PB-bx:I!3,$$]?$t9`j"E2 =/.3,$$? r$΢aL2|=)3,$$J&_$>z0bqZm3$58 3,$$QpmnWbaJ2T`t3,$$\~:å_a֮9_q=23,$$&([]Ta܎}T"2 ((*3,$$4_"7* 2&gv3,$$и>LA% Yg2=3,$$֦>e%GK%0585P3,$$-Y"{%'qEF58 ˆn3,$$kK+7]2ڄ3,$$8 -O@2>3,$$<۳y$ƃK;2i]3,$$r/[xVD58 gڴ3,$$a7aژ2 &2?p3,$$и& t|)$2'3,$$on;[2 i>3,$$`:~:({+3H2 `3,$$~N̑ R2v3,$$ésTZKۜ Groovy - An agile dynamic language for the Java Platform

Groovy - An agile dynamic language for the Java Platform
(GroovyDoc for Groovy and Java classes)

Groovy...
  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java objects and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java
groovy-1.8.6/src/main/groovy/0000755001501200150120000000000011715031256015432 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/transform/0000755001501200150120000000000011715031256017445 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/transform/TupleConstructor.java0000644001501200150120000001016311707612044023651 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation used to assist in the creation of tuple constructors in classes. *

* It allows you to write classes in this shortened form: *

 * {@code @TupleConstructor} class Customer {
 *     String first, last
 *     int age
 *     Date since
 *     Collection favItems
 * }
 * def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:new Date(), favItems:['Books', 'Games'])
 * def c2 = new Customer('Tom', 'Jones', 21, new Date(), ['Books', 'Games'])
 * def c3 = new Customer('Tom', 'Jones')
 * 
* The {@code @TupleConstructor} annotation instructs the compiler to execute an * AST transformation which adds the necessary constructor method to your class. *

* A tuple constructor is created with a parameter for each property (and optionally field and * super properties). * A default value is provided (using Java's default values) for all parameters in the constructor. * Groovy's normal conventions then allows any number of parameters to be left off the end of the parameter list * including all of the parameters - giving a no-arg constructor which can be used with the map-style naming conventions. *

* The order of parameters is given by the properties of any super classes with most super first * (if {@code includeSuperProperties} is set) followed by the properties of the class followed by the * by the fields of the class (if {@code includeFields} is set). Within each grouping the order * is as attributes appear within the respective class. *

* Limitations: currently not designed to support inner classes. * * @author Paul King * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.TupleConstructorASTTransformation") public @interface TupleConstructor { /** * Comma separated list of field and/or property names to exclude from the constructor. * Must not be used if 'includes' is used. */ String excludes() default ""; /** * Comma separated list of field and/or property names to include within the constructor. * Must not be used if 'excludes' is used. */ String includes() default ""; /** * Include fields in the constructor */ boolean includeFields() default false; /** * Include properties in the constructor */ boolean includeProperties() default true; /** * Include fields from super classes in the constructor */ boolean includeSuperFields() default false; /** * Include properties from super classes in the constructor */ boolean includeSuperProperties() default false; /** * Should super properties be called within a call to the parent constructor * rather than set as properties */ boolean callSuper() default false; /** * By default, this annotation becomes a no-op if you provide your own constructor. * By setting {@code force=true} then the tuple constructor(s) will be added regardless of * whether existing constructors exist. It is up to you to avoid creating duplicate constructors. */ boolean force() default false; } groovy-1.8.6/src/main/groovy/transform/Synchronized.java0000644001501200150120000001044511707612044022774 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Method annotation to make a method call synchronized for concurrency handling * with some useful baked-in conventions. *

* {@code @Synchronized} is a safer variant of the synchronized method modifier. * The annotation can only be used on static and instance methods. It operates similarly to * the synchronized keyword, but it locks on different objects. When used with * an instance method, the synchronized keyword locks on this, but the annotation * locks on a (by default automatically generated) field named $lock. * If the field does not exist, it is created for you. If you annotate a static method, * the annotation locks on a static field named $LOCK instead. *

* If you want, you can create these locks yourself. * The $lock and $LOCK fields will not be generated if you create * them yourself. You can also choose to lock on another field, by specifying its name as * parameter to the {@code @Synchronized} annotation. In this usage variant, the lock field * will not be created automatically, and you must explicitly create it yourself. *

* Rationale: Locking on this or your own class object can have unfortunate side-effects, * as other code not under your control can lock on these objects as well, which can * cause race conditions and other nasty threading-related bugs. *

* Example usage: *

 * class SynchronizedExample {
 *   private final myLock = new Object()
 *
 *   {@code @}Synchronized
 *   static void greet() {
 *     println "world"
 *   }
 *
 *   {@code @}Synchronized
 *   int answerToEverything() {
 *     return 42
 *   }
 *
 *   {@code @}Synchronized("myLock")
 *   void foo() {
 *     println "bar"
 *   }
 * }
 * 
* which becomes: *
 * class SynchronizedExample {
 *   private static final $LOCK = new Object[0]
 *   private final $lock = new Object[0]
 *   private final myLock = new Object()
 *
 *   static void greet() {
 *     synchronized($LOCK) {
 *       println "world"
 *     }
 *   }
 *
 *   int answerToEverything() {
 *     synchronized($lock) {
 *       return 42
 *     }
 *   }
 *
 *   void foo() {
 *     synchronized(myLock) {
 *       println "bar"
 *     }
 *   }
 * }
 * 
* * Credits: this annotation is inspired by the Project Lombok annotation of the * same name. The functionality has been kept similar to ease the learning * curve when swapping between these two tools. *

* Details: If $lock and/or $LOCK are auto-generated, the fields are initialized * with an empty Object[] array, and not just a new Object() as many snippets using * this pattern tend to use. This is because a new Object is NOT serializable, but * a 0-size array is. Therefore, using {@code @Synchronized} will not prevent your * object from being serialized. * * @author Paul King * @since 1.7.3 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.SynchronizedASTTransformation") public @interface Synchronized { /** * @return if a user specified lock object with the given name should be used */ String value () default ""; } groovy-1.8.6/src/main/groovy/transform/ToString.java0000644001501200150120000000741611715031256022071 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation used to assist in the creation of {@code toString()} methods in classes. * The {@code @ToString} annotation instructs the compiler to execute an * AST transformation which adds the necessary toString() method. *

* It allows you to write classes in this shortened form: *

 * {@code @ToString}
 * class Customer {
 *     String first, last
 *     int age
 *     Date since = new Date()
 *     Collection favItems
 *     private answer = 42
 * }
 * println new Customer(first:'Tom', last:'Jones', age:21, favItems:['Books', 'Games'])
 * 
* Which will have this output: *
 * Customer(Tom, Jones, 21, Wed Jul 14 23:57:14 EST 2010, [Books, Games])
 * 
* There are numerous options to customize the format of the generated output. * E.g. if you change the first annotation to: *
 * {@code @ToString(includeNames=true)}
 * 
* Then the output will be: *
 * Customer(first:Tom, last:Jones, age:21, since:Wed Jul 14 23:57:50 EST 2010, favItems:[Books, Games])
 * 
* Or if you change the first annotation to: *
 * {@code @ToString(includeNames=true,includeFields=true,excludes="since,favItems")}
 * 
* Then the output will be: *
 * Customer(first:Tom, last:Jones, age:21, answer:42)
 * 
* If you have this example: *
 * import groovy.transform.ToString
 * {@code @ToString} class NamedThing {
 *     String name
 * }
 * {@code @ToString}(includeNames=true,includeSuper=true)
 * class AgedThing extends NamedThing {
 *     int age
 * }
 * println new AgedThing(name:'Lassie', age:5)
 * 
* Then the output will be: *
 * AgedThing(age:5, super:NamedThing(Lassie))
 * 
* {@code @ToString} can also be used in conjunction with {@code @Canonical} and {@code @Immutable}. * * @author Paul King * @see Immutable * @see Canonical * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.ToStringASTTransformation") public @interface ToString { /** * Comma separated list of field and/or property names to exclude from generated toString. * Must not be used if 'includes' is used. */ String excludes() default ""; /** * Comma separated list of field and/or property names to include within the generated toString. * Must not be used if 'excludes' is used. */ String includes() default ""; /** * Whether to include super in generated toString */ boolean includeSuper() default false; /** * Whether to include names of properties/fields in generated toString */ boolean includeNames() default false; /** * Include fields as well as properties in generated toString */ boolean includeFields() default false; } groovy-1.8.6/src/main/groovy/transform/AutoExternalize.java0000644001501200150120000000546211707612044023443 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Note: This annotation is currently experimental! Use at your own risk! *

* Class annotation used to assist in the creation of {@code Externalizable} classes. * The {@code @AutoExternalize} annotation instructs the compiler to execute an * AST transformation which adds {@code writeExternal()} and {@code readExternal()} methods * to a class and adds {@code Externalizable} to the interfaces which the class implements. * The {@code writeExternal()} method writes each property (or field) for the class while the * {@code readExternal()} method will read each one back in the same order. Properties or fields * marked as {@code transient} are ignored. *

* Example usage: *

 * import groovy.transform.*
 * {@code @AutoExternalize}
 * class Person {
 *   String first, last
 *   List favItems
 *   Date since
 * }
 * 
* Which will create a class of the following form: *
 * class Person implements Externalizable {
 *   ...
 *   public void writeExternal(ObjectOutput out) throws IOException {
 *     out.writeObject(first)
 *     out.writeObject(last)
 *     out.writeObject(favItems)
 *     out.writeObject(since)
 *   }
 *
 *   public void readExternal(ObjectInput oin) {
 *     first = oin.readObject()
 *     last = oin.readObject()
 *     favItems = oin.readObject()
 *     since = oin.readObject()
 *   }
 *   ...
 * }
 * 
* * @author Paul King * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.AutoExternalizeASTTransformation") public @interface AutoExternalize { /** * Comma separated list of property names to exclude from externalizing */ String excludes() default ""; /** * Include fields as well as properties when externalizing */ boolean includeFields() default false; } groovy-1.8.6/src/main/groovy/transform/PackageScope.java0000644001501200150120000000524311707612044022642 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class, method or field annotation used for turning off Groovy's auto * visibility conventions. By default, Groovy automatically turns package * protected fields into properties and makes package protected methods * and classes public. This annotation allows this feature to be turned * off and revert back to Java behavior if needed. * * Place it on classes, fields or methods of interest as follows: *
 * {@code @}PackageScope class Bar {      // package protected
 *     {@code @}PackageScope int field    // package protected; not a property
 *     {@code @}PackageScope method(){}   // package protected
 * }
 * 
* or for greater control, at the class level with one or more * PackageScopeTarget values: *
 * import static groovy.transform.PackageScopeTarget.*
 * {@code @}PackageScope([CLASS, FIELDS])
 * class Foo {              // class will have package protected scope
 *     int field1, field2   // both package protected
 *     def method(){}       // public
 * }
 * {@code @}PackageScope(METHODS)
 * class Bar {         // public
 *     int field       // treated as a property
 *     def method1(){} // package protected
 *     def method2(){} // package protected
 * }
 * 
* * This transformation is typically only used in conjunction with a third-party * library or framework which relies upon package scoping. * * @author Paul King * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.PackageScopeASTTransformation") public @interface PackageScope { groovy.transform.PackageScopeTarget[] value() default {PackageScopeTarget.CLASS}; } groovy-1.8.6/src/main/groovy/transform/WithWriteLock.java0000644001501200150120000001003011707612044023042 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used in conjunction with {@link WithReadLock} to support read and write synchronization on a method.

* * To use this annotation, declare {@code @WithWriteLock} on your method. The method may be either an instance method or * a static method. The resulting method will allow only one thread access to the method at a time, and will wait to access * the method until any other read locks have been released.

* * This annotation is a declarative wrapper around the JDK's java.util.concurrent.locks.ReentrantReadWriteLock. * Objects containing this annotation will have a ReentrantReadWriteLock field named $reentrantLock added to the class, * and method access is protected by the lock. If the method is static then the field is static and named $REENTRANTLOCK.

* * The annotation takes an optional parameter for the name of the field. This field must exist on the class and must be * of type ReentrantReadWriteLock.

* * To understand how this annotation works, it is convenient to think in terms of the source code it replaces. The following * is a typical usage of this annotation from Groovy: *
 * import groovy.transform.*;
 *
 * public class ResourceProvider {
 *
 *     private final Map<String, String> data = new HashMap<String, String>();
 *
 *    {@code @WithReadLock}
 *     public String getResource(String key) throws Exception {
 *             return data.get(key);
 *     }
 *
 *    {@code @WithWriteLock}
 *     public void refresh() throws Exception {
 *             //reload the resources into memory
 *     }
 * }
 * 
* As part of the Groovy compiler, code resembling this is produced: *
 * import java.util.concurrent.locks.ReentrantReadWriteLock;
 * import java.util.concurrent.locks.ReadWriteLock;
 *
 * public class ResourceProvider {
 *
 *     private final ReadWriteLock $reentrantlock = new ReentrantReadWriteLock();
 *     private final Map<String, String> data = new HashMap<String, String>();
 *
 *     public String getResource(String key) throws Exception {
 *         $reentrantlock.readLock().lock();
 *         try {
 *             return data.get(key);
 *         } finally {
 *             $reentrantlock.readLock().unlock();
 *         }
 *     }
 *
 *     public void refresh() throws Exception {
 *         $reentrantlock.writeLock().lock();
 *         try {
 *             //reload the resources into memory
 *         } finally {
 *             $reentrantlock.writeLock().unlock();
 *         }
 *     }
 * }
 * 
* @author Hamlet D'Arcy * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.ReadWriteLockASTTransformation") public @interface WithWriteLock { /** * @return if a user specified lock object with the given name should be used * the lock object must exist. If the annotated method is static then the * lock object must be static. If the annotated method is not static then * the lock object must not be static. */ String value () default ""; } groovy-1.8.6/src/main/groovy/transform/Immutable.java0000644001501200150120000001543511715031256022237 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation used to assist in the creation of immutable classes. *

* It allows you to write classes in this shortened form: *

 * {@code @Immutable} class Customer {
 *     String first, last
 *     int age
 *     Date since
 *     Collection favItems
 * }
 * def d = new Date()
 * def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:d, favItems:['Books', 'Games'])
 * def c2 = new Customer('Tom', 'Jones', 21, d, ['Books', 'Games'])
 * assert c1 == c2
 * 
* The {@code @Immutable} annotation instructs the compiler to execute an * AST transformation which adds the necessary getters, constructors, * equals, hashCode and other helper methods that are typically written * when creating immutable classes with the defined properties. *

* A class created in this way has the following characteristics: *

    *
  • The class is automatically made final. *
  • Properties must be of an immutable type or a type with a strategy for handling non-immutable * characteristics. Specifically, the type must be one of the primitive or wrapper types, Strings, enums, * other {@code @Immutable} classes or known immutables (e.g. java.awt.Color, java.net.URI, java.util.UUID). * Also handled are Cloneable classes, collections, maps and arrays, and other "effectively immutable" * classes with special handling (e.g. java.util.Date). *
  • Properties automatically have private, final backing fields with getters. * Attempts to update the property will result in a {@code ReadOnlyPropertyException}. *
  • A map-based constructor is provided which allows you to set properties by name. *
  • A tuple-style constructor is provided which allows you to set properties in the same order as they are defined. *
  • Default {@code equals}, {@code hashCode} and {@code toString} methods are provided based on the property values. * Though not normally required, you may write your own implementations of these methods. For {@code equals} and {@code hashCode}, * if you do write your own method, it is up to you to obey the general contract for {@code equals} methods and supply * a corresponding matching {@code hashCode} method. * If you do provide one of these methods explicitly, the default implementation will be made available in a private * "underscore" variant which you can call. E.g., you could provide a (not very elegant) multi-line formatted * {@code toString} method for {@code Customer} above as follows: *
     *     String toString() {
     *        _toString().replaceAll(/\(/, '(\n\t').replaceAll(/\)/, '\n)').replaceAll(/, /, '\n\t')
     *    }
     * 
    * If an "underscore" version of the respective method already exists, then no default implementation is provided. *
  • {@code Date}s, {@code Cloneable}s and arrays are defensively copied on the way in (constructor) and out (getters). * Arrays and {@code Cloneable} objects use the {@code clone} method. For your own classes, * it is up to you to define this method and use deep cloning if appropriate. *
  • {@code Collection}s and {@code Map}s are wrapped by immutable wrapper classes (but not deeply cloned!). * Attempts to update them will result in an {@code UnsupportedOperationException}. *
  • Fields that are enums or other {@code @Immutable} classes are allowed but for an * otherwise possible mutable property type, an error is thrown. *
  • You don't have to follow Groovy's normal property conventions, e.g. you can create an explicit private field and * then you can write explicit get and set methods. Such an approach, isn't currently prohibited (to give you some * wiggle room to get around these conventions) but any fields created in this way are deemed not to be part of the * significant state of the object and aren't factored into the {@code equals} or {@code hashCode} methods. * Similarly, you may use static properties (though usually this is discouraged) and these too will be ignored * as far as significant state is concerned. If you do break standard conventions, you do so at your own risk and * your objects may no longer be immutable. It is up to you to ensure that your objects remain immutable at least * to the extent expected in other parts of your program! *
*

* Immutable classes are particularly useful for functional and concurrent styles of programming * and for use as key values within maps. If you want similar functionality to what this annotation * provides but don't need immutability then consider using {@code @Canonical}. *

* Customising behaviour: *

* You can customise the toString() method provided for you by {@code @Immutable} * by also adding the {@code @ToString} annotation to your class definition. *

* Limitations: *

    *
  • * As outlined above, Arrays and {@code Cloneable} objects use the {@code clone} method. For your own classes, * it is up to you to define this method and use deep cloning if appropriate. *
  • *
  • * As outlined above, {@code Collection}s and {@code Map}s are wrapped by immutable wrapper classes (but not deeply cloned!). *
  • *
  • * Currently {@code BigInteger} and {@code BigDecimal} are deemed immutable but see: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370 *
  • *
  • * {@code java.awt.Color} is treated as "effectively immutable" but is not final so while not normally used with child * classes, it isn't strictly immutable. Use at your own risk. *
  • *
  • * {@code java.util.Date} is treated as "effectively immutable" but is not final so it isn't strictly immutable. * Use at your own risk. *
  • *
* * @author Paul King * @see ToString * @see Canonical * @since 1.7 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.ImmutableASTTransformation") public @interface Immutable { } groovy-1.8.6/src/main/groovy/transform/ThreadInterrupt.groovy0000644001501200150120000001144311707612044024044 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import org.codehaus.groovy.transform.GroovyASTTransformationClass /** * Allows "interrupt-safe" executions of scripts by adding Thread.currentThread().isInterrupted() * checks on loops (for, while, do), the first statement of closures, and the first statement of methods. *
*
* This is especially useful when executing foreign scripts that you do not have control over. Inject this * transformation into a script that you need to interrupt. *
*
* Annotating anything in a script will cause for loops, while loops, methods, and closures to make an * isInterruptedCheck and throw a InterruptedException if the check yields true. The annotation by default * will apply to any classes defined in the script as well. Annotated a class will cause (by default) all classes * in the entire file ('Compilation Unit') to be enhanced. You can fine tune what is enhanced using the annotation * parameters. *
*
* Extensive usage examples can be found in the unit test for this class. A smaller example is presented here. * The following is sample usage of the annotation: *
*
 * @groovy.transform.ThreadInterrupt
 * def scriptMethod() {
 *     4.times {
 *         println 'executing script method...'
 *     }
 * }
 *
 * class MyClass {
 *
 *   def myMethod() {
 *       for (i in (1..10)) {
 *           println 'executing method...'
 *       }
 *   }
 * }
 *
 * scriptMethod()
 * new MyClass().myMethod()
 * 
*
* Which results in the following code being generated. Notice the checks and exceptions: *
*
 * public class script1290627909406 extends groovy.lang.Script {
 *
 *     public java.lang.Object scriptMethod() {
 *         if (java.lang.Thread.currentThread().isInterrupted()) {
 *             throw new java.lang.InterruptedException('Execution Interrupted')
 *         }
 *         4.times({
 *             if (java.lang.Thread.currentThread().isInterrupted()) {
 *                 throw new java.lang.InterruptedException('Execution Interrupted')
 *             }
 *             this.println('executing script method...')
 *         })
 *     }
 * }
 * public class MyClass extends java.lang.Object {
 *
 *     public java.lang.Object myMethod() {
 *         if (java.lang.Thread.currentThread().isInterrupted()) {
 *             throw new java.lang.InterruptedException('Execution Interrupted')
 *         }
 *         for (java.lang.Object i : (1..10)) {
 *             if (java.lang.Thread.currentThread().isInterrupted()) {
 *                 throw new java.lang.InterruptedException('Execution Interrupted')
 *             }
 *             this.println('executing method...')
 *         }
 *     }
 * }
 *
 * this.scriptMethod()
 * new MyClass().myMethod()
 * 
* * @see groovy.transform.TimedInterrupt * @see groovy.transform.ConditionalInterrupt * * @author Cedric Champeau * @author Hamlet D'Arcy * * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target([ ElementType.METHOD, ElementType.TYPE]) @GroovyASTTransformationClass(["org.codehaus.groovy.transform.ThreadInterruptibleASTTransformation"]) public @interface ThreadInterrupt { /** * By default, annotating anything in a source file ('Compilation Unit') will trigger this transformation * for all classes and scripts in that file. If you add the Annotation to an import statement, then all * scripts and Classes will be enhanced. If you want to change this behavior then set applyToAllClasses * to false. If you annotate a type then only that type will be augmented, not other types or the surrounding * script. If you annotate a script, then any enclosed types will not be augmented. * @return */ boolean applyToAllClasses() default true; /** * By default an isInterrupted check is added to the start of all user-defined methods. To turn this off simply * set this parameter to false. * @return */ boolean checkOnMethodStart() default true; Class thrown() default InterruptedException; } groovy-1.8.6/src/main/groovy/transform/PackageScopeTarget.java0000644001501200150120000000213411707612044024005 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; /** * Intended target when {@code @}PackageScope is placed at the class level. * * @author Paul King * @since 1.8.0 */ public enum PackageScopeTarget { /** * Make the Class have package protected visibility. */ CLASS, /** * Make the Class methods have package protected visibility. */ METHODS, /** * Make the Class fields have package protected visibility. */ FIELDS } groovy-1.8.6/src/main/groovy/transform/ConditionalInterrupt.groovy0000644001501200150120000001251111707612044025075 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import org.codehaus.groovy.transform.GroovyASTTransformationClass /** * Allows "interrupt-safe" executions of scripts by adding a custom check for interruption * on loops (for, while, do), the first statement of closures, and the first statement of methods. *
*
* This is especially useful when executing foreign scripts that you do not have control over. Inject this * transformation into a script that you need to interrupt based on some custom criteria. *
*
* Annotating anything in a script will cause for loops, while loops, methods, and closures to make a * check against the specified closure. If the closure yields true (according to GroovyTruth), then the script * will throw an InterruptedException. The annotation by default applies to any classes defined in the script * as well. Annotated a class will cause (by default) all classes in the entire file ('Compilation Unit') to be * enhanced. You can fine tune what is enhanced using the annotation parameters. *
*
* Extensive usage examples can be found in the unit test for this class. A smaller example is presented here. * The following is sample usage of the annotation: *
*
 * @ConditionalInterrupt({ counter++> 10})
 * import groovy.transform.ConditionalInterrupt
 *
 * counter = 0
 * def scriptMethod() {
 *      4.times {
 *          println 'executing script method...'
 *      }
 * }
 *
 * scriptMethod()
 * 
* Which results in the following code being generated. Notice the checks and exceptions: *
*
 * public class script1291741477073 extends groovy.lang.Script {
 *
 *     Object counter = 0
 *
 *     public java.lang.Object run() {
 *         counter = 0
 *     }
 *
 *     public java.lang.Object scriptMethod() {
 *         if (this.conditionalTransform$condition()) {
 *             throw new java.lang.InterruptedException('Execution interrupted. The following condition failed: { counter++> 10}')
 *         }
 *         4.times({
 *             if (this.conditionalTransform$condition()) {
 *                 throw new java.lang.InterruptedException('Execution interrupted. The following condition failed: { counter++> 10}')
 *             }
 *             this.println('executing script method...')
 *         })
 *     }
 *
 *     private java.lang.Object conditionalTransform$condition() {
 *         counter++ > 10
 *     }
 * }
 * 
*
* * Note that when you're annotating scripts, the variable scoping semantics are unchanged. Therefore, you must be * careful about the variable scope you're using. Make sure that variables you reference in the closure parameter * are in scope during script execution. The following example will throw a MissingPropertyException because * counter is not in scope for a class: *
 * import groovy.transform.ConditionalInterrupt
 *
 * def counter = 0
 * @ConditionalInterrupt({ counter++> 10})
 * class MyClass {
 *     def myMethod() {
 *         4.times {
 *             println 'executing script method...'
 *         }
 *     }
 * }
 *
 * new MyClass().myMethod()
 * 
* * @see groovy.transform.TimedInterrupt * @see groovy.transform.ThreadInterrupt * * @author Cedric Champeau * @author Hamlet D'Arcy * * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target([ ElementType.METHOD, ElementType.TYPE]) @GroovyASTTransformationClass(["org.codehaus.groovy.transform.ConditionalInterruptibleASTTransformation"]) public @interface ConditionalInterrupt { /** * By default, annotating anything in a source file ('Compilation Unit') will trigger this transformation * for all classes and scripts in that file. If you add the Annotation to an import statement, then all * scripts and Classes will be enhanced. If you want to change this behavior then set applyToAllClasses * to false. If you annotate a type then only that type will be augmented, not other types or the surrounding * script. If you annotate a script, then any enclosed types will not be augmented. * @return */ boolean applyToAllClasses() default true; /** * By default an isInterrupted check is added to the start of all user-defined methods. To turn this off simply * set this parameter to false. * @return */ boolean checkOnMethodStart() default true; /** * Sets the type of exception which is thrown. * @return */ Class thrown() default InterruptedException; /** * Condition should be set as a closure expression. * @return */ Class value(); } groovy-1.8.6/src/main/groovy/transform/TimedInterrupt.groovy0000644001501200150120000001143011707612044023673 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import org.codehaus.groovy.transform.GroovyASTTransformationClass import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException /** * Allows safe timed executions of scripts by adding elapsed time checks on loops (for, while, do), the first statement * of closures, and the first statement of methods. *
*
* This is especially useful when executing foreign scripts that you do not have control over. Inject this * transformation into a script that you want to timeout after a specified amount of timet. *
*
* Annotating anything in a script will cause for loops, while loops, methods, and closures to make an * elapsed time check and throw a TimeoutException if the check yields true. The annotation by default * will apply to any classes defined in the script as well. Annotated a class will cause (by default) all classes * in the entire file ('Compilation Unit') to be enhanced. You can fine tune what is enhanced using the annotation * parameters. Static methods and static fields are ignored. *
*
* Extensive usage examples can be found in the unit test for this class. A smaller example is presented here. * The following is sample usage of the annotation forcing the script to timeout after 1000 seconds: *
*
 * import groovy.transform.TimedInterrupt
 * import java.util.concurrent.TimeUnit
 *
 * {@code @TimedInterrupt}(value = 1000L, unit = TimeUnit.SECONDS)
 * class MyClass {
 *
 *      def method() {
 *          println '...'
 *      }
 * }
 * 
* This sample script will be transformed at compile time to something that resembles this: *
 * import java.util.concurrent.TimeUnit
 * import java.util.concurrent.TimeoutException
 *
 * public class MyClass {
 *
 *     final private long TimedInterrupt$expireTime
 *     final private java.util.Date TimedInterrupt$startTime
 *
 *     public MyClass() {
 *         TimedInterrupt$expireTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(1000, TimeUnit.SECONDS)
 *         TimedInterrupt$startTime = new java.util.Date()
 *     }
 *
 *     public java.lang.Object method() {
 *         if (TimedInterrupt$expireTime < System.nanoTime()) {
 *             throw new TimeoutException('Execution timed out after 1000 units. Start time: ' + TimedInterrupt$startTime)
 *         }
 *         return this.println('...')
 *     }
 * }
 * 
* @author Hamlet D'Arcy * * @see groovy.transform.ThreadInterrupt * @see groovy.transform.ConditionalInterrupt * * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target([ ElementType.METHOD, ElementType.TYPE]) @GroovyASTTransformationClass(["org.codehaus.groovy.transform.TimedInterruptibleASTTransformation"]) public @interface TimedInterrupt { /** * By default, annotating anything in a source file ('Compilation Unit') will trigger this transformation * for all classes and scripts in that file. If you add the Annotation to an import statement, then all * scripts and Classes will be enhanced. If you want to change this behavior then set applyToAllClasses * to false. If you annotate a type then only that type will be augmented, not other types or the surrounding * script. If you annotate a script, then any enclosed types will not be augmented. * @return */ boolean applyToAllClasses() default true; /** * By default an isInterrupted check is added to the start of all user-defined methods. To turn this off simply * set this parameter to false. * @return */ boolean checkOnMethodStart() default true; /** * The maximum elapsed time the script will be allowed to run for. By default it is measure in seconds * @return */ long value(); /** * The TimeUnit of the value parameter. By default it is TimeUnit.SECONDS. * @return */ TimeUnit unit() default TimeUnit.SECONDS; /** * The type of exception thrown when timeout is reached. * @return */ Class thrown() default TimeoutException; } groovy-1.8.6/src/main/groovy/transform/AutoCloneStyle.java0000644001501200150120000000210111707612044023215 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; /** * Intended style to use for cloning when using the {@code @}AutoClone annotation. * * @author Paul King * @since 1.8.0 * @see groovy.transform.AutoClone */ public enum AutoCloneStyle { /** * Uses only cloning. */ CLONE, /** * Uses the copy constructor pattern. */ COPY_CONSTRUCTOR, /** * Uses serialization to clone. */ SERIALIZATION } groovy-1.8.6/src/main/groovy/transform/Field.java0000644001501200150120000000406511707612044021341 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Variable annotation used for changing the scope of a variable within a script from * being within the run method of the script to being at the class level for the script. *

* The annotated variable will become a private field of the script class. * The type of the field will be the same as the type of the variable. Example usage: *

 * {@code @Field} List awe = [1, 2, 3]
 * def awesum() { awe.sum() }
 * assert awesum() == 6
 * 
* In this example, without the annotation, variable awe would be * a local script variable (technically speaking it will be a local variable within * the run method of the script class). Such a local variable would * not be visible inside the awesum method. With the annotation, * awe becomes a private List field in the script class and is * visible within the awesum method. * * @author Paul King * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.LOCAL_VARIABLE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.FieldASTTransformation") public @interface Field { } groovy-1.8.6/src/main/groovy/transform/IndexedProperty.java0000644001501200150120000000505211707612044023440 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Field annotation used with properties to provide an indexed getter and setter for the property. * Groovy provides nice GPath syntax support for accessing indexed properties but Java tools * or frameworks may expect the JavaBean style setters and getters. *

* Example usage: suppose you have a class with the following properties: *

 * {@code @IndexedProperty} FieldType[] someField
 * {@code @IndexedProperty} List otherField
 * {@code @IndexedProperty} List furtherField
 * 
* will add the following methods to the class containing the properties: *
 * FieldType getSomeField(int index) {
 *     someField[index]
 * }
 * FieldType getOtherField(int index) {
 *     otherField[index]
 * }
 * Object getFurtherField(int index) {
 *     furtherField[index]
 * }
 * void setSomeField(int index, FieldType val) {
 *     someField[index] = val
 * }
 * void setOtherField(int index, FieldType val) {
 *     otherField[index] = val
 * }
 * void setFurtherField(int index, Object val) {
 *     furtherField[index] = val
 * }
 * 
* Normal Groovy visibility rules for properties apply * (i.e. no public, private or package * visibility can be specified) or you will receive a compile-time error message. * The normal Groovy property getters and setters will also be created. *

* * @author Paul King * @since 1.7.3 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.IndexedPropertyASTTransformation") public @interface IndexedProperty { } groovy-1.8.6/src/main/groovy/transform/Canonical.java0000644001501200150120000001263711715031256022210 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation used to assist in the creation of mutable classes. *

* It allows you to write classes in this shortened form: *

 * {@code @Canonical} class Customer {
 *     String first, last
 *     int age
 *     Date since
 *     Collection favItems = ['Food']
 *     def object 
 * }
 * def d = new Date()
 * def anyObject = new Object()
 * def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:d, favItems:['Books', 'Games'], object: anyObject)
 * def c2 = new Customer('Tom', 'Jones', 21, d, ['Books', 'Games'], anyObject)
 * assert c1 == c2
 *
 * If you set the autoDefaults flag to true, you don't need to provide all arguments in constructors calls,
 * in this case all properties not present are initialized to the default value:
 * def c3 = new Customer(last: 'Jones', age: 21)
 * def c4 = new Customer('Tom', 'Jones')
 * 
 * assert null == c3.since
 * assert 0 == c4.age
 * assert c3.favItems == ['Food'] && c4.favItems == ['Food']
 * 
 * 
* The {@code @Canonical} annotation instructs the compiler to execute an * AST transformation which adds positional constructors, * equals, hashCode and a pretty print toString to your class. There are additional * annotations if you only need some of the functionality: {@code @EqualsAndHashCode}, * {@code @ToString} and {@code @TupleConstructor}. In addition, you can add one of * the other annotations if you need to further customize the behavior of the * AST transformation. *

* A class created in this way has the following characteristics: *

    *
  • A no-arg constructor is provided which allows you to set properties by name using Groovy's normal bean conventions. *
  • Tuple-style constructors are provided which allow you to set properties in the same order as they are defined. *
  • Default {@code equals}, {@code hashCode} and {@code toString} methods are provided based on the property values. * Though not normally required, you may write your own implementations of these methods. For {@code equals} and {@code hashCode}, * if you do write your own method, it is up to you to obey the general contract for {@code equals} methods and supply * a corresponding matching {@code hashCode} method. * If you do provide one of these methods explicitly, the default implementation will be made available in a private * "underscore" variant which you can call. E.g., you could provide a (not very elegant) multi-line formatted * {@code toString} method for {@code Customer} above as follows: *
     *     String toString() {
     *        _toString().replaceAll(/\(/, '(\n\t').replaceAll(/\)/, '\n)').replaceAll(/, /, '\n\t')
     *    }
     * 
    * If an "underscore" version of the respective method already exists, then no default implementation is provided. *
*

* If you want similar functionality to what this annotation provides but also require immutability, see the * {@code @Immutable} annotation. *

* Limitations: *

    *
  • * If you explicitly add your own constructors, then the transformation will not add any other constructor to the class. *
  • * * @author Paulo Poiati * @author Paul King * @see groovy.transform.EqualsAndHashCode * @see groovy.transform.ToString * @see groovy.transform.TupleConstructor * @see groovy.transform.Immutable * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.CanonicalASTTransformation") public @interface Canonical { /** * Comma separated list of field and/or property names to exclude. * Must not be used if 'includes' is used. * * If the {@code @Canonical} behavior is customised by using it in conjunction with one of the more specific * related annotations (i.e. {@code @ToString}, {@code @EqualsAndHashCode} or {@code @TupleConstructor}), then * the value of this attribute can be overriden within the more specific annotation. */ String excludes() default ""; /** * Comma separated list of field and/or property names to include. * Must not be used if 'excludes' is used. * * If the {@code @Canonical} behavior is customised by using it in conjunction with one of the more specific * related annotations (i.e. {@code @ToString}, {@code @EqualsAndHashCode} or {@code @TupleConstructor}), then * the value of this attribute can be overriden within the more specific annotation. */ String includes() default ""; } groovy-1.8.6/src/main/groovy/transform/WithReadLock.java0000644001501200150120000001011611707612044022630 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used in conjunction with {@link WithWriteLock} to support read and write synchronization on a method.

    * * To use this annotation, declare {@code @WithReadLock} on your method. The method may be either an instance method or * a static method. The resulting method will allow multiple threads to read the information at the same time. * However, if some other method obtains a write lock, then this method will force callers to wait until the write is complete.

    * * This annotation is a declarative wrapper around the JDK's java.util.concurrent.locks.ReentrantReadWriteLock. * Objects containing this annotation will have a ReentrantReadWriteLock field named $reentrantLock added to the class, * and method access is protected by the lock. If the method is static then the field is static and named $REENTRANTLOCK.

    * * The annotation takes an optional parameter for the name of the field. This field must exist on the class and must be * of type ReentrantReadWriteLock.

    * * To understand how this annotation works, it is convenient to think in terms of the source code it replaces. The following * is a typical usage of this annotation from Groovy: *
     * import groovy.transform.*;
     *
     * public class ResourceProvider {
     *
     *     private final Map<String, String> data = new HashMap<String, String>();
     *
     *    {@code @WithReadLock}
     *     public String getResource(String key) throws Exception {
     *             return data.get(key);
     *     }
     *
     *    {@code @WithWriteLock}
     *     public void refresh() throws Exception {
     *             //reload the resources into memory
     *     }
     * }
     * 
    * As part of the Groovy compiler, code resembling this is produced: *
     * import java.util.concurrent.locks.ReentrantReadWriteLock;
     * import java.util.concurrent.locks.ReadWriteLock;
     *
     * public class ResourceProvider {
     *
     *     private final ReadWriteLock $reentrantlock = new ReentrantReadWriteLock();
     *     private final Map<String, String> data = new HashMap<String, String>();
     *
     *     public String getResource(String key) throws Exception {
     *         $reentrantlock.readLock().lock();
     *         try {
     *             return data.get(key);
     *         } finally {
     *             $reentrantlock.readLock().unlock();
     *         }
     *     }
     *
     *     public void refresh() throws Exception {
     *         $reentrantlock.writeLock().lock();
     *         try {
     *             //reload the resources into memory
     *         } finally {
     *             $reentrantlock.writeLock().unlock();
     *         }
     *     }
     * }
     * 
    * @author Hamlet D'Arcy * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.ReadWriteLockASTTransformation") public @interface WithReadLock { /** * @return if a user specified lock object with the given name should be used * the lock object must exist. If the annotated method is static then the * lock object must be static. If the annotated method is not static then * the lock object must not be static. */ String value () default ""; } groovy-1.8.6/src/main/groovy/transform/AutoClone.java0000644001501200150120000001735211707612044022212 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Note: This annotation is currently experimental! Use at your own risk! *

    * Class annotation used to assist in the creation of {@code Cloneable} classes. * The {@code @AutoClone} annotation instructs the compiler to execute an * AST transformation which adds a public {@code clone()} method and adds * {@code Cloneable} to the interfaces which the class implements. *

    * Because the JVM doesn't have a one-size fits all cloning strategy, several * customizations exist for the cloning implementation. By default, the {@code clone()} * method will call {@code super.clone()} before calling {@code clone()} on each * {@code Cloneable} property of the class. *

    * Example usage: *

     * import groovy.transform.AutoClone
     * {@code @AutoClone}
     * class Person {
     *   String first, last
     *   List favItems
     *   Date since
     * }
     * 
    * Which will create a class of the following form: *
     * class Person implements Cloneable {
     *   ...
     *   public Object clone() throws CloneNotSupportedException {
     *     Object result = super.clone()
     *     result.favItems = favItems.clone()
     *     result.since = since.clone()
     *     return result
     *   }
     *   ...
     * }
     * 
    * Which can be used as follows: *
     * def p = new Person(first:'John', last:'Smith', favItems:['ipod', 'shiraz'], since:new Date())
     * def p2 = p.clone()
     *
     * assert p instanceof Cloneable
     * assert p.favItems instanceof Cloneable
     * assert p.since instanceof Cloneable
     * assert !(p.first instanceof Cloneable)
     *
     * assert !p.is(p2)
     * assert !p.favItems.is(p2.favItems)
     * assert !p.since.is(p2.since)
     * assert p.first.is(p2.first)
     * 
    * In the above example, {@code super.clone()} is called which in this case * calls {@code clone()} from {@code java.lang.Object}. This does a bit-wise * copy of all the properties (references and primitive values). Properties * like {@code first} has type {@code String} which is not {@code Cloneable} * so it is left as the bit-wise copy. Both {@code Date} and {@code ArrayList} * are {@code Cloneable} so the {@code clone()} method on each of those properties * will be called. For the list, a shallow copy is made during its {@code clone()} method. *

    * If your classes require deep cloning, it is up to you to provide the appropriate * deep cloning logic in the respective {@code clone()} method for your class. *

    * If one of your properties contains an object that doesn't support cloning * or attempts deep copying of a data structure containing an object that * doesn't support cloning, then a {@code CloneNotSupportedException} may occur * at runtime. *

    * Another popular cloning strategy is known as the copy constructor pattern. * If any of your fields are {@code final} and {@code Cloneable} you should set * {@code style=COPY_CONSTRUCTOR} which will then use the copy constructor pattern. * Here is an example making use of the copy constructor pattern: *

     * import groovy.transform.AutoClone
     * import static groovy.transform.AutoCloneStyle.*
     * {@code @AutoClone(style=COPY_CONSTRUCTOR)}
     * class Person {
     *   final String first, last
     *   final Date birthday
     * }
     * {@code @AutoClone(style=COPY_CONSTRUCTOR)}
     * class Customer extends Person {
     *   final int numPurchases
     *   final List favItems
     * }
     * 
    * Which will create classes of the following form: *
     * class Person implements Cloneable {
     *   ...
     *   protected Person(Person other) throws CloneNotSupportedException {
     *     first = other.first
     *     last = other.last
     *     birthday = other.birthday.clone()
     *   }
     *   public Object clone() throws CloneNotSupportedException {
     *     return new Person(this)
     *   }
     *   ...
     * }
     * class Customer extends Person {
     *   ...
     *   protected Customer(Customer other) throws CloneNotSupportedException {
     *     super(other)
     *     numPurchases = other.numPurchases
     *     favItems = other.favItems.clone()
     *   }
     *   public Object clone() throws CloneNotSupportedException {
     *     return new Customer(this)
     *   }
     *   ...
     * }
     * 
    * If you use this style on a child class, the parent class must * also have a copy constructor (created using this annotation or by hand). * This approach can be slightly slower than the traditional cloning approach * but the {@code Cloneable} fields of your class can be final. *

    * As a final example, if your class already implements the {@code Serializable} * or {@code Externalizable} interface, you can choose the following cloning style: *

     * {@code @AutoClone(style=SERIALIZATION)}
     * class Person implements Serializable {
     *   String first, last
     *   Date birthday
     * }
     * 
    * which outputs a class with the following form: *
     * class Person implements Cloneable, Serializable {
     *   ...
     *   Object clone() throws CloneNotSupportedException {
     *     def baos = new ByteArrayOutputStream()
     *     baos.withObjectOutputStream{ it.writeObject(this) }
     *     def bais = new ByteArrayInputStream(baos.toByteArray())
     *     bais.withObjectInputStream(getClass().classLoader){ it.readObject() }
     *   }
     *   ...
     * }
     * 
    * This will output an error if your class doesn't implement one of * {@code Serializable} or {@code Externalizable}, will typically be * significantly slower than the other approaches, also doesn't * allow fields to be final, will take up more memory as even immutable classes * like String will be cloned but does have the advantage that it performs * deep cloning automatically. *

    * Further references on cloning: *

    * * @author Paul King * @see groovy.transform.AutoCloneStyle * @see groovy.transform.AutoExternalize * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.AutoCloneASTTransformation") public @interface AutoClone { /** * Comma separated list of property names to exclude from cloning */ String excludes() default ""; /** * Include fields as well as properties when cloning */ boolean includeFields() default false; /** * Style to use when cloning */ groovy.transform.AutoCloneStyle style() default AutoCloneStyle.CLONE; } groovy-1.8.6/src/main/groovy/transform/EqualsAndHashCode.java0000644001501200150120000001713211707612044023571 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation used to assist in creating appropriate {@code equals()} and {@code hashCode()} methods. *

    * It allows you to write classes in this shortened form: *

     * import groovy.transform.EqualsAndHashCode
     * {@code @EqualsAndHashCode}
     * class Person {
     *     String first, last
     *     int age
     * }
     * def p1 = new Person(first:'John', last:'Smith', age:21)
     * def p2 = new Person(first:'John', last:'Smith', age:21)
     * assert p1 == p2
     * def map = [:]
     * map[p1] = 45
     * assert map[p2] == 45
     * 
    * The {@code @EqualsAndHashCode} annotation instructs the compiler to execute an * AST transformation which adds the necessary equals and hashCode methods to the class. *

    * The {@code hashCode()} method is calculated using Groovy's {@code HashCodeHelper} class * which implements an algorithm similar to the one outlined in the book Effective Java. *

    * The {@code equals()} method compares the values of the individual properties (and optionally fields) * of the class. It can also optionally call equals on the super class. Two different equals method * implementations are supported both of which support the equals contract outlined in the javadoc * for java.lang.Object *

    * To illustrate the 'canEqual' implementation style (see http://www.artima.com/lejava/articles/equality.html * for further details), consider this class: *

     * {@code @EqualsAndHashCode}
     * class IntPair {
     *     int x, y
     * }
     * 
    * The generated equals and canEqual methods will be something like below: *
     * public boolean equals(java.lang.Object other)
     *     if (other == null) return false
     *     if (this.is(other)) return true
     *     if (!(other instanceof IntPair)) return false
     *     if (!other.canEqual(this)) return false
     *     if (x != other.x) return false
     *     if (y != other.y) return false
     *     return true
     * }
     *
     * public boolean canEqual(java.lang.Object other) {
     *     return other instanceof IntPair
     * }
     * 
    * If no further options are specified, this is the default style for {@code @Canonical} and * {@code @EqualsAndHashCode} annotated classes. The advantage of this style is that it allows inheritance * to be used in limited cases where its purpose is for overriding implementation details rather than * creating a derived type with different behavior. This is useful when using JPA Proxies for example or * as shown in the following examples: *
     * {@code @Canonical} class IntPair { int x, y }
     * def p1 = new IntPair(1, 2)
     *
     * // overriden getter but deemed an IntPair as far as domain is concerned
     * def p2 = new IntPair(1, 1) { int getY() { 2 } }
     *
     * // additional helper method added through inheritance but
     * // deemed an IntPair as far as our domain is concerned
     * {@code @InheritConstructors} class IntPairWithSum extends IntPair {
     *     def sum() { x + y }
     * }
     *
     * def p3 = new IntPairWithSum(1, 2)
     *
     * assert p1 == p2 && p2 == p1
     * assert p1 == p3 && p3 == p1
     * assert p3 == p2 && p2 == p3
     * 
    * Note that if you create any domain classes which don't have exactly the * same contract as IntPair then you should provide an appropriate * equals and canEqual method. The easiest way to * achieve this would be to use the {@code @Canonical} or * {@code @EqualsAndHashCode} annotations as shown below: *
     * {@code @EqualsAndHashCode}
     * {@code @TupleConstructor(includeSuperProperties=true)}
     * class IntTriple extends IntPair { int z }
     * def t1 = new IntTriple(1, 2, 3)
     * assert p1 != t1 && p2 != t1 && t1 != p3
     * 
    * * The alternative supported style regards any kind of inheritance as creation of * a new type and is illustrated in the following example: *
     * {@code @EqualsAndHashCode(useCanEqual=false)}
     * class IntPair {
     *     int x, y
     * }
     * 
    * The generated equals method will be something like below: *
     * public boolean equals(java.lang.Object other)
     *     if (other == null) return false
     *     if (this.is(other)) return true
     *     if (IntPair != other.getClass()) return false
     *     if (x != other.x) return false
     *     if (y != other.y) return false
     *     return true
     * }
     * 
    * This style is appropriate for final classes (where inheritance is not * allowed) which have only java.lang.Object as a super class. * Most {@code @Immutable} classes fall in to this category. For such classes, * there is no need to introduce the canEqual() method. *

    * Note that if you explicitly set useCanEqual=false for child nodes * in a class hierarchy but have it true for parent nodes and you * also have callSuper=true in the child, then your generated * equals methods will not strictly follow the equals contract. *

    * Note that when used in the recommended fashion, the two implementations supported adhere * to the equals contract. You can provide your own equivalence relationships if you need, * e.g. for comparing instances of the IntPair and IntTriple classes * discussed earlier, you could provide the following method in IntPair: *

     * boolean hasEqualXY(other) { other.x == getX() && other.y == getY() }
     * 
    * Then for the objects defined earlier, the following would be true: *
     * assert p1.hasEqualXY(t1) && t1.hasEqualXY(p1)
     * assert p2.hasEqualXY(t1) && t1.hasEqualXY(p2)
     * assert p3.hasEqualXY(t1) && t1.hasEqualXY(p3)
     * 
    * * @see org.codehaus.groovy.util.HashCodeHelper * @author Paul King * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation") public @interface EqualsAndHashCode { /** * Comma separated list of field and/or property names to exclude from the equals and hashCode calculations. * Must not be used if 'includes' is used. */ String excludes() default ""; /** * Comma separated list of field and/or property names to include within the equals and hashCode calculations. * Must not be used if 'excludes' is used. */ String includes() default ""; /** * Whether to include super in equals and hashCode calculations */ boolean callSuper() default false; /** * Include fields as well as properties in equals and hashCode calculations */ boolean includeFields() default false; /** * Generate a canEqual method to be used by equals */ boolean useCanEqual() default true; } groovy-1.8.6/src/main/groovy/transform/InheritConstructors.java0000644001501200150120000001001111714271434024337 0ustar miguelmiguel/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.transform; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation to make constructors from a super class available in a sub class. *

    * {@code @InheritConstructors} saves you typing some boilerplate code. *

    * Example usage: *

     * class Person {
     *     String first, last
     *     Person(String first, String last) {
     *         this.first = first
     *         this.last = last.toUpperCase()
     *     }
     * }
     *
     * {@code @InheritConstructors}
     * class PersonAge extends Person {
     *     int age
     * }
     *
     * def js = new PersonAge('John', 'Smith')
     * js.age = 25
     * println "$js.last, $js.first is $js.age years old"
     * // => SMITH, John is 25 years old
     * 
    * for this case, the PersonAge class will be * equivalent to the following code: *
     * class PersonAge extends Person {
     *     PersonAge(String first, String last) {
     *         super(first, last)
     *     }
     *     int age
     * }
     * 
    * You may add additional constructors in addition to inherited ones. * If the argument types of a supplied constructor exactly match those * of a parent constructor, then that constructor won't be inherited. *

    * Style note: Don't go overboard using this annotation. * Typical Groovy style is to use named-arg constructors when possible. * This is easy to do for Groovy objects or any objects following JavaBean * conventions. In other cases, inheriting the constructors may be useful. * However, sub-classes often introduce new properties and these are often best * set in a constructor; especially if that matches the style adopted * in parent classes. So, even for the example above, it may have been * better style to define an explicit constructor for PersonAge * that also set the age property. Sometimes, consistent * style is much more important than saving a few keystrokes. *

    * As another example, this: *

     * {@code @InheritConstructors} class CustomException extends RuntimeException { }
     * 
    * is equivalent to this: *
     * class CustomException extends RuntimeException {
     *     CustomException() {
     *         super()
     *     }
     *     CustomException(String message) {
     *         super(message)
     *     }
     *     CustomException(String message, Throwable cause) {
     *         super(message, cause)
     *     }
     *     CustomException(Throwable cause) {
     *         super(cause)
     *     }
     * }
     * 
    *

    * Advanced note:If you create Groovy constructors with optional * arguments this leads to multiple constructors created in the byte code. * The expansion to multiple constructors occurs in a later phase to * this AST transformation. This means that you can't override (i.e. not * inherit) the constructors with signatures that Groovy adds later. * If you get it wrong you will get a compile-time error about the duplication. *

    * * @author Paul King * @since 1.7.3 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.InheritConstructorsASTTransformation") public @interface InheritConstructors { } groovy-1.8.6/src/main/groovy/ui/0000755001501200150120000000000011715031256016047 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/ui/ConsoleActions.groovy0000644001501200150120000002220511707612044022243 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.KeyStroke newFileAction = action( name: 'New File', closure: controller.&fileNewFile, mnemonic: 'N', accelerator: shortcut('N'), smallIcon: imageIcon(resource:"icons/page.png", class:this), shortDescription: 'New Groovy Script' ) newWindowAction = action( name: 'New Window', closure: controller.&fileNewWindow, mnemonic: 'W', accelerator: shortcut('shift N') ) openAction = action( name: 'Open', closure: controller.&fileOpen, mnemonic: 'O', accelerator: shortcut('O'), smallIcon: imageIcon(resource:"icons/folder_page.png", class:this), shortDescription: 'Open Groovy Script' ) saveAction = action( name: 'Save', closure: controller.&fileSave, mnemonic: 'S', accelerator: shortcut('S'), smallIcon: imageIcon(resource:"icons/disk.png", class:this), shortDescription: 'Save Groovy Script', enabled: false // controller will enable as needed ) saveAsAction = action( name: 'Save As...', closure: controller.&fileSaveAs, mnemonic: 'A', ) printAction = action( name: 'Print...', closure: controller.&print, mnemonic: 'P', accelerator: shortcut('P') ) exitAction = action( name: 'Exit', closure: controller.&exit, mnemonic: 'X' // whether or not application exit should have an // accelerator is debatable in usability circles // at the very least a confirm dialog should dhow up //accelerator: shortcut('Q') ) undoAction = action( name: 'Undo', closure: controller.&undo, mnemonic: 'U', accelerator: shortcut('Z'), smallIcon: imageIcon(resource:"icons/arrow_undo.png", class:this), shortDescription: 'Undo' ) redoAction = action( name: 'Redo', closure: controller.&redo, mnemonic: 'R', accelerator: shortcut('shift Z'), // is control-shift-Z or control-Y more common? smallIcon: imageIcon(resource:"icons/arrow_redo.png", class:this), shortDescription: 'Redo' ) findAction = action( name: 'Find...', closure: controller.&find, mnemonic: 'F', accelerator: shortcut('F'), smallIcon: imageIcon(resource:"icons/find.png", class:this), shortDescription: 'Find' ) findNextAction = action( name: 'Find Next', closure: controller.&findNext, mnemonic: 'N', accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0) ) findPreviousAction = action( name: 'Find Previous', closure: controller.&findPrevious, mnemonic: 'V', accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK) ) replaceAction = action( name: 'Replace...', closure: controller.&replace, mnemonic: 'E', accelerator: shortcut('H'), smallIcon: imageIcon(resource:"icons/text_replace.png", class:this), shortDescription: 'Replace' ) cutAction = action( name: 'Cut', closure: controller.&cut, mnemonic: 'T', accelerator: shortcut('X'), smallIcon: imageIcon(resource:"icons/cut.png", class:this), shortDescription: 'Cut' ) copyAction = action( name: 'Copy', closure: controller.©, mnemonic: 'C', accelerator: shortcut('C'), smallIcon: imageIcon(resource:"icons/page_copy.png", class:this), shortDescription: 'Copy' ) pasteAction = action( name: 'Paste', closure: controller.&paste, mnemonic: 'P', accelerator: shortcut('V'), smallIcon: imageIcon(resource:"icons/page_paste.png", class:this), shortDescription: 'Paste' ) selectAllAction = action( name: 'Select All', closure: controller.&selectAll, mnemonic: 'A', accelerator: shortcut('A') ) historyPrevAction = action( name: 'Previous', closure: controller.&historyPrev, mnemonic: 'P', accelerator: shortcut(KeyEvent.VK_COMMA), smallIcon: imageIcon(resource:"icons/book_previous.png", class:this), shortDescription: 'Previous Groovy Script', enabled: false // controller will enable as needed ) historyNextAction = action( name: 'Next', closure: controller.&historyNext, mnemonic: 'N', accelerator: shortcut(KeyEvent.VK_PERIOD), smallIcon: imageIcon(resource:"icons/book_next.png", class:this), shortDescription: 'Next Groovy Script', enabled: false // controller will enable as needed ) clearOutputAction = action( name: 'Clear Output', closure: controller.&clearOutput, mnemonic: 'C', accelerator: shortcut('W') ) runAction = action( name: 'Run', closure: controller.&runScript, mnemonic: 'R', keyStroke: shortcut('ENTER'), accelerator: shortcut('R'), smallIcon: imageIcon(resource:"icons/script_go.png", class:this), shortDescription: 'Execute Groovy Script' ) runSelectionAction = action( name: 'Run Selection', closure: controller.&runSelectedScript, mnemonic: 'E', keyStroke: shortcut('shift ENTER'), accelerator: shortcut('shift R') ) addClasspathJar = action( name: 'Add Jar(s) to ClassPath', closure: controller.&addClasspathJar, mnemonic: 'J', ) addClasspathDir = action( name: 'Add Directory to ClassPath', closure: controller.&addClasspathDir, mnemonic: 'D', ) clearClassloader = action( name: 'Clear Script Context', closure: controller.&clearContext, mnemonic: 'C', ) inspectLastAction = action( name: 'Inspect Last', closure: controller.&inspectLast, mnemonic: 'I', accelerator: shortcut('I') ) inspectVariablesAction = action( name: 'Inspect Variables', closure: controller.&inspectVariables, mnemonic: 'V', accelerator: shortcut('J') ) inspectAstAction = action( name: 'Inspect Ast', closure: controller.&inspectAst, mnemonic: 'A', accelerator: shortcut('T'), ) captureStdOutAction = action( name: 'Capture Standard Output', closure: controller.&captureStdOut, mnemonic: 'O' ) captureStdErrAction = action( name: 'Capture Standard Error Output', closure: controller.&captureStdErr, mnemonic: 'E' ) fullStackTracesAction = action( name: 'Show Full Stack Traces', closure: controller.&fullStackTraces, mnemonic: 'F' ) showScriptInOutputAction = action( name: 'Show Script in Output', closure: controller.&showScriptInOutput, mnemonic: 'R' ) visualizeScriptResultsAction = action( name: 'Visualize Script Results', closure: controller.&visualizeScriptResults, mnemonic: 'V' ) showToolbarAction = action( name: 'Show Toolbar', closure: controller.&showToolbar, mnemonic: 'T' ) detachedOutputAction = action( name: 'Detached Output', closure: controller.&detachedOutput, mnemonic: 'D' ) showOutputWindowAction = action( closure: controller.&showOutputWindow, keyStroke: shortcut('shift O'), ) hideOutputWindowAction1 = action( closure: controller.&hideOutputWindow, keyStroke: 'SPACE', ) hideOutputWindowAction2 = action( closure: controller.&hideOutputWindow, keyStroke: 'ENTER', ) hideOutputWindowAction3 = action( closure: controller.&hideOutputWindow, keyStroke: 'ESCAPE', ) hideOutputWindowAction4 = action( closure: controller.&hideAndClearOutputWindow, keyStroke: shortcut('W'), ) autoClearOutputAction = action( name: 'Auto Clear Output On Run', closure: controller.&autoClearOutput, mnemonic: 'A' ) largerFontAction = action( name: 'Larger Font', closure: controller.&largerFont, mnemonic: 'L', accelerator: shortcut('shift L') ) smallerFontAction = action( name: 'Smaller Font', closure: controller.&smallerFont, mnemonic: 'S', accelerator: shortcut('shift S') ) aboutAction = action( name: 'About', closure: controller.&showAbout, mnemonic: 'A' ) threadInterruptAction = action( name: 'Allow Interruption', closure: controller.&threadInterruption, mnemonic: 'O' ) interruptAction = action( name: 'Interrupt', closure: controller.&doInterrupt, mnemonic: 'T', smallIcon: imageIcon(resource:"icons/cross.png", class:this), shortDescription: 'Interrupt Running Script', enabled: false // controller will enable as needed ) compileAction = action( name: 'Compile', closure: controller.&compileScript, mnemonic: 'L', accelerator: shortcut('L'), shortDescription: 'Compile Groovy Script' ) groovy-1.8.6/src/main/groovy/ui/view/0000755001501200150120000000000011707612044017022 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/ui/view/BasicMenuBar.groovy0000644001501200150120000000601511707612044022566 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view menuBar { menu(text: 'File', mnemonic: 'F') { menuItem(newFileAction) menuItem(newWindowAction) menuItem(openAction) separator() menuItem(saveAction) menuItem(saveAsAction) separator() menuItem(printAction) separator() menuItem(exitAction) } menu(text: 'Edit', mnemonic: 'E') { menuItem(undoAction) menuItem(redoAction) separator() menuItem(cutAction) menuItem(copyAction) menuItem(pasteAction) separator() menuItem(findAction) menuItem(findNextAction) menuItem(findPreviousAction) menuItem(replaceAction) separator() menuItem(selectAllAction) } menu(text: 'View', mnemonic: 'V') { menuItem(clearOutputAction) separator() menuItem(largerFontAction) menuItem(smallerFontAction) separator() checkBoxMenuItem(captureStdOutAction, selected: controller.captureStdOut) checkBoxMenuItem(captureStdErrAction, selected: controller.captureStdErr) checkBoxMenuItem(fullStackTracesAction, selected: controller.fullStackTraces) checkBoxMenuItem(showScriptInOutputAction, selected: controller.showScriptInOutput) checkBoxMenuItem(visualizeScriptResultsAction, selected: controller.visualizeScriptResults) checkBoxMenuItem(showToolbarAction, selected: controller.showToolbar) checkBoxMenuItem(detachedOutputAction, selected: controller.detachedOutput) checkBoxMenuItem(autoClearOutputAction, selected: controller.autoClearOutput) } menu(text: 'History', mnemonic: 'I') { menuItem(historyPrevAction) menuItem(historyNextAction) } menu(text: 'Script', mnemonic: 'S') { menuItem(runAction) menuItem(runSelectionAction) checkBoxMenuItem(threadInterruptAction, selected: controller.threadInterrupt) menuItem(interruptAction) menuItem(compileAction) separator() menuItem(addClasspathJar) menuItem(addClasspathDir) menuItem(clearClassloader) separator() menuItem(inspectLastAction) menuItem(inspectVariablesAction) menuItem(inspectAstAction) } menu(text: 'Help', mnemonic: 'H') { menuItem(aboutAction) } } groovy-1.8.6/src/main/groovy/ui/view/BasicStatusBar.groovy0000644001501200150120000000234611627206700023147 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import java.awt.BorderLayout import java.awt.GridBagConstraints import javax.swing.SwingConstants statusPanel = panel(constraints: BorderLayout.SOUTH) { gridBagLayout() separator(gridwidth:GridBagConstraints.REMAINDER, fill:GridBagConstraints.HORIZONTAL) status = label('Welcome to Groovy.', weightx:1.0, anchor:GridBagConstraints.WEST, fill:GridBagConstraints.HORIZONTAL, insets: [1,3,1,3]) separator(orientation:SwingConstants.VERTICAL, fill:GridBagConstraints.VERTICAL) rowNumAndColNum = label('1:1', insets: [1,3,1,3]) } groovy-1.8.6/src/main/groovy/ui/view/MacOSXMenuBar.groovy0000644001501200150120000001006411627206700022635 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view def handler = false if (!handler) { try { handler = build(""" package groovy.ui import com.apple.mrj.* class ConsoleMacOsSupport implements MRJQuitHandler, MRJAboutHandler { def quitHandler def aboutHandler public void handleAbout() { aboutHandler() } public void handleQuit() { quitHandler() } } def handler = new ConsoleMacOsSupport(quitHandler:controller.&exit, aboutHandler:controller.&showAbout) MRJApplicationUtils.registerAboutHandler(handler) MRJApplicationUtils.registerQuitHandler(handler) return handler """, new GroovyClassLoader(this.class.classLoader)) } catch (Exception se) { // usually an AccessControlException, sometimes applets and JNLP won't let // you access MRJ classes. // However, in any exceptional case back out and use the BasicMenuBar se.printStackTrace() build(BasicMenuBar) return } } menuBar { menu(text: 'File', mnemonic: 'F') { menuItem(newFileAction, icon:null) menuItem(newWindowAction, icon:null) menuItem(openAction, icon:null) separator() menuItem(saveAction, icon:null) menuItem(saveAsAction, icon:null) separator() menuItem(printAction, icon:null) } menu(text: 'Edit', mnemonic: 'E') { menuItem(undoAction, icon:null) menuItem(redoAction, icon:null) separator() menuItem(cutAction, icon:null) menuItem(copyAction, icon:null) menuItem(pasteAction, icon:null) separator() menuItem(findAction, icon:null) menuItem(findNextAction, icon:null) menuItem(findPreviousAction, icon:null) menuItem(replaceAction, icon:null) separator() menuItem(selectAllAction, icon:null) } menu(text: 'View', mnemonic: 'V') { menuItem(clearOutputAction, icon:null) separator() menuItem(largerFontAction, icon:null) menuItem(smallerFontAction, icon:null) separator() checkBoxMenuItem(captureStdOutAction, selected: controller.captureStdOut) checkBoxMenuItem(captureStdErrAction, selected: controller.captureStdErr) checkBoxMenuItem(fullStackTracesAction, selected: controller.fullStackTraces) checkBoxMenuItem(showScriptInOutputAction, selected: controller.showScriptInOutput) checkBoxMenuItem(visualizeScriptResultsAction, selected: controller.visualizeScriptResults) checkBoxMenuItem(showToolbarAction, selected: controller.showToolbar) checkBoxMenuItem(detachedOutputAction, selected: controller.detachedOutput) checkBoxMenuItem(autoClearOutputAction, selected: controller.autoClearOutput) } menu(text: 'History', mnemonic: 'I') { menuItem(historyPrevAction, icon:null) menuItem(historyNextAction, icon:null) } menu(text: 'Script', mnemonic: 'S') { menuItem(runAction, icon:null) menuItem(runSelectionAction, icon:null) menuItem(interruptAction, icon:null) menuItem(compileAction, icon:null) separator() menuItem(addClasspathJar) menuItem(addClasspathDir) menuItem(clearClassloader) separator() menuItem(inspectLastAction, icon:null) menuItem(inspectVariablesAction, icon:null) menuItem(inspectAstAction, icon:null) } } groovy-1.8.6/src/main/groovy/ui/view/Defaults.groovy0000644001501200150120000000521411627206700022041 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import groovy.ui.text.GroovyFilter import java.awt.Color import javax.swing.text.StyleConstants import javax.swing.text.StyleContext menuBarClass = groovy.ui.view.BasicMenuBar contentPaneClass = groovy.ui.view.BasicContentPane toolBarClass = groovy.ui.view.BasicToolBar statusBarClass = groovy.ui.view.BasicStatusBar styles = [ // output window styles regular: [ (StyleConstants.FontFamily): 'Monospaced' ], prompt: [ (StyleConstants.Foreground): new Color(0, 128, 0) ], command: [ (StyleConstants.Foreground): Color.BLUE ], stacktrace: [ (StyleConstants.Foreground): Color.RED.darker() ], hyperlink: [ (StyleConstants.Foreground): Color.BLUE, (StyleConstants.Underline): true ], output: [:], result: [ (StyleConstants.Foreground): Color.BLUE, (StyleConstants.Background): Color.YELLOW ], // syntax highlighting styles (StyleContext.DEFAULT_STYLE) : [ (StyleConstants.FontFamily): 'Monospaced' ], (GroovyFilter.COMMENT): [ (StyleConstants.Foreground): Color.LIGHT_GRAY.darker().darker(), (StyleConstants.Italic) : true ], (GroovyFilter.QUOTES): [ (StyleConstants.Foreground): Color.MAGENTA.darker().darker() ], (GroovyFilter.SINGLE_QUOTES): [ (StyleConstants.Foreground): Color.GREEN.darker().darker() ], (GroovyFilter.SLASHY_QUOTES): [ (StyleConstants.Foreground): Color.ORANGE.darker() ], (GroovyFilter.DIGIT): [ (StyleConstants.Foreground): Color.RED.darker() ], (GroovyFilter.OPERATION): [ (StyleConstants.Bold): true ], (GroovyFilter.IDENT): [:], (GroovyFilter.RESERVED_WORD): [ (StyleConstants.Bold): true, (StyleConstants.Foreground): Color.BLUE.darker().darker() ] ] groovy-1.8.6/src/main/groovy/ui/view/GTKDefaults.groovy0000644001501200150120000000475711707612044022423 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import javax.swing.JComponent import javax.swing.text.StyleConstants import javax.swing.text.StyleContext import org.codehaus.groovy.runtime.InvokerHelper build(Defaults) // change font to DejaVu Sans Mono, much clearer styles.regular[StyleConstants.FontFamily] = 'DejaVu Sans Mono' styles[StyleContext.DEFAULT_STYLE][StyleConstants.FontFamily] = 'DejaVu Sans Mono' // possibly change look and feel if (System.properties['java.version'] =~ /^1\.5/) { // GTK wasn't where it needed to be in 1.5, especially with toolbars // use metal instead lookAndFeel('metal', boldFonts:false) // we also need to turn on anti-aliasing ourselves key = InvokerHelper.getProperty('com.sun.java.swing.SwingUtilities2' as Class, 'AA_TEXT_PROPERTY_KEY') addAttributeDelegate {builder, node, attributes -> if (node instanceof JComponent) { node.putClientProperty(key, new Boolean(true)); } } } // some current distros (Ubuntu 7.10) have broken printing support :( // detect it and disable it try { pj = java.awt.print.PrinterJob.getPrinterJob() ps = pj.getPrintService() ps.getAttributes() docFlav = (ps.getSupportedDocFlavors() as List).find {it.mimeType == 'application/vnd.cups-postscript' } attrset = ps.getAttributes() orient = attrset.get(javax.print.attribute.standard.OrientationRequested) ?: ps.getDefaultAttributeValue(javax.print.attribute.standard.OrientationRequested) ps.isAttributeValueSupported(orient, docFlav, attrset) } catch (NullPointerException npe) { //print will bomb out... replace with disabled print action printAction = action( name: 'Print...', closure: controller.&print, mnemonic: 'P', accelerator: shortcut('P'), shortDescription: 'Printing does not work in Java with this version of CUPS', enabled: false ) } groovy-1.8.6/src/main/groovy/ui/view/BasicToolBar.groovy0000644001501200150120000000310511627206700022573 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import javax.swing.SwingConstants import java.awt.BorderLayout toolbar = toolBar(rollover:true, visible:controller.showToolbar, constraints:BorderLayout.NORTH) { button(newFileAction, text:null) button(openAction, text:null) button(saveAction, text:null) separator(orientation:SwingConstants.VERTICAL) button(undoAction, text:null) button(redoAction, text:null) separator(orientation:SwingConstants.VERTICAL) button(cutAction, text:null) button(copyAction, text:null) button(pasteAction, text:null) separator(orientation:SwingConstants.VERTICAL) button(findAction, text:null) button(replaceAction, text:null) separator(orientation:SwingConstants.VERTICAL) button(historyPrevAction, text:null) button(historyNextAction, text:null) separator(orientation:SwingConstants.VERTICAL) button(runAction, text:null) button(interruptAction, text:null) } groovy-1.8.6/src/main/groovy/ui/view/WindowsDefaults.groovy0000644001501200150120000000303111707612044023410 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import javax.swing.JComponent import javax.swing.text.StyleConstants import javax.swing.text.StyleContext import org.codehaus.groovy.runtime.InvokerHelper build(Defaults) // change fonts for vista if (System.properties['os.version'] =~ /6\./) { // Vista/Server 2008 or later styles.regular[StyleConstants.FontFamily] = 'Consolas' styles[StyleContext.DEFAULT_STYLE][StyleConstants.FontFamily] = 'Consolas' // in JDK 1.5 we need to turn on anti-aliasing so consoles looks better if (System.properties['java.version'] =~ /^1\.5/) { key = InvokerHelper.getProperty('com.sun.java.swing.SwingUtilities2' as Class, 'AA_TEXT_PROPERTY_KEY') addAttributeDelegate {builder, node, attributes -> if (node instanceof JComponent) { node.putClientProperty(key, new Boolean(true)); } } } } groovy-1.8.6/src/main/groovy/ui/view/BasicContentPane.groovy0000644001501200150120000001207311627206700023453 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import groovy.ui.ConsoleTextEditor import groovy.ui.Console import java.awt.* import java.awt.image.BufferedImage import static javax.swing.JSplitPane.VERTICAL_SPLIT import javax.swing.text.Style import javax.swing.text.StyleContext import javax.swing.text.StyledDocument import java.util.prefs.Preferences import javax.swing.text.StyleConstants import javax.swing.WindowConstants import javax.swing.JSplitPane def prefs = Preferences.userNodeForPackage(Console) def detachedOutputFlag = prefs.getBoolean("detachedOutput", false) outputWindow = frame(visible:false, defaultCloseOperation: WindowConstants.HIDE_ON_CLOSE) { blank = glue() blank.preferredSize = [0, 0] as Dimension } splitPane = splitPane(resizeWeight: 0.5, orientation: VERTICAL_SPLIT) { inputEditor = widget(new ConsoleTextEditor(), border:emptyBorder(0)) buildOutputArea(prefs) } private def buildOutputArea(prefs) { scrollArea = scrollPane(border: emptyBorder(0)) { outputArea = textPane( editable: false, name: "outputArea", contentType: "text/html", background: new Color(255, 255, 218), font: new Font("Monospaced", Font.PLAIN, prefs.getInt("fontSize", 12)), border: emptyBorder(4) ) } } inputArea = inputEditor.textEditor // attach ctrl-enter to input area // need to wrap in actions to keep it from being added as a component actions { container(inputArea, name: "inputArea", font:new Font("Monospaced", Font.PLAIN, prefs.getInt("fontSize", 12)), border:emptyBorder(4)) { action(runAction) action(runSelectionAction) action(showOutputWindowAction) } container(outputArea, name: "outputArea") { action(hideOutputWindowAction1) action(hideOutputWindowAction2) action(hideOutputWindowAction3) action(hideOutputWindowAction4) } } // add styles to the output area, should this be moved into SwingBuilder somehow? outputArea.font = new Font("Monospaced", outputArea.font.style, outputArea.font.size) StyledDocument doc = outputArea.styledDocument Style defStyle = StyleContext.defaultStyleContext.getStyle(StyleContext.DEFAULT_STYLE) def applyStyle = {Style style, values -> values.each{k, v -> style.addAttribute(k, v)}} Style regular = doc.addStyle("regular", defStyle) applyStyle(regular, styles.regular) promptStyle = doc.addStyle("prompt", regular) applyStyle(promptStyle, styles.prompt) commandStyle = doc.addStyle("command", regular) applyStyle(commandStyle, styles.command) outputStyle = doc.addStyle("output", regular) applyStyle(outputStyle, styles.output) resultStyle = doc.addStyle("result", regular) applyStyle(resultStyle, styles.result) stacktraceStyle = doc.addStyle("stacktrace", regular) applyStyle(stacktraceStyle, styles.stacktrace) hyperlinkStyle = doc.addStyle("hyperlink", regular) applyStyle(hyperlinkStyle, styles.hyperlink) // redo styles for editor doc = inputArea.styledDocument StyleContext styleContext = StyleContext.defaultStyleContext styles.each {styleName, defs -> Style style = styleContext.getStyle(styleName) if (style) { applyStyle(style, defs) String family = defs[StyleConstants.FontFamily] if (style.name == 'default' && family) { inputEditor.defaultFamily = family inputArea.font = new Font(family, Font.PLAIN, inputArea.font.size) } } } // set the preferred size of the input and output areas // this is a good enough solution, there are margins and scrollbars and such to worry about for 80x12x2 Graphics g = GraphicsEnvironment.localGraphicsEnvironment.createGraphics (new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB)) FontMetrics fm = g.getFontMetrics(outputArea.font) outputArea.preferredSize = [ prefs.getInt("outputAreaWidth", fm.charWidth(0x77) * 81), prefs.getInt("outputAreaHeight", (fm.getHeight() + fm.leading) * 12) ] as Dimension inputEditor.preferredSize = [ prefs.getInt("inputAreaWidth", fm.charWidth(0x77) * 81), prefs.getInt("inputAreaHeight", (fm.getHeight() + fm.leading) * 12) ] as Dimension origDividerSize = -1 if (detachedOutputFlag) { splitPane.add(blank, JSplitPane.BOTTOM) origDividerSize = splitPane.dividerSize splitPane.dividerSize = 0 splitPane.resizeWeight = 1.0 outputWindow.add(scrollArea, BorderLayout.CENTER) } groovy-1.8.6/src/main/groovy/ui/view/MacOSXDefaults.groovy0000644001501200150120000000503511627206700023055 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.view import groovy.ui.text.GroovyFilter import java.awt.Color import javax.swing.text.StyleConstants build(Defaults) // menu bar tweaks System.setProperty("apple.laf.useScreenMenuBar", "true") System.setProperty("com.apple.mrj.application.apple.menu.about.name", "GroovyConsole") // redo output styles styles = [ // output window styles regular: [ (StyleConstants.FontFamily): "Monaco" ], prompt: [ (StyleConstants.Foreground): Color.LIGHT_GRAY ], command: [ (StyleConstants.Foreground): Color.GRAY ], stacktrace: [ (StyleConstants.Foreground): Color.RED.darker() ], hyperlink: [ (StyleConstants.Foreground): Color.BLUE, (StyleConstants.Underline): true ], output: [:], result: [ (StyleConstants.Foreground): Color.WHITE, (StyleConstants.Background): Color.BLACK ], // syntax highlighting styles (GroovyFilter.COMMENT): [ (StyleConstants.Foreground): Color.LIGHT_GRAY.darker().darker(), (StyleConstants.Italic) : true ], (GroovyFilter.QUOTES): [ (StyleConstants.Foreground): Color.MAGENTA.darker().darker() ], (GroovyFilter.SINGLE_QUOTES): [ (StyleConstants.Foreground): Color.GREEN.darker().darker() ], (GroovyFilter.SLASHY_QUOTES): [ (StyleConstants.Foreground): Color.ORANGE.darker() ], (GroovyFilter.DIGIT): [ (StyleConstants.Foreground): Color.RED.darker() ], (GroovyFilter.OPERATION): [ (StyleConstants.Bold): true ], (GroovyFilter.IDENT): [:], (GroovyFilter.RESERVED_WORD): [ (StyleConstants.Bold): true, (StyleConstants.Foreground): Color.BLUE.darker().darker() ] ] menuBarClass = MacOSXMenuBargroovy-1.8.6/src/main/groovy/ui/SystemOutputInterceptor.java0000644001501200150120000000576011707612044023647 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui; import groovy.lang.Closure; import java.io.FilterOutputStream; import java.io.IOException; import java.io.PrintStream; /** * Intercepts System.out/System.err. Implementation helper for Console.groovy. * * @version $Id$ */ public class SystemOutputInterceptor extends FilterOutputStream { private Closure callback; private boolean output; /** * Constructor * * @param callback accepts a string to be sent to std out and returns a Boolean. * If the return value is true, output will be sent to * System.out, otherwise it will not. */ public SystemOutputInterceptor(final Closure callback) { this(callback, true); } /** * Constructor * * @param callback accepts a string to be sent to std out and returns a Boolean. * If the return value is true, output will be sent to * System.out/System.err, otherwise it will not. * @param output flag that tells whether System.out needs capturing ot System.err */ public SystemOutputInterceptor(final Closure callback, boolean output) { super(output ? System.out : System.err); assert callback != null; this.callback = callback; this.output = output; } /** * Starts intercepting System.out/System.err */ public void start() { if (output) { System.setOut(new PrintStream(this)); } else { System.setErr(new PrintStream(this)); } } /** * Stops intercepting System.out/System.err, sending output to wherever it was * going when this interceptor was created. */ public void stop() { if (output) { System.setOut((PrintStream) out); } else { System.setErr((PrintStream) out); } } /** * Intercepts output - moret common case of byte[] */ public void write(byte[] b, int off, int len) throws IOException { Boolean result = (Boolean) callback.call(new String(b, off, len)); if (result) { out.write(b, off, len); } } /** * Intercepts output - single characters */ public void write(int b) throws IOException { Boolean result = (Boolean) callback.call(String.valueOf((char) b)); if (result) { out.write(b); } } } groovy-1.8.6/src/main/groovy/ui/ConsoleView.groovy0000644001501200150120000001167711707612044021570 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import groovy.ui.view.Defaults import groovy.ui.view.GTKDefaults import groovy.ui.view.MacOSXDefaults import groovy.ui.view.WindowsDefaults import java.awt.datatransfer.DataFlavor import java.awt.dnd.* import javax.swing.UIManager import javax.swing.event.DocumentListener switch (UIManager.getSystemLookAndFeelClassName()) { case 'com.sun.java.swing.plaf.windows.WindowsLookAndFeel': case 'com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel': build(WindowsDefaults) break case 'apple.laf.AquaLookAndFeel': case 'com.apple.laf.AquaLookAndFeel': build(MacOSXDefaults) break case 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel': build(GTKDefaults) break default: build(Defaults) break } binding.rootContainerDelegate.delegate = this consoleFrame = binding['rootContainerDelegate']() container(consoleFrame) { binding.menuBarDelegate.delegate = delegate binding['menuBarDelegate'](menuBarClass) build(contentPaneClass) build(toolBarClass) build(statusBarClass) } controller.promptStyle = promptStyle controller.commandStyle = commandStyle controller.outputStyle = outputStyle controller.stacktraceStyle = stacktraceStyle controller.hyperlinkStyle = hyperlinkStyle controller.resultStyle = resultStyle // add the window close handler if (consoleFrame instanceof java.awt.Window) { consoleFrame.windowClosing = controller.&exit } // link in references to the controller controller.inputEditor = inputEditor controller.inputArea = inputEditor.textEditor controller.outputArea = outputArea controller.outputWindow = outputWindow controller.statusLabel = status controller.frame = consoleFrame controller.rowNumAndColNum = rowNumAndColNum controller.toolbar = toolbar // link actions controller.saveAction = saveAction controller.prevHistoryAction = historyPrevAction controller.nextHistoryAction = historyNextAction controller.fullStackTracesAction = fullStackTracesAction controller.showToolbarAction = showToolbarAction controller.detachedOutputAction = detachedOutputAction controller.autoClearOutputAction = autoClearOutputAction controller.threadInterruptAction = threadInterruptAction controller.showOutputWindowAction = showOutputWindowAction controller.hideOutputWindowAction1 = hideOutputWindowAction1 controller.hideOutputWindowAction2 = hideOutputWindowAction2 controller.hideOutputWindowAction3 = hideOutputWindowAction3 controller.hideOutputWindowAction4 = hideOutputWindowAction4 controller.interruptAction = interruptAction controller.origDividerSize = origDividerSize controller.splitPane = splitPane controller.blank = blank controller.scrollArea = scrollArea // some more UI linkage controller.outputArea.addComponentListener(controller) controller.inputArea.addComponentListener(controller) controller.outputArea.addHyperlinkListener(controller) controller.outputArea.addHyperlinkListener(controller) controller.outputArea.addFocusListener(controller) controller.inputArea.addCaretListener(controller) controller.inputArea.document.addDocumentListener({ controller.setDirty(true) } as DocumentListener) controller.rootElement = inputArea.document.defaultRootElement def dtListener = [ dragEnter:{DropTargetDragEvent evt -> if (evt.dropTargetContext.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { evt.acceptDrag(DnDConstants.ACTION_COPY) } else { evt.rejectDrag() } }, dragOver:{DropTargetDragEvent evt -> //dragEnter(evt) }, dropActionChanged:{DropTargetDragEvent evt -> //dragEnter(evt) }, dragExit:{DropTargetEvent evt -> }, drop:{DropTargetDropEvent evt -> evt.acceptDrop DnDConstants.ACTION_COPY //println "Dropping! ${evt.transferable.getTransferData(DataFlavor.javaFileListFlavor)}" if (controller.askToSaveFile()) { controller.loadScriptFile(evt.transferable.getTransferData(DataFlavor.javaFileListFlavor)[0]) } }, ] as DropTargetListener [consoleFrame, inputArea, outputArea].each { new DropTarget(it, DnDConstants.ACTION_COPY, dtListener) } // don't send any return value from the view, all items should be referenced via the bindings return null groovy-1.8.6/src/main/groovy/ui/OutputTransforms.groovy0000644001501200150120000000641711627206700022705 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import java.awt.* import java.awt.image.BufferedImage import javax.swing.Icon import javax.swing.ImageIcon import org.codehaus.groovy.runtime.InvokerHelper public class OutputTransforms { @Lazy static def localTransforms = loadOutputTransforms() static def loadOutputTransforms() { def transforms = [] // // load user local transforms // def userHome = new File(System.getProperty('user.home')) def groovyDir = new File(userHome, '.groovy') def userTransforms = new File(groovyDir, "OutputTransforms.groovy") if (userTransforms.exists()) { GroovyShell shell = new GroovyShell() shell.setVariable('transforms', transforms) shell.evaluate(userTransforms) } // // built-in transforms // // any non-window GUI components, such as a heavyweight button or a // Swing component, gets passed if it has no parent set (the parent // clause is to keep buttons from disappearing from user shown forms) transforms << { it -> if ((it instanceof Component) && !(it instanceof Window) && (it.parent == null)) it } // remaining components get printed to an image transforms << { it -> if (it instanceof javax.swing.JComponent) { Dimension d = it.size if (d.width == 0) { d = it.preferredSize it.size = d } GraphicsEnvironment ge = GraphicsEnvironment.localGraphicsEnvironment GraphicsDevice gs = ge.defaultScreenDevice GraphicsConfiguration gc = gs.defaultConfiguration BufferedImage image = gc.createCompatibleImage(d.width as int, d.height as int, Transparency.TRANSLUCENT) Graphics2D g2 = image.createGraphics() it.print(g2) g2.dispose() new ImageIcon(image) } } // icons get passed, they can be rendered multiple times so no parent check transforms << { it -> if (it instanceof Icon) it } // Images become ImageIcons transforms << { it -> if (it instanceof Image) new ImageIcon(it)} // final case, non-nulls just get inspected as strings transforms << { it -> if (it != null) "${InvokerHelper.inspect(it)}" } return transforms } static def transformResult(def base, def transforms = localTransforms) { for (Closure c : transforms) { def result = c(base as Object) if (result != null) { return result } } return base } } groovy-1.8.6/src/main/groovy/ui/ConsoleIvyPlugin.groovy0000644001501200150120000000442411627206700022573 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import groovy.grape.GrapeIvy import groovy.grape.Grape import org.apache.ivy.core.event.resolve.StartResolveEvent import org.apache.ivy.core.event.download.PrepareDownloadEvent import org.apache.ivy.core.event.IvyListener /** * Groovy Swing console. * * Adds Groovy Grape feedback (via an Ivy listener). * * @author Guillaume Laforge * @author Paul King */ class ConsoleIvyPlugin { Console savedConsole Set resolvedDependencies = [] Set downloadedArtifacts = [] def addListener(Console console) { savedConsole = console ((GrapeIvy) Grape.instance).ivyInstance.eventManager.addIvyListener([progress: { ivyEvent -> switch (ivyEvent) { case StartResolveEvent: ivyEvent.moduleDescriptor.dependencies.each { it -> def name = it.toString() if (!resolvedDependencies.contains(name)) { resolvedDependencies << name savedConsole.showMessage "Resolving ${name} ..." } } break case PrepareDownloadEvent: ivyEvent.artifacts.each { it -> def name = it.toString() if (!downloadedArtifacts.contains(name)) { downloadedArtifacts << name savedConsole.showMessage "Downloading artifact ${name} ..." } } break } }] as IvyListener) } } groovy-1.8.6/src/main/groovy/ui/GroovySocketServer.java0000644001501200150120000001541611707612044022547 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui; import groovy.lang.GroovyShell; import groovy.lang.Script; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import org.codehaus.groovy.runtime.DefaultGroovyMethods; /** * Simple server that executes supplied script against a socket.

    * * Typically this is used from the groovy command line agent but it can be * invoked programatically. To run this program from the command line please * refer to the command line documentation at * Groovy CLI.

    * * Here is an example of how to use this class to open a listening socket on the server, * listen for incoming data, and then echo the data back to the client in reverse order: *
     * new GroovySocketServer(
     *         new GroovyShell(),      // evaluator
     *         false,                  // is not a file
     *         "println line.reverse()",         // script to evaluate
     *         true,                   // return result to client
     *         1960)                   //port
     * 
    * There are several variables in the script binding:
    *
      *
    • line - The data from the socket
    • *
    • out - The output PrintWriter, should you need it for some reason.
    • *
    • socket - The socket, should you need it for some reason.
    • *
    * * @version $Id$ * @author Jeremy Rayner */ public class GroovySocketServer implements Runnable { private URL url; private GroovyShell groovy; private boolean isScriptFile; private String scriptFilenameOrText; private boolean autoOutput; /** * This creates and starts the socket server on a new Thread. There is no need to call run or spawn * a new thread yourself. * @param groovy * The GroovyShell object that evaluates the incoming text. If you need additional classes in the * classloader then configure that through this object. * @param isScriptFile * Whether the incoming socket data String will be a script or a file path. * @param scriptFilenameOrText * This will be a groovy script or a file location depending on the argument isScriptFile. * @param autoOutput * whether output should be automatically echoed back to the client * @param port * the port to listen on * */ public GroovySocketServer(GroovyShell groovy, boolean isScriptFile, String scriptFilenameOrText, boolean autoOutput, int port) { this.groovy = groovy; this.isScriptFile = isScriptFile; this.scriptFilenameOrText = scriptFilenameOrText; this.autoOutput = autoOutput; try { url = new URL("http", InetAddress.getLocalHost().getHostAddress(), port, "/"); System.out.println("groovy is listening on port " + port); } catch (IOException e) { e.printStackTrace(); } new Thread(this).start(); } /** * Runs this server. There is typically no need to call this method, as the object's constructor * creates a new thread and runs this object automatically. */ public void run() { try { ServerSocket serverSocket = new ServerSocket(url.getPort()); while (true) { // Create one script per socket connection. // This is purposefully not caching the Script // so that the script source file can be changed on the fly, // as each connection is made to the server. Script script; if (isScriptFile) { GroovyMain gm = new GroovyMain(); script = groovy.parse(gm.getText(scriptFilenameOrText)); } else { script = groovy.parse(scriptFilenameOrText); } new GroovyClientConnection(script, autoOutput, serverSocket.accept()); } } catch (Exception e) { e.printStackTrace(); } } class GroovyClientConnection implements Runnable { private Script script; private Socket socket; private BufferedReader reader; private PrintWriter writer; private boolean autoOutputFlag; GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException { this.script = script; this.autoOutputFlag = autoOutput; this.socket = socket; reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(socket.getOutputStream()); new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start(); } public void run() { try { String line = null; script.setProperty("out", writer); script.setProperty("socket", socket); script.setProperty("init", Boolean.TRUE); while ((line = reader.readLine()) != null) { // System.out.println(line); script.setProperty("line", line); Object o = script.run(); script.setProperty("init", Boolean.FALSE); if (o != null) { if ("success".equals(o)) { break; // to close sockets gracefully etc... } else { if (autoOutputFlag) { writer.println(o); } } } writer.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { try { writer.flush(); writer.close(); } finally { try { socket.close(); } catch (IOException e3) { e3.printStackTrace(); } } } } } } groovy-1.8.6/src/main/groovy/ui/InteractiveShell.properties0000644001501200150120000000420711627206700023435 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # # # CLI messages # cli.option.help.description=Display this help message cli.option.version.description=Display the version cli.info.unexpected_args=Unexpected arguments: {0} cli.info.version=Groovy Shell {0} # # Command messages # command.help.descripion=Displays this help text command.help.available_commands=Available commands: command.exit.descripion=Exit the shell command.discard.descripion=Discards the current statement buffer command.display.descripion=Displays the current statement buffer command.display.buffer_empty=The current buffer is empty. command.explain.descripion=Explains the parsing of the current statement buffer (currently disabled) command.explain.tree_header=Parse tree: command.explain.unparsable=The statement does not parse. command.execute.descripion=Executes the current statement buffer command.execute.not_complete=Statement is not complete. command.binding.descripion=Shows the binding used by the shell command.binding.binding_empty=The current binding is empty. command.binding.available_variables=Available variables: command.discardclasses.descripion=Discards all former unbound class definitions command.discardclasses.classdefs_discarded=All former unbound class definitions are discarded. command.inspect.descripion=Opens an object browser for the expression returned from previous 'go' command.inspect.no_result=Nothing to inspect (preceding 'go' missing?). # # Misc messages # startup_banner.0=Groovy Shell ({0}, JVM: {1}) startup_banner.1=Type 'go' to execute statements; Type 'help' for more information. groovy-1.8.6/src/main/groovy/ui/GroovyMain.java0000644001501200150120000004504211715031256021011 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovyShell; import groovy.lang.GroovySystem; import groovy.lang.MissingMethodException; import groovy.lang.Script; import java.io.*; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.InvokerInvocationException; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.StackTraceUtils; /** * A Command line to execute groovy. * * @author Jeremy Rayner * @author Yuri Schimke * @author Roshan Dawrani * @version $Revision$ */ public class GroovyMain { // arguments to the script private List args; // is this a file on disk private boolean isScriptFile; // filename or content of script private String script; // process args as input files private boolean processFiles; // edit input files in place private boolean editFiles; // automatically output the result of each script private boolean autoOutput; // automatically split each line using the splitpattern private boolean autoSplit; // The pattern used to split the current line private String splitPattern = " "; // process sockets private boolean processSockets; // port to listen on when processing sockets private int port; // backup input files with extension private String backupExtension; // do you want full stack traces in script exceptions? private boolean debug = false; // Compiler configuration, used to set the encodings of the scripts/classes private CompilerConfiguration conf = new CompilerConfiguration(System.getProperties()); /** * Main CLI interface. * * @param args all command line args. */ public static void main(String args[]) { processArgs(args, System.out); } // package-level visibility for testing purposes (just usage/errors at this stage) // TODO: should we have an 'err' printstream too for ParseException? static void processArgs(String[] args, final PrintStream out) { Options options = buildOptions(); try { CommandLine cmd = parseCommandLine(options, args); if (cmd.hasOption('h')) { printHelp(out, options); } else if (cmd.hasOption('v')) { String version = GroovySystem.getVersion(); out.println("Groovy Version: " + version + " JVM: " + System.getProperty("java.version") + " Vendor: " + System.getProperty("java.vm.vendor") + " OS: " + System.getProperty("os.name")); } else { // If we fail, then exit with an error so scripting frameworks can catch it // TODO: pass printstream(s) down through process if (!process(cmd)) { System.exit(1); } } } catch (ParseException pe) { out.println("error: " + pe.getMessage()); printHelp(out, options); } } private static void printHelp(PrintStream out, Options options) { HelpFormatter formatter = new HelpFormatter(); PrintWriter pw = new PrintWriter(out); formatter.printHelp( pw, 80, "groovy [options] [args]", "options:", options, 2, 4, null, // footer false); pw.flush(); } /** * Parse the command line. * * @param options the options parser. * @param args the command line args. * @return parsed command line. * @throws ParseException if there was a problem. */ private static CommandLine parseCommandLine(Options options, String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); return parser.parse(options, args, true); } /** * Build the options parser. Has to be synchronized because of the way Options are constructed. * * @return an options parser. */ @SuppressWarnings("static-access") private static synchronized Options buildOptions() { Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("path").withDescription("Specify where to find the class files - must be first argument").create("classpath")); options.addOption(OptionBuilder.withLongOpt("classpath").hasArg().withArgName("path").withDescription("Aliases for '-classpath'").create("cp")); options.addOption( OptionBuilder.withLongOpt("define"). withDescription("define a system property"). hasArg(true). withArgName("name=value"). create('D')); options.addOption( OptionBuilder.withLongOpt("disableopt"). withDescription("disables one or all optimization elements. " + "optlist can be a comma separated list with the elements: " + "all (disables all optimizations), " + "int (disable any int based optimizations)"). hasArg(true). withArgName("optlist"). create()); options.addOption( OptionBuilder.hasArg(false) .withDescription("usage information") .withLongOpt("help") .create('h')); options.addOption( OptionBuilder.hasArg(false) .withDescription("debug mode will print out full stack traces") .withLongOpt("debug") .create('d')); options.addOption( OptionBuilder.hasArg(false) .withDescription("display the Groovy and JVM versions") .withLongOpt("version") .create('v')); options.addOption( OptionBuilder.withArgName("charset") .hasArg() .withDescription("specify the encoding of the files") .withLongOpt("encoding") .create('c')); options.addOption( OptionBuilder.withArgName("script") .hasArg() .withDescription("specify a command line script") .create('e')); options.addOption( OptionBuilder.withArgName("extension") .hasOptionalArg() .withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')") .create('i')); options.addOption( OptionBuilder.hasArg(false) .withDescription("process files line by line using implicit 'line' variable") .create('n')); options.addOption( OptionBuilder.hasArg(false) .withDescription("process files line by line and print result (see also -n)") .create('p')); options.addOption( OptionBuilder.withArgName("port") .hasOptionalArg() .withDescription("listen on a port and process inbound lines (default: 1960)") .create('l')); options.addOption( OptionBuilder.withArgName("splitPattern") .hasOptionalArg() .withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable") .withLongOpt("autosplit") .create('a')); return options; } private static void setSystemPropertyFrom(final String nameValue) { if(nameValue==null) throw new IllegalArgumentException("argument should not be null"); String name, value; int i = nameValue.indexOf("="); if (i == -1) { name = nameValue; value = Boolean.TRUE.toString(); } else { name = nameValue.substring(0, i); value = nameValue.substring(i + 1, nameValue.length()); } name = name.trim(); System.setProperty(name, value); } /** * Process the users request. * * @param line the parsed command line. * @throws ParseException if invalid options are chosen */ private static boolean process(CommandLine line) throws ParseException { List args = line.getArgList(); if (line.hasOption('D')) { String[] values = line.getOptionValues('D'); for (int i=0; i_FpiV*ό䷍2vʙwNt&TF"aMCA)B \LJۊTwa!Rsj?=_>8@}ܴhԾ:aN7Ao_lG61` B2 26J(7`zz奾wgGAҩ#"ڍfO<)0@J<:ן>h]H`5*ABOA))j}Kr)l32<ևػA mA) Xro@brИ݇) u7o5=t㻵мV8_?j_Hz5m{S;&NAT%`"F"D $)"dWӨD@\}ôg2Cc=>c2SmAz;*b@DRBYWE`ii'x􏟞Nfg ą 19i;?E@l#5p#gMg+f *wCCXzyWoc,6^BA@ATuxN9a /~ L"5pLSffTP1PҶO?au|Je l$) HpM`J)TKaZ VBik  8l]?a%~Yd6^7h By ǏAUCi6a9vҽnqC}y -H|QWjS+!$02IJʟH ZԝV Ft ]wD`P i`ʽ*q]oKJ$Ra h:a2144Ô< 2n Qh˗눢 Pjҿi2 #;L(p!AaZRR:LOQZld!k+nVj$ $ 2N(!`i i;ຒ F{cLV=o/lNxh!d;ny0zC2| N;*{^h _ )%X'Q9 HvԮ6gԻ~H"ֱni74mq4)P0hv .[)@vٷM3PZv1:tَ4%r`mE<{mJA )JתNs϶ZCK{*R`W_:%Qڗt}L ZǙQ(QX W"!TYVaL-"  !$bf%MƞyssYH)%_`RR@>f!\4%[Q~`攒-ksRXuRmQ&DJ>یЬXzŋgQE(GLrLn)|,sTքlzzI package groovy.ui.*

    An interactive command line terminal along with a Swing console for evaluating Groovy scripts.

    groovy-1.8.6/src/main/groovy/ui/ConsoleApplet.groovy0000644001501200150120000000165411627206700022074 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import javax.swing.JApplet /** * ConsoleApplet */ public class ConsoleApplet extends JApplet { Console console public void start() { console = new Console() console.run this } public void stop() { console.exit() } } groovy-1.8.6/src/main/groovy/ui/HistoryRecord.groovy0000644001501200150120000000215111627206700022115 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui class HistoryRecord { String allText int selectionStart int selectionEnd String scriptName Object result Throwable exception public String getTextToRun(boolean useSelection) { if (useSelection && selectionStart != selectionEnd) { return allText[selectionStart ..< selectionEnd] } return allText } public Object getValue() { return exception ? exception : result } } groovy-1.8.6/src/main/groovy/ui/icons/0000755001501200150120000000000011627206700017162 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/ui/icons/page_copy.png0000644001501200150120000000122711627206700021640 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<)IDAT8u=hTAlnvB0I%VAQJA0(Z`!N'Q ei$ƸwL3c332v|t& * jyTz6?5^CG^m 'gazaō77n=Pm`HOveK#y=fOcdHN'0 b2VX!1ln ' \D j3.>qkKENݯ_4K'S5 XcZ*JJ#~0[@jӲ^~1!'r/9J*5R0FC߹gM80L\y}|64d16dyb+ ek,M Z-IJ$RH#>:G (IJ'COo+UFR jZԨ5P镏w[YPKC(ʱvOPCӇ5uPA-sbPC, yGX'B]:bSuTkw<1yJO]o#gFqb#[^jܼRljRA+U,v?tJ:3Dz|/\:cq=R4 1*Qljvf L{SG3;1Ј.bc#61lIAKD"$X$ TDyUIޥwO69DBכY}o*>'o{t:& ﱋoGgpfS=3Og~jUiִe[ǫ;kҏxOT$4ls1 w}؝>``ʨ2*c*u˽=v̝* D)ke{Oy,0CB0(4;.ݓ3*J 4 PC%# 0C/$4 I2O!E6k3tGBT%`YCam)6Ӱl0C/щ*ER4\g ˲ZW7{谆$$|ṵu/ٮ+Jt(6 \O_ٿ눊>IENDB`groovy-1.8.6/src/main/groovy/ui/icons/bullet_green.png0000644001501200150120000000044711627206700022344 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8c?%a8첒W7[\]k`Df_УwI-6m6˫?g:/D`;[wz tior'_|efp~*^g(e1]OQU"D9єH#"IENDB`groovy-1.8.6/src/main/groovy/ui/icons/folder_page.png0000644001501200150120000000126011627206700022136 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<BIDATAUewahMQKًPFiU6ABZ6>d\YDdQBPi#N{={{Lp\ahΣhݻo?]}{ p??pÃ&2Ʀv|*8GTJZ |u1-o]Yeڅif'sgNp1ӵ D0A¬{yԢ޾~VD@J +Z։啗9n@MLkZ !jȅ֯-\1eSs~J-0eUlʖ?]:fhB U swv‰[d@ʤp ZjU睼p L9z)dk`Z6jB{ hE?\F~0_XŻ{lc^-e@&mesmt)Pԛō˯ #H-i s9@r|jGaB9ɶAdDOX}H ?i!<))IENDB`groovy-1.8.6/src/main/groovy/ui/icons/arrow_redo.png0000644001501200150120000000116111627206700022032 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥OHQ7Zcf9UԢت fdPlQ RȕnE"à6e-r#apd6Yc|lDe{yDQؿ<>3;uDٖ47KgAg)g$ujUO 2kp s܍ { t?<(7YՔLX]`$7id? w_3:*WrlNC/-좕B'{ u_a46ҽbߡE%D47;ٻƩ;8ˣ}>6[ӕS@*Z Qk>~͵hB\9uxZvYb J Cيٽ?BYvn&kft$,d9Zap\^ Y7 QJF 9=Q4 ؜Io SBpsI) Fv(@yՎވc\@ %% Z2h'@d(<|áaJuM@O⤁LGjd!X8Af 5J i K->w62ƾWH}:mP]XB0QX=ib_g=!Ftt…clrIENDB`groovy-1.8.6/src/main/groovy/ui/icons/find.png0000644001501200150120000000122311627206700020606 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<%IDAT8c?%4ydÞ'/XfƦ"ʀGviQTo@5 )%k;o47Y%u ZbVTyE,Xݣo6ةm=x)k?"eKZ帹yLe? '?e}KjmѹÓ .dfay 6\Vo]Z9մ6\K/bĬ` *YBc~Z: ola_[S1qIbR/*.?##;L@ : ]_@$e;@1/x%|W4 |F=c 9WA12 5zaN?(8SSQEQBZ(`‚?֎nx% P`_IU P,aj(X@K*п9}ce&R12hZu O)t(Ģn|J|:L4B]H id4A lWJ$e_^I6:ο9r\EIENDB`groovy-1.8.6/src/main/groovy/ui/icons/cut_red.png0000644001501200150120000000121211627206700021311 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8c?.=йnBI03vEf3Db'r"'Lb#U^.8Y&6Mǻai n^S)S6,9:yV h__sSb}>wՇ)&e@pƖsWHZЭ7^kZYMt lMskHNSl3t=7? jIS'24`3n'qXMdayVgHg4఍ћzAR3/8/]|5ԿB~7/VZ;iot꡻^hdrѧ6.҂' q(`5`$q[灊VkojآVN2Sڙc }lj]܌ lܽnrcпe}N`Lɠ+?TrIENDB`groovy-1.8.6/src/main/groovy/ui/icons/cut.png0000644001501200150120000000121011627206700020455 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8c?.5SˮzKGO̵ο,.W1޶;d"]wWEuVei-Cp-^}1[|nm{hg?67[1 ila}>:2΍鏍uivC;?Ҥ[6OD:ƹM/&}8\vN^|b:bq.k-RX$bq\7My| CgsQAT}%E$;z+ &M&j#EdLE)E&ԱjcDKCGW:.0a@f UM&kHТb(\ޞNOڷ*kNT x/?ݍp,2JQ Pwwrnܢ AQJdYZ?5I83IENDB`groovy-1.8.6/src/main/groovy/ui/icons/book_previous.png0000644001501200150120000000125011627206700022554 0ustar miguelmiguelPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<:IDAT8˥SMhSA^bJ5UL*&1URV(QAhznYVȉw>F) qnp.\1 \pEQܜv x \rk #)=wd8{o )Wd2lwu+6Z "W &Ei (K $2 0^  -Abr?T01 2YPiJ]*.dS1("@2dfG"{Pprre߂,~s eI3^}~y$ =#NrrlyiS/0 U+!\DH@@ ="K{Wfp\nGM]p866SG6mf"(%v5b 6fVVրrcΦݜ3.3f Ŧ }^XJ?ʽ'rlm耶EwdIENDB`groovy-1.8.6/src/main/groovy/ui/Console.groovy0000644001501200150120000012552411713765676020753 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui import groovy.inspect.swingui.ObjectBrowser import groovy.inspect.swingui.AstBrowser import groovy.swing.SwingBuilder import groovy.ui.text.FindReplaceUtility import java.awt.Component import java.awt.EventQueue import java.awt.Font import java.awt.Toolkit import java.awt.Window import java.awt.event.ActionEvent import java.awt.event.ComponentEvent import java.awt.event.ComponentListener import java.awt.event.FocusListener import java.awt.event.FocusEvent import java.util.prefs.Preferences import javax.swing.* import javax.swing.event.CaretEvent import javax.swing.event.CaretListener import javax.swing.event.HyperlinkListener import javax.swing.event.HyperlinkEvent import javax.swing.text.AttributeSet import javax.swing.text.Element import javax.swing.text.SimpleAttributeSet import javax.swing.text.Style import javax.swing.text.StyleConstants import javax.swing.text.html.HTML import javax.swing.filechooser.FileFilter import org.codehaus.groovy.runtime.StackTraceUtils import org.codehaus.groovy.control.ErrorCollector import org.codehaus.groovy.control.MultipleCompilationErrorsException import org.codehaus.groovy.control.messages.SyntaxErrorMessage import org.codehaus.groovy.syntax.SyntaxException import org.codehaus.groovy.control.messages.ExceptionMessage import java.awt.Dimension import java.awt.BorderLayout import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer import groovy.transform.ThreadInterrupt /** * Groovy Swing console. * * Allows user to interactively enter and execute Groovy. * * @version $Id$ * @author Danno Ferrin * @author Dierk Koenig, changed Layout, included Selection sensitivity, included ObjectBrowser * @author Alan Green more features: history, System.out capture, bind result to _ * @author Guillaume Laforge, stacktrace hyperlinking to the current script line * @author Hamlet D'Arcy, AST browser * @author Roshan Dawrani * @author Paul King */ class Console implements CaretListener, HyperlinkListener, ComponentListener, FocusListener { static final String DEFAULT_SCRIPT_NAME_START = "ConsoleScript" static private prefs = Preferences.userNodeForPackage(Console) // Whether or not std output should be captured to the console static boolean captureStdOut = prefs.getBoolean('captureStdOut', true) static boolean captureStdErr = prefs.getBoolean('captureStdErr', true) static consoleControllers = [] boolean fullStackTraces = prefs.getBoolean('fullStackTraces', Boolean.valueOf(System.getProperty("groovy.full.stacktrace", "false"))) Action fullStackTracesAction boolean showScriptInOutput = prefs.getBoolean('showScriptInOutput', true) Action showScriptInOutputAction boolean visualizeScriptResults = prefs.getBoolean('visualizeScriptResults', false) Action visualizeScriptResultsAction boolean showToolbar = prefs.getBoolean('showToolbar', true) Component toolbar Action showToolbarAction boolean detachedOutput = prefs.getBoolean('detachedOutput', false) Action detachedOutputAction Action showOutputWindowAction Action hideOutputWindowAction1 Action hideOutputWindowAction2 Action hideOutputWindowAction3 Action hideOutputWindowAction4 int origDividerSize Component outputWindow Component copyFromComponent Component blank Component scrollArea boolean autoClearOutput = prefs.getBoolean('autoClearOutput', false) Action autoClearOutputAction // Safer thread interruption boolean threadInterrupt = prefs.getBoolean('threadInterrupt', false) Action threadInterruptAction // Maximum size of history int maxHistory = 10 // Maximum number of characters to show on console at any time int maxOutputChars = System.getProperty('groovy.console.output.limit','20000') as int // UI SwingBuilder swing RootPaneContainer frame ConsoleTextEditor inputEditor JSplitPane splitPane JTextPane inputArea JTextPane outputArea JLabel statusLabel JLabel rowNumAndColNum // row info Element rootElement int cursorPos int rowNum int colNum // Styles for output area Style promptStyle Style commandStyle Style outputStyle Style stacktraceStyle Style hyperlinkStyle Style resultStyle // Internal history List history = [] int historyIndex = 1 // valid values are 0..history.length() HistoryRecord pendingRecord = new HistoryRecord( allText: "", selectionStart: 0, selectionEnd: 0) Action prevHistoryAction Action nextHistoryAction // Current editor state boolean dirty Action saveAction int textSelectionStart // keep track of selections in inputArea int textSelectionEnd def scriptFile File currentFileChooserDir = new File(Preferences.userNodeForPackage(Console).get('currentFileChooserDir', '.')) File currentClasspathJarDir = new File(Preferences.userNodeForPackage(Console).get('currentClasspathJarDir', '.')) File currentClasspathDir = new File(Preferences.userNodeForPackage(Console).get('currentClasspathDir', '.')) // Running scripts CompilerConfiguration config GroovyShell shell int scriptNameCounter = 0 SystemOutputInterceptor systemOutInterceptor SystemOutputInterceptor systemErrorInterceptor Thread runThread = null Closure beforeExecution Closure afterExecution public static String ICON_PATH = '/groovy/ui/ConsoleIcon.png' // used by ObjectBrowser and AST Viewer public static String NODE_ICON_PATH = '/groovy/ui/icons/bullet_green.png' // used by AST Viewer private static groovyFileFilter = new GroovyFileFilter() private boolean scriptRunning = false private boolean stackOverFlowError = false Action interruptAction static void main(args) { if (args.length == 1 && args[0] == '--help') { println '''usage: groovyConsole [options] [filename] options: --help This Help message -cp,-classpath,--classpath Specify classpath''' return } // allow the full stack traces to bubble up to the root logger java.util.logging.Logger.getLogger(StackTraceUtils.STACK_LOG_NAME).useParentHandlers = true //when starting via main set the look and feel to system UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); def console = new Console(Console.class.classLoader?.getRootLoader()) console.run() if (args.length == 1) console.loadScriptFile(args[0] as File) } Console() { this(new Binding()) } Console(Binding binding) { this(null, binding) } Console(ClassLoader parent) { this(parent, new Binding()) } Console(ClassLoader parent, Binding binding) { newScript(parent, binding); try { System.setProperty("groovy.full.stacktrace", System.getProperty("groovy.full.stacktrace", Boolean.toString(prefs.getBoolean('fullStackTraces', false)))) } catch (SecurityException se) { fullStackTracesAction.enabled = false; } consoleControllers += this // listen for Ivy events if Ivy is on the Classpath try { if (Class.forName('org.apache.ivy.core.event.IvyListener')) { def ivyPluginClass = Class.forName('groovy.ui.ConsoleIvyPlugin') ivyPluginClass.newInstance().addListener(this) } } catch(ClassNotFoundException ignore) { } binding.variables._outputTransforms = OutputTransforms.loadOutputTransforms() } void newScript(ClassLoader parent, Binding binding) { config = new CompilerConfiguration() if (threadInterrupt) config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt)) shell = new GroovyShell(parent, binding, config) } static def frameConsoleDelegates = [ rootContainerDelegate:{ frame( title: 'GroovyConsole', //location: [100,100], // in groovy 2.0 use platform default location iconImage: imageIcon("/groovy/ui/ConsoleIcon.png").image, defaultCloseOperation: JFrame.DO_NOTHING_ON_CLOSE, ) { try { current.locationByPlatform = true } catch (Exception e) { current.location = [100, 100] // for 1.4 compatibility } containingWindows += current } }, menuBarDelegate: {arg-> current.JMenuBar = build(arg)} ]; void run() { run(frameConsoleDelegates) } void run(JApplet applet) { run([ rootContainerDelegate:{ containingWindows += SwingUtilities.getRoot(applet.getParent()) applet }, menuBarDelegate: {arg-> current.JMenuBar = build(arg)} ]) } void run(Map defaults) { swing = new SwingBuilder() defaults.each{k, v -> swing[k] = v} // tweak what the stack traces filter out to be fairly broad System.setProperty("groovy.sanitized.stacktraces", """org.codehaus.groovy.runtime. org.codehaus.groovy. groovy.lang. gjdk.groovy.lang. sun. java.lang.reflect. java.lang.Thread groovy.ui.Console""") // add controller to the swingBuilder bindings swing.controller = this // create the actions swing.build(ConsoleActions) // create the view swing.build(ConsoleView) bindResults() // stitch some actions together swing.bind(source:swing.inputEditor.undoAction, sourceProperty:'enabled', target:swing.undoAction, targetProperty:'enabled') swing.bind(source:swing.inputEditor.redoAction, sourceProperty:'enabled', target:swing.redoAction, targetProperty:'enabled') if (swing.consoleFrame instanceof java.awt.Window) { swing.consoleFrame.pack() swing.consoleFrame.show() } installInterceptor() swing.doLater inputArea.&requestFocus } public void installInterceptor() { systemOutInterceptor = new SystemOutputInterceptor(this.¬ifySystemOut, true) systemOutInterceptor.start() systemErrorInterceptor = new SystemOutputInterceptor(this.¬ifySystemErr, false) systemErrorInterceptor.start() } void addToHistory(record) { history.add(record) // history.size here just retrieves method closure if (history.size() > maxHistory) { history.remove(0) } // history.size doesn't work here either historyIndex = history.size() updateHistoryActions() } // Ensure we don't have too much in console (takes too much memory) private ensureNoDocLengthOverflow(doc) { // if it is a case of stackOverFlowError, show the exception details from the front // as there is no point in showing the repeating details at the back int offset = stackOverFlowError ? maxOutputChars : 0 if (doc.length > maxOutputChars) { doc.remove(offset, doc.length - maxOutputChars) } } // Append a string to the output area void appendOutput(String text, AttributeSet style){ def doc = outputArea.styledDocument doc.insertString(doc.length, text, style) ensureNoDocLengthOverflow(doc) } void appendOutput(Window window, AttributeSet style) { appendOutput(window.toString(), style) } void appendOutput(Object object, AttributeSet style) { appendOutput(object.toString(), style) } void appendOutput(Component component, AttributeSet style) { SimpleAttributeSet sas = new SimpleAttributeSet(); sas.addAttribute(StyleConstants.NameAttribute, "component") StyleConstants.setComponent(sas, component) appendOutput(component.toString(), sas) } void appendOutput(Icon icon, AttributeSet style) { SimpleAttributeSet sas = new SimpleAttributeSet(); sas.addAttribute(StyleConstants.NameAttribute, "icon") StyleConstants.setIcon(sas, icon) appendOutput(icon.toString(), sas) } void appendStacktrace(text) { def doc = outputArea.styledDocument // split lines by new line separator def lines = text.split(/(\n|\r|\r\n|\u0085|\u2028|\u2029)/) // Java Identifier regex def ji = /([\p{Alnum}_\$][\p{Alnum}_\$]*)/ // stacktrace line regex def stacktracePattern = /\tat $ji(\.$ji)+\((($ji(\.(java|groovy))?):(\d+))\)/ lines.each { line -> int initialLength = doc.length def matcher = line =~ stacktracePattern def fileName = matcher.matches() ? matcher[0][-5] : "" if (fileName == scriptFile?.name || fileName.startsWith(DEFAULT_SCRIPT_NAME_START)) { def fileNameAndLineNumber = matcher[0][-6] def length = fileNameAndLineNumber.length() def index = line.indexOf(fileNameAndLineNumber) def style = hyperlinkStyle def hrefAttr = new SimpleAttributeSet() // don't pass a GString as it won't be coerced to String as addAttribute takes an Object hrefAttr.addAttribute(HTML.Attribute.HREF, "file://" + fileNameAndLineNumber) style.addAttribute(HTML.Tag.A, hrefAttr); doc.insertString(initialLength, line[0.. swing[k] = v} swing.controller = consoleController swing.build(ConsoleActions) swing.build(ConsoleView) installInterceptor() swing.consoleFrame.pack() swing.consoleFrame.show() swing.doLater swing.inputArea.&requestFocus } void fileOpen(EventObject evt = null) { def scriptName = selectFilename() if (scriptName != null) { loadScriptFile(scriptName) } } void loadScriptFile(File file) { swing.edt { inputArea.editable = false } swing.doOutside { try { consoleText = file.readLines().join('\n') scriptFile = file swing.edt { updateTitle() inputArea.document.remove 0, inputArea.document.length inputArea.document.insertString 0, consoleText, null setDirty(false) inputArea.caretPosition = 0 } } finally { swing.edt { inputArea.editable = true } // GROOVY-3684: focus away and then back to inputArea ensures caret blinks swing.doLater outputArea.&requestFocusInWindow swing.doLater inputArea.&requestFocusInWindow } } } // Save file - return false if user cancelled save boolean fileSave(EventObject evt = null) { if (scriptFile == null) { return fileSaveAs(evt) } else { scriptFile.write(inputArea.text) setDirty(false) return true } } // Save file - return false if user cancelled save boolean fileSaveAs(EventObject evt = null) { scriptFile = selectFilename("Save") if (scriptFile != null) { scriptFile.write(inputArea.text) setDirty(false) return true } else { return false } } def finishException(Throwable t, boolean executing) { if(executing) { statusLabel.text = 'Execution terminated with exception.' history[-1].exception = t } else { statusLabel.text = 'Compilation failed.' } if (t instanceof MultipleCompilationErrorsException) { MultipleCompilationErrorsException mcee = t ErrorCollector collector = mcee.errorCollector int count = collector.errorCount appendOutputNl("${count} compilation error${count > 1 ? 's' : ''}:\n\n", commandStyle) collector.errors.each { error -> if (error instanceof SyntaxErrorMessage) { SyntaxException se = error.cause int errorLine = se.line String message = se.originalMessage String scriptFileName = scriptFile?.name ?: DEFAULT_SCRIPT_NAME_START def doc = outputArea.styledDocument def style = hyperlinkStyle def hrefAttr = new SimpleAttributeSet() // don't pass a GString as it won't be coerced to String as addAttribute takes an Object hrefAttr.addAttribute(HTML.Attribute.HREF, "file://" + scriptFileName + ":" + errorLine) style.addAttribute(HTML.Tag.A, hrefAttr); doc.insertString(doc.length, message + " at ", stacktraceStyle) doc.insertString(doc.length, "line: ${se.line}, column: ${se.startColumn}\n\n", style) } else if (error instanceof Throwable) { reportException(error) } else if (error instanceof ExceptionMessage) { reportException(error.cause) } } } else { reportException(t) } if(!executing) { bindResults() } // GROOVY-4496: set the output window position to the top-left so the exception details are visible from the start outputArea.caretPosition = 0 if (detachedOutput) { prepareOutputWindow() showOutputWindow() } } private calcPreferredSize(a, b, c) { [c, [a, b].min()].max() } private reportException(Throwable t) { appendOutputNl("Exception thrown\n", commandStyle) StringWriter sw = new StringWriter() new PrintWriter(sw).withWriter {pw -> StackTraceUtils.deepSanitize(t).printStackTrace(pw) } appendStacktrace("\n${sw.buffer}\n") } def finishNormal(Object result) { // Take down the wait/cancel dialog history[-1].result = result if (result != null) { statusLabel.text = 'Execution complete.' appendOutputNl("Result: ", promptStyle) def obj = (visualizeScriptResults ? OutputTransforms.transformResult(result, shell.context._outputTransforms) : result.toString()) // multi-methods are magical! appendOutput(obj, resultStyle) } else { statusLabel.text = 'Execution complete. Result was null.' } bindResults() if (detachedOutput) { prepareOutputWindow() showOutputWindow() } } def compileFinishNormal() { statusLabel.text = 'Compilation complete.' } private def prepareOutputWindow() { outputArea.setPreferredSize(null) outputWindow.pack() outputArea.setPreferredSize([calcPreferredSize(outputWindow.getWidth(), inputEditor.getWidth(), 120), calcPreferredSize(outputWindow.getHeight(), inputEditor.getHeight(), 60)] as Dimension) outputWindow.pack() } // Gets the last, non-null result def getLastResult() { // runtime bugs in here history.reverse produces odd lookup // return history.reverse.find {it != null} if (!history) { return } for (i in (history.size() - 1)..0) { if (history[i].result != null) { return history[i].result } } return null } void historyNext(EventObject evt = null) { if (historyIndex < history.size()) { setInputTextFromHistory(historyIndex + 1) } else { statusLabel.text = "Can't go past end of history (time travel not allowed)" beep() } } void historyPrev(EventObject evt = null) { if (historyIndex > 0) { setInputTextFromHistory(historyIndex - 1) } else { statusLabel.text = "Can't go past start of history" beep() } } void inspectLast(EventObject evt = null){ if (null == lastResult) { JOptionPane.showMessageDialog(frame, "The last result is null.", "Cannot Inspect", JOptionPane.INFORMATION_MESSAGE) return } ObjectBrowser.inspect(lastResult) } void inspectVariables(EventObject evt = null) { ObjectBrowser.inspect(shell.context.variables) } void inspectAst(EventObject evt = null) { new AstBrowser(inputArea, rootElement, shell.getClassLoader()).run({ inputArea.getText() } ) } void largerFont(EventObject evt = null) { updateFontSize(inputArea.font.size + 2) } static boolean notifySystemOut(String str) { if (!captureStdOut) { // Output as normal return true } // Put onto GUI if (EventQueue.isDispatchThread()) { consoleControllers.each {it.appendOutputLines(str, it.outputStyle)} } else { SwingUtilities.invokeLater { consoleControllers.each {it.appendOutputLines(str, it.outputStyle)} } } return false } static boolean notifySystemErr(String str) { if (!captureStdErr) { // Output as normal return true } // Put onto GUI if (EventQueue.isDispatchThread()) { consoleControllers.each {it.appendStacktrace(str)} } else { SwingUtilities.invokeLater { consoleControllers.each {it.appendStacktrace(str)} } } return false } // actually run the script void runScript(EventObject evt = null) { runScriptImpl(false) } void runSelectedScript(EventObject evt = null) { runScriptImpl(true) } void addClasspathJar(EventObject evt = null) { def fc = new JFileChooser(currentClasspathJarDir) fc.fileSelectionMode = JFileChooser.FILES_ONLY fc.multiSelectionEnabled = true fc.acceptAllFileFilterUsed = true if (fc.showDialog(frame, "Add") == JFileChooser.APPROVE_OPTION) { currentClasspathJarDir = fc.currentDirectory Preferences.userNodeForPackage(Console).put('currentClasspathJarDir', currentClasspathJarDir.path) fc.selectedFiles?.each { file -> shell.getClassLoader().addURL(file.toURL()) } } } void addClasspathDir(EventObject evt = null) { def fc = new JFileChooser(currentClasspathDir) fc.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY fc.acceptAllFileFilterUsed = true if (fc.showDialog(frame, "Add") == JFileChooser.APPROVE_OPTION) { currentClasspathDir = fc.currentDirectory Preferences.userNodeForPackage(Console).put('currentClasspathDir', currentClasspathDir.path) shell.getClassLoader().addURL(fc.selectedFile.toURL()) } } void clearContext(EventObject evt = null) { def binding = new Binding() newScript(null, binding) // reload output transforms binding.variables._outputTransforms = OutputTransforms.loadOutputTransforms() } private void runScriptImpl(boolean selected) { if(scriptRunning) { statusLabel.text = 'Cannot run script now as a script is already running. Please wait or use "Interrupt Script" option.' return } scriptRunning = true interruptAction.enabled = true stackOverFlowError = false // reset this flag before running a script def endLine = System.getProperty('line.separator') def record = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'), selectionStart: textSelectionStart, selectionEnd: textSelectionEnd) addToHistory(record) pendingRecord = new HistoryRecord(allText:'', selectionStart:0, selectionEnd:0) if (prefs.getBoolean("autoClearOutput", false)) clearOutput() // Print the input text if (showScriptInOutput) { for (line in record.getTextToRun(selected).tokenize("\n")) { appendOutputNl('groovy> ', promptStyle) appendOutput(line, commandStyle) } appendOutputNl(" \n", promptStyle) } // Kick off a new thread to do the evaluation // Run in a thread outside of EDT, this method is usually called inside the EDT runThread = Thread.start { try { SwingUtilities.invokeLater { showExecutingMessage() } String name = scriptFile?.name ?: (DEFAULT_SCRIPT_NAME_START + scriptNameCounter++) if(beforeExecution) { beforeExecution() } def result = shell.run(record.getTextToRun(selected), name, []) if(afterExecution) { afterExecution() } SwingUtilities.invokeLater { finishNormal(result) } } catch (Throwable t) { if(t instanceof StackOverflowError) { // set the flag that will be used in printing exception details in output pane stackOverFlowError = true clearOutput() } SwingUtilities.invokeLater { finishException(t, true) } } finally { runThread = null scriptRunning = false interruptAction.enabled = false } } } void compileScript(EventObject evt = null) { if(scriptRunning) { statusLabel.text = 'Cannot compile script now as a script is already running. Please wait or use "Interrupt Script" option.' return } stackOverFlowError = false // reset this flag before running a script def endLine = System.getProperty('line.separator') def record = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'), selectionStart: textSelectionStart, selectionEnd: textSelectionEnd) if (prefs.getBoolean("autoClearOutput", false)) clearOutput() // Print the input text if (showScriptInOutput) { for (line in record.allText.tokenize("\n")) { appendOutputNl('groovy> ', promptStyle) appendOutput(line, commandStyle) } appendOutputNl(" \n", promptStyle) } // Kick off a new thread to do the compilation // Run in a thread outside of EDT, this method is usually called inside the EDT runThread = Thread.start { try { SwingUtilities.invokeLater { showCompilingMessage() } shell.parse(record.allText) SwingUtilities.invokeLater { compileFinishNormal() } } catch (Throwable t) { SwingUtilities.invokeLater { finishException(t, false) } } finally { runThread = null } } } def selectFilename(name = "Open") { def fc = new JFileChooser(currentFileChooserDir) fc.fileSelectionMode = JFileChooser.FILES_ONLY fc.acceptAllFileFilterUsed = true fc.fileFilter = groovyFileFilter if(name == "Save") { fc.selectedFile = new File("*.groovy") } if (fc.showDialog(frame, name) == JFileChooser.APPROVE_OPTION) { currentFileChooserDir = fc.currentDirectory Preferences.userNodeForPackage(Console).put('currentFileChooserDir', currentFileChooserDir.path) return fc.selectedFile } else { return null } } void setDirty(boolean newDirty) { //TODO when @BoundProperty is live, this should be handled via listeners dirty = newDirty saveAction.enabled = newDirty updateTitle() } private void setInputTextFromHistory(newIndex) { def endLine = System.getProperty('line.separator') if (historyIndex >= history.size()) { pendingRecord = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'), selectionStart: textSelectionStart, selectionEnd: textSelectionEnd) } historyIndex = newIndex def record if (historyIndex < history.size()) { record = history[historyIndex] statusLabel.text = "command history ${history.size() - historyIndex}" } else { record = pendingRecord statusLabel.text = 'at end of history' } inputArea.text = record.allText inputArea.selectionStart = record.selectionStart inputArea.selectionEnd = record.selectionEnd setDirty(true) // Should calculate dirty flag properly (hash last saved/read text in each file) updateHistoryActions() } private void updateHistoryActions() { nextHistoryAction.enabled = historyIndex < history.size() prevHistoryAction.enabled = historyIndex > 0 } // Adds a variable to the binding // Useful for adding variables before opening the console void setVariable(String name, Object value) { shell.context.setVariable(name, value) } void showAbout(EventObject evt = null) { def version = GroovySystem.getVersion() def pane = swing.optionPane() // work around GROOVY-1048 pane.setMessage('Welcome to the Groovy Console for evaluating Groovy scripts\nVersion ' + version) def dialog = pane.createDialog(frame, 'About GroovyConsole') dialog.show() } void find(EventObject evt = null) { FindReplaceUtility.showDialog() } void findNext(EventObject evt = null) { FindReplaceUtility.FIND_ACTION.actionPerformed(evt) } void findPrevious(EventObject evt = null) { def reverseEvt = new ActionEvent( evt.getSource(), evt.getID(), evt.getActionCommand(), evt.getWhen(), ActionEvent.SHIFT_MASK) //reverse FindReplaceUtility.FIND_ACTION.actionPerformed(reverseEvt) } void replace(EventObject evt = null) { FindReplaceUtility.showDialog(true) } void showMessage(String message) { statusLabel.text = message } void showExecutingMessage() { statusLabel.text = 'Script executing now. Please wait or use "Interrupt Script" option.' } void showCompilingMessage() { statusLabel.text = 'Script compiling now. Please wait.' } // Shows the detached 'outputArea' dialog void showOutputWindow(EventObject evt = null) { if (detachedOutput) { outputWindow.setLocationRelativeTo(frame) outputWindow.show() } } void hideOutputWindow(EventObject evt = null) { if (detachedOutput) { outputWindow.visible = false } } void hideAndClearOutputWindow(EventObject evt = null) { clearOutput() hideOutputWindow() } void smallerFont(EventObject evt = null){ updateFontSize(inputArea.font.size - 2) } void updateTitle() { if (frame.properties.containsKey('title')) { if (scriptFile != null) { frame.title = scriptFile.name + (dirty?" * ":"") + " - GroovyConsole" } else { frame.title = "GroovyConsole" } } } private updateFontSize(newFontSize) { if (newFontSize > 40) { newFontSize = 40 } else if (newFontSize < 4) { newFontSize = 4 } prefs.putInt("fontSize", newFontSize) // don't worry, the fonts won't be changed to this family, the styles will only derive from this def newFont = new Font(inputEditor.defaultFamily, Font.PLAIN, newFontSize) inputArea.font = newFont outputArea.font = newFont } void invokeTextAction(evt, closure, area = inputArea) { def source = evt.getSource() if (source != null) { closure(area) } } void cut(EventObject evt = null) { invokeTextAction(evt, { source -> source.cut() }) } void copy(EventObject evt = null) { invokeTextAction(evt, { source -> source.copy() }, copyFromComponent ?: inputArea) } void paste(EventObject evt = null) { invokeTextAction(evt, { source -> source.paste() }) } void selectAll(EventObject evt = null) { invokeTextAction(evt, { source -> source.selectAll() }) } void setRowNumAndColNum() { cursorPos = inputArea.getCaretPosition() rowNum = rootElement.getElementIndex(cursorPos) + 1 def rowElement = rootElement.getElement(rowNum - 1) colNum = cursorPos - rowElement.getStartOffset() + 1 rowNumAndColNum.setText("$rowNum:$colNum") } void print(EventObject evt = null) { inputEditor.printAction.actionPerformed(evt) } void undo(EventObject evt = null) { inputEditor.undoAction.actionPerformed(evt) } void redo(EventObject evt = null) { inputEditor.redoAction.actionPerformed(evt) } void hyperlinkUpdate(HyperlinkEvent e) { if (e.eventType == HyperlinkEvent.EventType.ACTIVATED) { // URL of the form: file://myscript.groovy:32 String url = e.getURL() int lineNumber = url[(url.lastIndexOf(':') + 1)..-1].toInteger() def editor = inputEditor.textEditor def text = editor.text int newlineBefore = 0 int newlineAfter = 0 int currentLineNumber = 1 // let's find the previous and next newline surrounding the offending line int i = 0 for (ch in text) { if (ch == '\n') { currentLineNumber++ } if (currentLineNumber == lineNumber) { newlineBefore = i def nextNewline = text.indexOf('\n', i + 1) newlineAfter = nextNewline > -1 ? nextNewline : text.length() break } i++ } // highlight / select the whole line editor.setCaretPosition(newlineBefore) editor.moveCaretPosition(newlineAfter) } } void componentHidden(ComponentEvent e) { } void componentMoved(ComponentEvent e) { } void componentResized(ComponentEvent e) { def component = e.getComponent() prefs.putInt("${component.name}Width", component.width) prefs.putInt("${component.name}Height", component.height) } public void componentShown(ComponentEvent e) { } public void focusGained(FocusEvent e) { // remember component with focus for text-copy functionality if (e.component == outputArea || e.component == inputArea) { copyFromComponent = e.component } } public void focusLost(FocusEvent e) { } } class GroovyFileFilter extends FileFilter { private static final GROOVY_SOURCE_EXTENSIONS = ['*.groovy', '*.gvy', '*.gy', '*.gsh', '*.story', '*.gpp', '*.grunit'] private static final GROOVY_SOURCE_EXT_DESC = GROOVY_SOURCE_EXTENSIONS.join(',') public boolean accept(File f) { if (f.isDirectory()) { return true } GROOVY_SOURCE_EXTENSIONS.find {it == getExtension(f)} ? true : false } public String getDescription() { "Groovy Source Files ($GROOVY_SOURCE_EXT_DESC)" } static String getExtension(f) { def ext = null; def s = f.getName() def i = s.lastIndexOf('.') if (i > 0 && i < s.length() - 1) { ext = s.substring(i).toLowerCase() } "*$ext" } } groovy-1.8.6/src/main/groovy/ui/ConsoleSupport.java0000644001501200150120000000501111627206700021706 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui; import groovy.lang.GroovyShell; import java.awt.Color; import javax.swing.JTextPane; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; /** * Base class for console * * @author James Strachan * @version $Revision$ */ public abstract class ConsoleSupport { Style promptStyle; Style commandStyle; Style outputStyle; private GroovyShell shell; int counter; protected void addStylesToDocument(JTextPane outputArea) { StyledDocument doc = outputArea.getStyledDocument(); Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE); Style regular = doc.addStyle("regular", def); StyleConstants.setFontFamily(def, "Monospaced"); promptStyle = doc.addStyle("prompt", regular); StyleConstants.setForeground(promptStyle, Color.BLUE); commandStyle = doc.addStyle("command", regular); StyleConstants.setForeground(commandStyle, Color.MAGENTA); outputStyle = doc.addStyle("output", regular); StyleConstants.setBold(outputStyle, true); } public Style getCommandStyle() { return commandStyle; } public Style getOutputStyle() { return outputStyle; } public Style getPromptStyle() { return promptStyle; } public GroovyShell getShell() { if (shell == null) { shell = new GroovyShell(); } return shell; } protected Object evaluate(String text) { String name = "Script" + counter++; try { return getShell().evaluate(text, name); } catch (Exception e) { handleException(text, e); return null; } } protected abstract void handleException(String text, Exception e); }groovy-1.8.6/src/main/groovy/ui/InteractiveShell.java0000644001501200150120000006537711715031256022201 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui; import groovy.lang.Binding; import groovy.lang.Closure; import groovy.lang.GroovyShell; import groovy.lang.GroovySystem; import org.codehaus.groovy.tools.shell.util.MessageSource; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.InvokerInvocationException; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.tools.ErrorReporter; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.HelpFormatter; import jline.ConsoleReader; import jline.SimpleCompletor; /** * A simple interactive shell for evaluating groovy expressions on the command line (aka. groovysh). * * @author James Strachan * @author Chris Poirier * @author Yuri Schimke * @author Brian McCallistair * @author Guillaume Laforge * @author Dierk Koenig, include the inspect command, June 2005 * @author Jason Dillon * * @version $Revision$ */ @Deprecated public class InteractiveShell implements Runnable { private static final String NEW_LINE = System.getProperty("line.separator"); private static final MessageSource MESSAGES = new MessageSource(InteractiveShell.class); private final GroovyShell shell; private final InputStream in; // FIXME: This doesn't really need to be a field, but hold on to it for now private final PrintStream out; private final PrintStream err; private final ConsoleReader reader; private Object lastResult; private Closure beforeExecution; private Closure afterExecution; /** * Entry point when called directly. */ public static void main(final String args[]) { try { processCommandLineArguments(args); final InteractiveShell groovy = new InteractiveShell(); groovy.run(); } catch (Exception e) { System.err.println("FATAL: " + e); e.printStackTrace(); System.exit(1); } System.exit(0); } /** * Process cli args when the shell is invoked via main(). * * @noinspection AccessStaticViaInstance */ private static void processCommandLineArguments(final String[] args) throws Exception { assert args != null; // // TODO: Let this take a single, optional argument which is a file or URL to run? // Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("help") .withDescription(MESSAGES.getMessage("cli.option.help.description")) .create('h')); options.addOption(OptionBuilder.withLongOpt("version") .withDescription(MESSAGES.getMessage("cli.option.version.description")) .create('V')); // // TODO: Add more options, maybe even add an option to prime the buffer from a URL or File? // // // FIXME: This does not currently barf on unsupported options short options, though it does for long ones. // Same problem with commons-cli 1.0 and 1.1 // CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args, true); String[] lineargs = line.getArgs(); // Puke if there were arguments, we don't support any right now if (lineargs.length != 0) { System.err.println(MESSAGES.format("cli.info.unexpected_args", new Object[] { DefaultGroovyMethods.join(lineargs, " ") })); System.exit(1); } PrintWriter writer = new PrintWriter(System.out); if (line.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( writer, 80, // width "groovysh [options]", "", options, 4, // left pad 4, // desc pad "", false); // auto usage writer.flush(); System.exit(0); } if (line.hasOption('V')) { writer.println(MESSAGES.format("cli.info.version", new Object[] { GroovySystem.getVersion() })); writer.flush(); System.exit(0); } } /** * Default constructor, initializes uses new binding and system streams. */ public InteractiveShell() throws IOException { this(System.in, System.out, System.err); } /** * Constructs a new InteractiveShell instance * * @param in The input stream to use * @param out The output stream to use * @param err The error stream to use */ public InteractiveShell(final InputStream in, final PrintStream out, final PrintStream err) throws IOException { this(null, new Binding(), in, out, err); } /** * Constructs a new InteractiveShell instance * * @param binding The binding instance * @param in The input stream to use * @param out The output stream to use * @param err The error stream to use */ public InteractiveShell(final Binding binding, final InputStream in, final PrintStream out, final PrintStream err) throws IOException { this(null, binding, in, out, err); } /** * Constructs a new InteractiveShell instance * * @param parent The parent ClassLoader * @param binding The binding instance * @param in The input stream to use * @param out The output stream to use * @param err The error stream to use */ public InteractiveShell(final ClassLoader parent, final Binding binding, final InputStream in, final PrintStream out, final PrintStream err) throws IOException { assert binding != null; assert in != null; assert out != null; assert err != null; this.in = in; this.out = out; this.err = err; // Initialize the JLine console input reader Writer writer = new OutputStreamWriter(out); reader = new ConsoleReader(in, writer); reader.setDefaultPrompt("groovy> "); // Add some completors to fancy things up reader.addCompletor(new CommandNameCompletor()); if (parent != null) { shell = new GroovyShell(parent, binding); } else { shell = new GroovyShell(binding); } // Add some default variables to the shell Map map = shell.getContext().getVariables(); // // FIXME: Um, is this right? Only set the "shell" var in the context if its set already? // if (map.get("shell") != null) { map.put("shell", shell); } } //--------------------------------------------------------------------------- // COMMAND LINE PROCESSING LOOP // // TODO: Add a general error display handler, and probably add a "ERROR: " prefix to the result for clarity ? // Maybe add one for WARNING's too? // /** * Reads commands and statements from input stream and processes them. */ public void run() { // Display the startup banner out.println(MESSAGES.format("startup_banner.0", new Object[] { GroovySystem.getVersion(), System.getProperty("java.version") })); out.println(MESSAGES.getMessage("startup_banner.1")); while (true) { // Read a code block to evaluate; this will deal with basic error handling final String code = read(); // If we got a null, then quit if (code == null) { break; } reset(); // Evaluate the code block if it was parsed if (code.length() > 0) { try { if (beforeExecution != null) { beforeExecution.call(); } lastResult = shell.evaluate(code); if (afterExecution != null) { afterExecution.call(); } // Shows the result of the evaluated code out.print("===> "); out.println(lastResult); } catch (CompilationFailedException e) { err.println(e); } catch (Throwable e) { // Unroll invoker exceptions if (e instanceof InvokerInvocationException) { e = e.getCause(); } filterAndPrintStackTrace(e); } } } } /** * A closure that is executed before the execution of a given script * * @param beforeExecution The closure to execute */ public void setBeforeExecution(final Closure beforeExecution) { this.beforeExecution = beforeExecution; } /** * A closure that is executed after the execution of the last script. The result of the * execution is passed as the first argument to the closure (the value of 'it') * * @param afterExecution The closure to execute */ public void setAfterExecution(final Closure afterExecution) { this.afterExecution = afterExecution; } /** * Filter stacktraces to show only relevant lines of the exception thrown. * * @param cause the throwable whose stacktrace needs to be filtered */ private void filterAndPrintStackTrace(final Throwable cause) { assert cause != null; // // TODO: Use message... // err.print("ERROR: "); err.println(cause); cause.printStackTrace(err); // // FIXME: What is the point of this? AFAICT, this just produces crappy/corrupt traces and is completely useless // // StackTraceElement[] stackTrace = e.getStackTrace(); // // for (int i = 0; i < stackTrace.length; i++) { // StackTraceElement element = stackTrace[i]; // String fileName = element.getFileName(); // // if ((fileName==null || (!fileName.endsWith(".java")) && (!element.getClassName().startsWith("gjdk")))) { // err.print("\tat "); // err.println(element); // } // } } //--------------------------------------------------------------------------- // COMMAND LINE PROCESSING MACHINERY /** The statement text accepted to date */ private StringBuffer accepted = new StringBuffer(); /** A line of statement text not yet accepted */ private String pending; // // FIXME: Doesn't look like 'line' is really used/needed anywhere... could drop it, or perhaps // could use it to update the prompt er something to show the buffer size? // /** The current line number */ private int line; /** Set to force clear of accepted */ private boolean stale = false; /** A SourceUnit used to check the statement */ private SourceUnit parser; /** Any actual syntax error caught during parsing */ private Exception error; /** * Resets the command-line processing machinery after use. */ protected void reset() { stale = true; pending = null; line = 1; parser = null; error = null; } // // FIXME: This Javadoc is not correct... read() will return the full code block read until "go" // /** * Reads a single statement from the command line. Also identifies * and processes command shell commands. Returns the command text * on success, or null when command processing is complete. * * NOTE: Changed, for now, to read until 'execute' is issued. At * 'execute', the statement must be complete. */ protected String read() { reset(); boolean complete = false; boolean done = false; while (/* !complete && */ !done) { // Read a line. If IOException or null, or command "exit", terminate processing. try { pending = reader.readLine(); } catch (IOException e) { // // FIXME: Shouldn't really eat this exception, may be something we need to see... ? // } // If result is null then we are shutting down if (pending == null) { return null; } // First up, try to process the line as a command and proceed accordingly // Trim what we have for use in command bits, so things like "help " actually show the help screen String command = pending.trim(); if (COMMAND_MAPPINGS.containsKey(command)) { int code = ((Integer)COMMAND_MAPPINGS.get(command)).intValue(); switch (code) { case COMMAND_ID_EXIT: return null; case COMMAND_ID_HELP: displayHelp(); break; case COMMAND_ID_DISCARD: reset(); done = true; break; case COMMAND_ID_DISPLAY: displayStatement(); break; case COMMAND_ID_EXPLAIN: explainStatement(); break; case COMMAND_ID_BINDING: displayBinding(); break; case COMMAND_ID_EXECUTE: if (complete) { done = true; } else { err.println(MESSAGES.getMessage("command.execute.not_complete")); } break; case COMMAND_ID_DISCARD_LOADED_CLASSES: resetLoadedClasses(); break; case COMMAND_ID_INSPECT: inspect(); break; default: throw new Error("BUG: Unknown command for code: " + code); } // Finished processing command bits, continue reading, don't need to process code continue; } // Otherwise, it's part of a statement. If it's just whitespace, // we'll just accept it and move on. Otherwise, parsing is attempted // on the accumulated statement text, and errors are reported. The // pending input is accepted or rejected based on that parsing. freshen(); if (pending.trim().length() == 0) { accept(); continue; } // Try to parse the current code buffer final String code = current(); if (parse(code)) { // Code parsed fine accept(); complete = true; } else if (error == null) { // Um... ??? accept(); } else { // Parse failed, spit out something to the user report(); } } // Get and return the statement. return accepted(complete); } private void inspect() { if (lastResult == null){ err.println(MESSAGES.getMessage("command.inspect.no_result")); return; } // // FIXME: Update this once we have joint compile happy in the core build? // // this should read: groovy.inspect.swingui.ObjectBrowser.inspect(lastResult) // but this doesn't compile since ObjectBrowser.groovy is compiled after this class. // // // FIXME: When launching this, if the user tries to "exit" and the window is still opened, the shell will // hang... not really nice user experience IMO. Should try to fix this if we can. // try { Class type = Class.forName("groovy.inspect.swingui.ObjectBrowser"); Method method = type.getMethod("inspect", new Class[]{ Object.class }); method.invoke(type, new Object[]{ lastResult }); } catch (Exception e) { err.println("Cannot invoke ObjectBrowser"); e.printStackTrace(); } } /** * Returns the accepted statement as a string. If not complete, returns empty string. */ private String accepted(final boolean complete) { if (complete) { return accepted.toString(); } return ""; } /** * Returns the current statement, including pending text. */ private String current() { return accepted.toString() + pending + NEW_LINE; } /** * Accepts the pending text into the statement. */ private void accept() { accepted.append(pending).append(NEW_LINE); line += 1; } /** * Clears accepted if stale. */ private void freshen() { if (stale) { accepted.setLength(0); stale = false; } } //--------------------------------------------------------------------------- // SUPPORT ROUTINES /** * Attempts to parse the specified code with the specified tolerance. * Updates the parser and error members * appropriately. Returns true if the text parsed, false otherwise. * The attempts to identify and suppress errors resulting from the * unfinished source text. */ private boolean parse(final String code, final int tolerance) { assert code != null; boolean parsed = false; parser = null; error = null; // Create the parser and attempt to parse the text as a top-level statement. try { parser = SourceUnit.create("groovysh-script", code, tolerance); parser.parse(); parsed = true; } // We report errors other than unexpected EOF to the user. catch (CompilationFailedException e) { if (parser.getErrorCollector().getErrorCount() > 1 || !parser.failedWithUnexpectedEOF()) { error = e; } } catch (Exception e) { error = e; } return parsed; } private boolean parse(final String code) { return parse(code, 1); } /** * Reports the last parsing error to the user. */ private void report() { err.println("Discarding invalid text:"); // TODO: i18n new ErrorReporter(error, false).write(err); } //----------------------------------------------------------------------- // COMMANDS // // TODO: Add a simple command to read in a File/URL into the buffer for execution, but need better command // support first (aka GShell) so we can allow commands to take args, etc. // private static final int COMMAND_ID_EXIT = 0; private static final int COMMAND_ID_HELP = 1; private static final int COMMAND_ID_DISCARD = 2; private static final int COMMAND_ID_DISPLAY = 3; private static final int COMMAND_ID_EXPLAIN = 4; private static final int COMMAND_ID_EXECUTE = 5; private static final int COMMAND_ID_BINDING = 6; private static final int COMMAND_ID_DISCARD_LOADED_CLASSES = 7; private static final int COMMAND_ID_INSPECT = 8; private static final int LAST_COMMAND_ID = 8; private static final String[] COMMANDS = { "exit", "help", "discard", "display", "explain", "execute", "binding", "discardclasses", "inspect" }; private static final Map COMMAND_MAPPINGS = new HashMap(); static { for (int i = 0; i <= LAST_COMMAND_ID; i++) { COMMAND_MAPPINGS.put(COMMANDS[i], i); } // A few synonyms COMMAND_MAPPINGS.put("quit", COMMAND_ID_EXIT); COMMAND_MAPPINGS.put("go", COMMAND_ID_EXECUTE); } private static final Map COMMAND_HELP = new HashMap(); static { COMMAND_HELP.put(COMMANDS[COMMAND_ID_EXIT], "exit/quit - " + MESSAGES.getMessage("command.exit.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_HELP], "help - " + MESSAGES.getMessage("command.help.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_DISCARD], "discard - " + MESSAGES.getMessage("command.discard.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_DISPLAY], "display - " + MESSAGES.getMessage("command.display.descripion")); // // FIXME: If this is disabled, then er comment it out, so it doesn't confuse the user // COMMAND_HELP.put(COMMANDS[COMMAND_ID_EXPLAIN], "explain - " + MESSAGES.getMessage("command.explain.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_EXECUTE], "execute/go - " + MESSAGES.getMessage("command.execute.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_BINDING], "binding - " + MESSAGES.getMessage("command.binding.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_DISCARD_LOADED_CLASSES], "discardclasses - " + MESSAGES.getMessage("command.discardclasses.descripion")); COMMAND_HELP.put(COMMANDS[COMMAND_ID_INSPECT], "inspect - " + MESSAGES.getMessage("command.inspect.descripion")); } /** * Displays help text about available commands. */ private void displayHelp() { out.println(MESSAGES.getMessage("command.help.available_commands")); for (int i = 0; i <= LAST_COMMAND_ID; i++) { out.print(" "); out.println(COMMAND_HELP.get(COMMANDS[i])); } } /** * Displays the accepted statement. */ private void displayStatement() { final String[] lines = accepted.toString().split(NEW_LINE); if (lines.length == 1 && lines[0].trim().equals("")) { out.println(MESSAGES.getMessage("command.display.buffer_empty")); } else { // Eh, try to pick a decent pad size... but don't try to hard int padsize = 2; if (lines.length >= 10) padsize++; if (lines.length >= 100) padsize++; if (lines.length >= 1000) padsize++; // Dump the current buffer with a line number prefix for (int i = 0; i < lines.length; i++) { // Normalize the field size of the line number String lineno = DefaultGroovyMethods.padLeft(String.valueOf(i + 1), padsize, " "); out.print(lineno); out.print("> "); out.println(lines[i]); } } } /** * Displays the current binding used when instantiating the shell. */ private void displayBinding() { Binding context = shell.getContext(); Map variables = context.getVariables(); Set set = variables.keySet(); if (set.isEmpty()) { out.println(MESSAGES.getMessage("command.binding.binding_empty")); } else { out.println(MESSAGES.getMessage("command.binding.available_variables")); for (Object key : set) { out.print(" "); out.print(key); out.print(" = "); out.println(variables.get(key)); } } } /** * Attempts to parse the accepted statement and display the parse tree for it. */ private void explainStatement() { if (parse(accepted(true), 10) || error == null) { out.println(MESSAGES.getMessage("command.explain.tree_header")); //out.println(tree); } else { out.println(MESSAGES.getMessage("command.explain.unparsable")); } } private void resetLoadedClasses() { shell.resetLoadedClasses(); out.println(MESSAGES.getMessage("command.discardclasses.classdefs_discarded")); } // // Custom JLine Completors to fancy up the user experience more. // private class CommandNameCompletor extends SimpleCompletor { public CommandNameCompletor() { super(new String[0]); // Add each command name/alias as a candidate Iterator iter = COMMAND_MAPPINGS.keySet().iterator(); while (iter.hasNext()) { addCandidateString((String)iter.next()); } } } // // TODO: Add local variable completion? // // // TODO: Add shell method completion? // /* private void findShellMethods(String complete) { List methods = shell.getMetaClass().getMetaMethods(); for (Iterator i = methods.iterator(); i.hasNext();) { MetaMethod method = (MetaMethod) i.next(); if (method.getName().startsWith(complete)) { if (method.getParameterTypes().length > 0) { completions.add(method.getName() + "("); } else { completions.add(method.getName() + "()"); } } } } private void findLocalVariables(String complete) { Set names = shell.getContext().getVariables().keySet(); for (Iterator i = names.iterator(); i.hasNext();) { String name = (String) i.next(); if (name.startsWith(complete)) { completions.add(name); } } } */ } groovy-1.8.6/src/main/groovy/ui/text/0000755001501200150120000000000011707612044017034 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/ui/text/StructuredSyntaxHandler.java0000644001501200150120000001150511627206700024551 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.awt.Font; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * @author Evan "Hippy" Slatis */ public class StructuredSyntaxHandler extends DefaultHandler { //StyleConstants. public static final String REGEXP = "regexp"; public static final String STYLE = "style"; public static final String ALIGN_CENTER = "ALIGN_CENTER"; public static final String ALIGN_JUSTIFIED = "ALIGN_JUSTIFIED"; public static final String ALIGN_LEFT = "ALIGN_LEFT"; public static final String ALIGN_RIGHT = "ALIGN_RIGHT"; public static final String ALIGNMENT = "alignment"; public static final String BACKGROUND = "background"; public static final String BIDI_LEVEL = "bidiLevel"; public static final String BOLD = "bold"; public static final String COMPONENT_ATTRIBUTE = "componentAttribute"; public static final String COMPONENT_ELEMENT_NAME = "componentElementName"; public static final String COMPOSED_TEXT_ATTRIBUTE = "composedTextAttribute"; public static final String FIRST_LINE_INDENT = "firstLineIndent"; public static final String FONT_FAMILY = "fontFamily"; public static final String FONT_SIZE = "fontSize"; public static final String FOREGROUND = "foreground"; public static final String ICON_ATTRIBUTE = "iconAttribute"; public static final String ICON_ELEMENT_NAME = "iconElementName"; public static final String ITALIC = "italic"; public static final String LEFT_INDENT = "leftIndent"; public static final String LINE_SPACING = "lineSpacing"; public static final String MODEL_ATTRIBUTE = "modelAttribute"; public static final String NAME_ATTRIBUTE = "nameAttribute"; public static final String ORIENTATION = "orientation"; public static final String RESOLVE_ATTRIBUTE = "resolveAttribute"; public static final String RIGHT_INDENT = "rightIndent"; public static final String SPACE_ABOVE = "spaceAbove"; public static final String SPACE_BELOW = "spaceBelow"; public static final String STRIKE_THROUGH = "strikeThrough"; public static final String SUBSCRIPT = "subscript"; public static final String SUPERSCRIPT = "superscript"; public static final String TAB_SET = "tabSet"; public static final String UNDERLINE = "underline"; private StructuredSyntaxDocumentFilter.LexerNode currentNode; private StructuredSyntaxDocumentFilter.LexerNode parentNode; private final StructuredSyntaxDocumentFilter filter; private Font font; /** * Creates a new instance of MasterFrameHandler * * @param filter */ public StructuredSyntaxHandler(StructuredSyntaxDocumentFilter filter) { this.filter = filter; } /** * @param ch * @param start * @param length */ public void characters(char[] ch, int start, int length) { } /** * @throws SAXException */ public void endDocument() throws SAXException { super.endDocument(); } /** * @param uri * @param localName * @param qName * @throws SAXException */ public void endElement(String uri, String localName, String qName) throws SAXException { } /** * @param e * @throws SAXException */ public void error(SAXParseException e) throws SAXException { throw new SAXException("Line: " + e.getLineNumber() + " message: " + e.getMessage()); } /** * @throws SAXException */ public void startDocument() throws SAXException { super.startDocument(); currentNode = filter.getRootNode(); } /** * @param uri * @param localName * @param qName * @param attributes * @throws SAXException */ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); } } groovy-1.8.6/src/main/groovy/ui/text/StructuredSyntaxDocumentFilter.java0000644001501200150120000004625611707612044026134 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.DocumentFilter; import javax.swing.text.Position; import javax.swing.text.Segment; import javax.swing.text.Style; import javax.swing.text.StyleContext; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Evan "Hippy" Slatis */ public class StructuredSyntaxDocumentFilter extends DocumentFilter { public static final String TAB_REPLACEMENT = " "; private static final MLComparator ML_COMPARATOR = new MLComparator(); /** * The root of the lexical parsing tree. */ protected LexerNode lexer = new LexerNode(true); // The styled document the filter parses protected DefaultStyledDocument styledDocument; // the document buffer and segment private Segment segment = new Segment(); private CharBuffer buffer; /** * The position tree of multi-line comments. */ protected SortedSet mlTextRunSet = new TreeSet(ML_COMPARATOR); // Ensures not adding any regexp with capturing groups private static void checkRegexp(String regexp) { String checking = regexp.replaceAll("\\\\\\(", "X").replaceAll("\\(\\?", "X"); int checked = checking.indexOf('('); if (checked > -1) { String msg = "Only non-capturing groups allowed:\r\n" + regexp + "\r\n"; for (int i = 0; i < checked; i++) { msg += " "; } msg += "^"; throw new IllegalArgumentException(msg); } } /** * Creates a new instance of StructuredSyntaxDocumentFilter * @param document the styled document to parse */ public StructuredSyntaxDocumentFilter(DefaultStyledDocument document) { this.styledDocument = document; } private int calcBeginParse(int offset) { MultiLineRun mlr = getMultiLineRun(offset); if (mlr != null) { // means we're in middle of mlr, so start at beginning of mlr offset = mlr.start(); } else { // otherwise, earliest position in line not part of mlr offset = styledDocument.getParagraphElement(offset).getStartOffset(); mlr = getMultiLineRun(offset); offset = mlr == null ? offset : mlr.end() + 1; } return offset; } private int calcEndParse(int offset) { MultiLineRun mlr = getMultiLineRun(offset); if (mlr != null) { // means we're in middle of mlr, so end is at end of mlr offset = mlr.end(); } else { // otherwise, latest position in line not part of mlr offset = styledDocument.getParagraphElement(offset).getEndOffset(); mlr = getMultiLineRun(offset); offset = mlr == null ? offset : mlr.end(); } return offset; } /** * Create a new LexerNode for adding to root. * * @return a new LexerNode */ public LexerNode createLexerNode() { return new LexerNode(false); } // given an offset, return the mlr it resides in private MultiLineRun getMultiLineRun(int offset) { MultiLineRun ml = null; if (offset > 0) { Integer os = Integer.valueOf(offset); SortedSet set = mlTextRunSet.headSet(os); if (!set.isEmpty()) { ml = (MultiLineRun)set.last(); ml = ml.end() >= offset ? ml : null; } } return ml; } /** * Get the root node for lexing the document. Children can be added such * that matching patterns can be further parsed if required. * * @return the root lexing node. */ public LexerNode getRootNode() { return lexer; } /** * Insert a string into the document, and then parse it if the parser has been * set. * * @param fb * @param offset * @param text * @param attrs * @throws BadLocationException */ public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException { // remove problem meta characters returns text = replaceMetaCharacters(text); fb.insertString(offset, text, attrs); // start on the string that was inserted parseDocument(offset, text.length()); } /** * Parse the Document to update the character styles given an initial start * position. Called by the filter after it has updated the text. * * @param offset * @param length * @throws BadLocationException */ protected void parseDocument(int offset, int length) throws BadLocationException { // initialize the segment with the complete document so the segment doesn't // have an underlying gap in the buffer styledDocument.getText(0, styledDocument.getLength(), segment); buffer = CharBuffer.wrap(segment.array).asReadOnlyBuffer(); // initialize the lexer if necessary if (!lexer.isInitialized()) { // prime the parser and reparse whole document lexer.initialize(); offset = 0; length = styledDocument.getLength(); } else { int end = offset + length; offset = calcBeginParse(offset); length = calcEndParse(end) - offset; // clean the tree by ensuring multi line styles are reset in area // of parsing SortedSet set = mlTextRunSet.subSet(Integer.valueOf(offset), Integer.valueOf(offset + length)); if (set != null) { set.clear(); } } // parse the document lexer.parse(buffer, offset, length); } /** * Remove a string from the document, and then parse it if the parser has been * set. * * @param fb * @param offset * @param length * @throws BadLocationException */ public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException { // FRICKIN' HACK!!!!! For some reason, deleting a string at offset 0 // does not get done properly, so first replace and remove after parsing if (offset == 0 && length != fb.getDocument().getLength()) { fb.replace(0, length, "\n", lexer.defaultStyle); // start on either side of the removed text parseDocument(offset, 2); fb.remove(offset, 1); } else { fb.remove(offset, length); // start on either side of the removed text if (offset + 1 < fb.getDocument().getLength()) { parseDocument(offset, 1); } else if (offset - 1 > 0) { parseDocument(offset - 1, 1); } else { // empty text mlTextRunSet.clear(); } } } /** * Replace a string in the document, and then parse it if the parser has been * set. * * @param fb * @param offset * @param length * @param text * @param attrs * @throws BadLocationException */ public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { // remove problem meta characters returns text = replaceMetaCharacters(text); fb.replace(offset, length, text, attrs); // start on the text that was replaced parseDocument(offset, text.length()); } // tabs with spaces (I hate tabs) private String replaceMetaCharacters(String string) { // just in case remove carriage returns string = string.replaceAll("\\t", TAB_REPLACEMENT); return string; } public final class LexerNode { private Style defaultStyle; private Map styleMap = new LinkedHashMap(); private Map children = new HashMap(); private Matcher matcher; private List groupList = new ArrayList(); private boolean initialized; private CharBuffer lastBuffer; /* * Creates a new instance of LexerNode */ LexerNode(boolean isParent) { StyleContext sc = StyleContext.getDefaultStyleContext(); defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE); } private String buildRegexp(String[] regexps) { String regexp = ""; for (int i = 0; i < regexps.length; i++) { regexp += "|" + regexps[i]; } // ensure leading '|' is removed return regexp.substring(1); } public Style getDefaultStyle() { return defaultStyle; } private void initialize() { matcher = null; groupList.clear(); groupList.add(null); Iterator iter = styleMap.keySet().iterator(); String regexp = ""; while (iter.hasNext()) { String nextRegexp = (String)iter.next(); regexp += "|(" + nextRegexp + ")"; // have to compile regexp first so that it will match groupList.add(Pattern.compile(nextRegexp).pattern()); } if (!regexp.equals("")) { matcher = Pattern.compile(regexp.substring(1)).matcher(""); iter = children.values().iterator(); while (iter.hasNext()) { ((LexerNode)iter.next()).initialize(); } } initialized = true; } /** * @return true if initialised */ public boolean isInitialized() { return initialized; } /** * @param buffer * @param offset * @param length * @throws BadLocationException */ public void parse(CharBuffer buffer, int offset, int length) throws BadLocationException { // get the index of where we can start to look for an exit: // i.e. after the end of the length of the segment, when we find // that text in question already is set properly, we can stop // parsing int checkPoint = offset + length; // reset the matcher and start parsing string if (lastBuffer != buffer) { matcher.reset(buffer); lastBuffer = buffer; } // the start and end indices of a match in the Matcher looking int matchEnd = offset; Style style = null; while (matchEnd < checkPoint && matcher.find(offset)) { // when we get something other than -1, we know which regexp // matched; the 0 group is the complete expression of the // matcher, which would always return a hit based on the above // while condition int groupNum = 0; while ((offset = matcher.start(++groupNum)) == -1){ } // if the matching offset is not the same as the end of the // previous match, we have extra text not matched, so set to // the default style of this lexer node if (offset != matchEnd) { offset = offset > checkPoint ? checkPoint : offset; styledDocument.setCharacterAttributes(matchEnd, offset - matchEnd, defaultStyle, true); if (offset >= checkPoint) { return; } } // track the end of the matching string matchEnd = matcher.end(groupNum); // retrieve the proper style from groupNum of the groupList and // styleMap, then set the attributes of the matching string style = (Style)styleMap.get((String)groupList.get(groupNum)); styledDocument.setCharacterAttributes(offset, matchEnd - offset, style, true); // if the match was multiline, which we'll know if they span // multiple paragraph elements, the mark it (this list was cleaned // above in parseDocument()) if (styledDocument.getParagraphElement(offset).getStartOffset() != styledDocument.getParagraphElement(matchEnd).getStartOffset()) { // mark a ml run MultiLineRun mlr = new MultiLineRun(offset, matchEnd); mlTextRunSet.add(mlr); } // parse the child regexps, if any, within a matched block LexerNode node = (LexerNode)children.get(groupList.get(groupNum)); if (node != null) { node.parse(buffer, offset, matchEnd - offset); } // set the offset to start where we left off offset = matchEnd; } if (matchEnd < checkPoint) { // if we finished before hitting the end of the checkpoint from // no mroe matches, then set ensure the text is reset to the // defaultStyle styledDocument.setCharacterAttributes(matchEnd, checkPoint - matchEnd, defaultStyle, true); } } /** * * @param regexp * @param node */ public void putChild(String regexp, LexerNode node) { node.defaultStyle = (Style)styleMap.get(regexp); // have to compile regexp first so that it will match children.put(Pattern.compile(regexp).pattern(), node); initialized = false; } /** * @param regexps * @param node */ public void putChild(String[] regexps, LexerNode node) { putChild(buildRegexp(regexps), node); } /** * @param regexp * @param style */ public void putStyle(String regexp, Style style) { checkRegexp(regexp); styleMap.put(regexp, style); initialized = false; } /** * @param regexps * @param style */ public void putStyle(String regexps[], Style style) { putStyle(buildRegexp(regexps), style); } /** * @param regexp */ public void removeChild(String regexp) { children.remove(regexp); } /** * @param regexp */ public void removeStyle(String regexp) { styleMap.remove(regexp); children.remove(regexp); } /** * @param regexps */ public void removeStyle(String regexps[]) { removeStyle(buildRegexp(regexps)); } public void setDefaultStyle(Style style) { defaultStyle = style; } } protected class MultiLineRun { private Position start; private Position end; private int delimeterSize; public MultiLineRun(int start, int end) throws BadLocationException { this(start, end, 2); } public MultiLineRun(int start, int end, int delimeterSize) throws BadLocationException { if (start > end) { String msg = "Start offset is after end: "; throw new BadLocationException(msg, start); } if (delimeterSize < 1) { String msg = "Delimiters be at least size 1: " + delimeterSize; throw new IllegalArgumentException(msg); } this.start = styledDocument.createPosition(start); this.end = styledDocument.createPosition(end); this.delimeterSize = delimeterSize; } public int getDelimeterSize() { return delimeterSize; } public int end() { return end.getOffset(); } public int length() { return end.getOffset() - start.getOffset(); } public int start() { return start.getOffset(); } public String toString() { return start.toString() + " " + end.toString(); } } private static class MLComparator implements Comparator { public int compare(Object obj, Object obj1) { return valueOf(obj) - valueOf(obj1); } private int valueOf(Object obj) { return obj instanceof Integer ? ((Integer)obj).intValue() : (obj instanceof MultiLineRun) ? ((MultiLineRun)obj).start() : ((Position)obj).getOffset(); } } } groovy-1.8.6/src/main/groovy/ui/text/TextUndoManager.java0000644001501200150120000001357311627206700022754 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.beans.PropertyChangeListener; import javax.swing.event.SwingPropertyChangeSupport; import javax.swing.event.UndoableEditEvent; import javax.swing.undo.CompoundEdit; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; /** * To use this, simply drop this as an UndoableEditListener into your document, * and then create actions to call undo/redo as needed (checking can undo/redo * first, of course). * * @author Evan "Hippy" Slatis */ public class TextUndoManager extends UndoManager { private SwingPropertyChangeSupport propChangeSupport = new SwingPropertyChangeSupport(this); private StructuredEdit compoundEdit = new StructuredEdit(); private long firstModified; private UndoableEdit modificationMarker = editToBeUndone(); /** * Creates a new instance of TextUndoManager. */ public TextUndoManager() { } public void addPropertyChangeListener(PropertyChangeListener pcl) { propChangeSupport.addPropertyChangeListener(pcl); } public void die() { boolean undoable = canUndo(); super.die(); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); } public void discardAllEdits() { boolean undoable = canUndo(); boolean redoable = canRedo(); boolean changed = hasChanged(); super.discardAllEdits(); modificationMarker = editToBeUndone(); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); firePropertyChangeEvent(UndoManager.UndoName, redoable, canRedo()); } protected void firePropertyChangeEvent(String name, boolean oldValue, boolean newValue) { propChangeSupport.firePropertyChange(name, oldValue, newValue); } public boolean hasChanged() { return modificationMarker != editToBeUndone(); } public void redo() throws javax.swing.undo.CannotRedoException { compoundEdit.end(); if (firstModified == 0) { firstModified = ((StructuredEdit) editToBeRedone()).editedTime(); } boolean undoable = canUndo(); boolean changed = hasChanged(); super.redo(); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); } protected void redoTo(UndoableEdit edit) { compoundEdit.end(); if (firstModified == 0) { firstModified = ((StructuredEdit) editToBeRedone()).editedTime(); } boolean undoable = canUndo(); boolean changed = hasChanged(); super.redoTo(edit); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); } public void removePropertyChangeListener(PropertyChangeListener pcl) { propChangeSupport.removePropertyChangeListener(pcl); } public void reset() { boolean changed = modificationMarker != editToBeUndone(); if (changed) { modificationMarker = editToBeUndone(); } } protected void trimEdits(int from, int to) { boolean undoable = canUndo(); boolean redoable = canRedo(); boolean changed = hasChanged(); super.trimEdits(from, to); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); firePropertyChangeEvent(UndoManager.RedoName, redoable, canRedo()); } public void undo() throws javax.swing.undo.CannotUndoException { compoundEdit.end(); UndoableEdit edit = editToBeUndone(); if (((StructuredEdit) editToBeUndone()).editedTime() == firstModified) { firstModified = 0; } else if (firstModified == 0) { firstModified = ((StructuredEdit) editToBeUndone()).editedTime(); } boolean redoable = canRedo(); boolean changed = hasChanged(); super.undo(); firePropertyChangeEvent(UndoManager.RedoName, redoable, canRedo()); } public void undoableEditHappened(UndoableEditEvent uee) { UndoableEdit edit = uee.getEdit(); boolean undoable = canUndo(); long editTime = System.currentTimeMillis(); if (firstModified == 0 || editTime - compoundEdit.editedTime() > 700) { compoundEdit.end(); compoundEdit = new StructuredEdit(); } compoundEdit.addEdit(edit); firstModified = firstModified == 0 ? compoundEdit.editedTime() : firstModified; if (lastEdit() != compoundEdit) { boolean changed = hasChanged(); addEdit(compoundEdit); firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo()); } } private class StructuredEdit extends CompoundEdit { private long editedTime; public boolean addEdit(UndoableEdit edit) { boolean result = super.addEdit(edit); if (result && editedTime == 0) { editedTime = System.currentTimeMillis(); } return result; } public boolean canUndo() { return edits.size() > 0; } protected long editedTime() { return editedTime; } public boolean isInProgress() { return false; } } } groovy-1.8.6/src/main/groovy/ui/text/StructuredSyntaxResources.java0000644001501200150120000000550711707612044025154 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; /** * Contains all the basic resources and values used by the utility frame work * framework. * * @author Evan "Hippy" Slatis */ public final class StructuredSyntaxResources { // ================================================== // ClipBoard // ================================================== public static final Clipboard SYSTEM_CLIPBOARD; static { Clipboard systemClipboard = null; try { // if we don't have access to the system clipboard, will throw // a security exception SecurityManager mgr = System.getSecurityManager(); if (mgr != null) { mgr.checkSystemClipboardAccess(); } systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (SecurityException e) { // means we can't get to system clipboard, so create app level one systemClipboard = new Clipboard("UIResourceMgr"); } catch (Exception e) { e.printStackTrace(); } SYSTEM_CLIPBOARD = systemClipboard; } // ===================================================== // STANDARD FONTS // ===================================================== public static final Font LARGE_FONT = Font.decode("Arial-24"); public static final Font MEDIUM_FONT = Font.decode("Arial-18"); public static final Font SMALL_FONT = Font.decode("Arial-12"); public static final Font EDITOR_FONT = Font.decode("Monospaced-12"); // ===================================================== // UNDO/REDO NAMES // ===================================================== public static final String UNDO = "Undo"; public static final String REDO = "Redo"; public static final String PRINT = "Print"; public static final String FIND = "Find"; public static final String FIND_NEXT = "Find Next"; public static final String REPLACE = "Replace"; // singleton private StructuredSyntaxResources() { } } groovy-1.8.6/src/main/groovy/ui/text/package.html0000644001501200150120000000025711627206700021320 0ustar miguelmiguel package groovy.ui.text.*

    Text processing helpers for the interactive command line terminal.

    groovy-1.8.6/src/main/groovy/ui/text/TextEditor.java0000644001501200150120000004733111627206700022001 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.print.Pageable; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.Calendar; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.plaf.ComponentUI; import javax.swing.text.Caret; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.StyledDocument; import javax.swing.text.Utilities; /** * A simple text pane that is printable and wrapping is optional. * * @author Evan "Hippy" Slatis */ public class TextEditor extends JTextPane implements Pageable, Printable { public static final String FIND = "Find..."; public static final String FIND_NEXT = "Find Next"; public static final String FIND_PREVIOUS = "Find Previous"; public static final String REPLACE = "Replace..."; public static final String AUTO_INDENT = "AutoIndent"; private static final String TABBED_SPACES = " "; private static final Pattern TAB_BACK_PATTERN = Pattern.compile("^(([\t])|( )|( )|( )|( ))", Pattern.MULTILINE); private static final Pattern LINE_START = Pattern.compile("^", Pattern.MULTILINE); private static final JTextPane PRINT_PANE = new JTextPane(); private static final Dimension PRINT_SIZE = new Dimension(); private static Toolkit toolkit = Toolkit.getDefaultToolkit(); private static boolean isOvertypeMode; private Caret defaultCaret; private Caret overtypeCaret; private static final PageFormat PAGE_FORMAT; static { PrinterJob job = PrinterJob.getPrinterJob(); PAGE_FORMAT = job.defaultPage(); } private int numPages; private int lastUpdate; private MouseAdapter mouseAdapter = new MouseAdapter() { Cursor cursor; public void mouseEntered(MouseEvent me) { if (contains(me.getPoint())) { cursor = getCursor(); Cursor curs = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); getRootPane().getLayeredPane().setCursor(curs); } else { getRootPane().getLayeredPane().setCursor(cursor); } } public void mouseExited(MouseEvent me) { getRootPane().getLayeredPane().setCursor(null); } }; // unwrapped property private boolean unwrapped; // tabsAsSpaces property private boolean tabsAsSpaces; // multiLineTab property private boolean multiLineTab; // searchable property private boolean searchable = true; /** * Creates a new instance of TextEditor */ public TextEditor() { this(false); } /** * Creates a new instance of TextEditor */ public TextEditor(boolean tabsAsSpaces) { this(tabsAsSpaces, false); } /** * Creates a new instance of TextEditor */ public TextEditor(boolean tabsAsSpaces, boolean multiLineTab) { this(multiLineTab, tabsAsSpaces, false); } /** * Creates a new instance of TextEditor */ public TextEditor(boolean tabsAsSpaces, boolean multiLineTab, boolean unwrapped) { this.tabsAsSpaces = tabsAsSpaces; this.multiLineTab = multiLineTab; this.unwrapped = unwrapped; // remove and replace the delete action to another spot so ctrl H later // on is strictly for showing the fand & replace dialog ActionMap aMap = getActionMap(); Action action = null; do { action = action == null ? aMap.get(DefaultEditorKit.deletePrevCharAction) : null; aMap.remove(DefaultEditorKit.deletePrevCharAction); aMap = aMap.getParent(); } while (aMap != null); aMap = getActionMap(); InputMap iMap = getInputMap(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0, false); iMap.put(keyStroke, "delete"); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, KeyEvent.SHIFT_MASK, false); iMap.put(keyStroke, "delete"); aMap.put("delete", action); // set all the actions action = new FindAction(); aMap.put(FIND, action); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK, false); iMap.put(keyStroke, FIND); aMap.put(FIND_NEXT, FindReplaceUtility.FIND_ACTION); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, false); iMap.put(keyStroke, FIND_NEXT); aMap.put(FIND_PREVIOUS, FindReplaceUtility.FIND_ACTION); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_MASK, false); iMap.put(keyStroke, FIND_PREVIOUS); action = new TabAction(); aMap.put("TextEditor-tabAction", action); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false); iMap.put(keyStroke, "TextEditor-tabAction"); action = new ShiftTabAction(); aMap.put("TextEditor-shiftTabAction", action); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK, false); iMap.put(keyStroke, "TextEditor-shiftTabAction"); action = new ReplaceAction(); getActionMap().put(REPLACE, action); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK, false); do { iMap.remove(keyStroke); iMap = iMap.getParent(); } while (iMap != null); getInputMap().put(keyStroke, REPLACE); action = new AutoIndentAction(); getActionMap().put(AUTO_INDENT, action); keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false); getInputMap().put(keyStroke, AUTO_INDENT); setAutoscrolls(true); defaultCaret = getCaret(); overtypeCaret = new OvertypeCaret(); overtypeCaret.setBlinkRate(defaultCaret.getBlinkRate()); } public void addNotify() { super.addNotify(); addMouseListener(mouseAdapter); FindReplaceUtility.registerTextComponent(this); } public int getNumberOfPages() { StyledDocument doc = (StyledDocument)getDocument(); Paper paper = PAGE_FORMAT.getPaper(); numPages = (int)Math.ceil(getSize().getHeight() / paper.getImageableHeight()); return numPages; } public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { return PAGE_FORMAT; } public Printable getPrintable(int param) throws IndexOutOfBoundsException { return this; } public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException { if (page < numPages) { StyledDocument doc = (StyledDocument)getDocument(); Paper paper = pageFormat.getPaper(); // initialize the PRINT_PANE (need this so that wrapping // can take place) PRINT_PANE.setDocument(getDocument()); PRINT_PANE.setFont(getFont()); PRINT_SIZE.setSize(paper.getImageableWidth(), getSize().getHeight()); PRINT_PANE.setSize(PRINT_SIZE); // translate the graphics origin upwards so the area of the page we // want to print is in the origin; the clipping region auto set // will take care of the rest double y = -(page * paper.getImageableHeight()) + paper.getImageableY(); ((Graphics2D)graphics).translate(paper.getImageableX(), y); // print the text with its own routines PRINT_PANE.print(graphics); // translate the graphics object back to reality in the y dimension // so we can print a page number ((Graphics2D)graphics).translate(0, -y); Rectangle rect = graphics.getClipBounds(); graphics.setClip(rect.x, 0, rect.width, (int)paper.getHeight() + 100); // get the name of the pane (or user name) and the time for the header Calendar cal = Calendar.getInstance(); String header = cal.getTime().toString().trim(); String name = getName() == null ? System.getProperty("user.name").trim() : getName().trim(); String pageStr = String.valueOf(page + 1); Font font = Font.decode("Monospaced 8"); graphics.setFont(font); FontMetrics fm = graphics.getFontMetrics(font); int width = SwingUtilities.computeStringWidth(fm, header); ((Graphics2D)graphics).drawString(header, (float)(paper.getImageableWidth()/2 - width/2), (float)paper.getImageableY()/2 + fm.getHeight()); ((Graphics2D)graphics).translate(0, paper.getImageableY() - fm.getHeight()); double height = paper.getImageableHeight() + paper.getImageableY()/2; width = SwingUtilities.computeStringWidth(fm, name); ((Graphics2D)graphics).drawString(name, (float)(paper.getImageableWidth()/2 - width/2), (float)height - fm.getHeight()/2); ((Graphics2D)graphics).translate(0, fm.getHeight()); width = SwingUtilities.computeStringWidth(fm, pageStr); ((Graphics2D)graphics).drawString(pageStr, (float)(paper.getImageableWidth()/2 - width/2), (float)height - fm.getHeight()/2); return Printable.PAGE_EXISTS; } return Printable.NO_SUCH_PAGE; } public boolean getScrollableTracksViewportWidth(){ boolean bool = super.getScrollableTracksViewportWidth(); if (unwrapped) { Component parent = this.getParent(); ComponentUI ui = this.getUI(); int uiWidth = ui.getPreferredSize(this).width; int parentWidth = parent.getSize().width; bool = (parent != null) ? (ui.getPreferredSize(this).width < parent.getSize().width) : true; } return bool; } public boolean isMultiLineTabbed() { return multiLineTab; } public static boolean isOvertypeMode() { return isOvertypeMode; } public boolean isTabsAsSpaces() { return tabsAsSpaces; } public boolean isUnwrapped() { return unwrapped; } protected void processKeyEvent(KeyEvent e) { super.processKeyEvent(e); // Handle release of Insert key to toggle overtype/insert mode if (e.getID() == KeyEvent.KEY_RELEASED && e.getKeyCode() == KeyEvent.VK_INSERT) { setOvertypeMode(!isOvertypeMode()); } } public void removeNotify() { super.removeNotify(); removeMouseListener(mouseAdapter); FindReplaceUtility.unregisterTextComponent(this); } public void replaceSelection(String text) { // Implement overtype mode by selecting the character at the current // caret position if (isOvertypeMode()) { int pos = getCaretPosition(); if (getSelectedText() == null && pos < getDocument().getLength()) { moveCaretPosition(pos + 1); } } super.replaceSelection(text); } public void setBounds(int x, int y, int width, int height) { if (unwrapped) { Dimension size = this.getPreferredSize(); super.setBounds(x, y, Math.max(size.width, width), Math.max(size.height, height)); } else { super.setBounds(x, y, width, height); } } /** * @param multiLineTab */ public void isMultiLineTabbed(boolean multiLineTab) { this.multiLineTab = multiLineTab; } /** * @param tabsAsSpaces */ public void isTabsAsSpaces(boolean tabsAsSpaces) { this.tabsAsSpaces = tabsAsSpaces; } /** * Set the caret to use depending on overtype/insert mode * * @param isOvertypeMode */ public void setOvertypeMode(boolean isOvertypeMode) { TextEditor.isOvertypeMode = isOvertypeMode; int pos = getCaretPosition(); if (isOvertypeMode()) { setCaret(overtypeCaret); } else { setCaret(defaultCaret); } setCaretPosition(pos); } /** * @param unwrapped */ public void setUnwrapped(boolean unwrapped) { this.unwrapped = unwrapped; } private class FindAction extends AbstractAction { public void actionPerformed(ActionEvent ae) { FindReplaceUtility.showDialog(); } } private class ReplaceAction extends AbstractAction { public void actionPerformed(ActionEvent ae) { FindReplaceUtility.showDialog(true); } } private class ShiftTabAction extends AbstractAction { public void actionPerformed(ActionEvent ae) { try { if (multiLineTab && TextEditor.this.getSelectedText() != null) { Document doc = TextEditor.this.getDocument(); int end = Utilities.getRowEnd(TextEditor.this, getSelectionEnd()); TextEditor.this.setSelectionEnd(end); Element el = Utilities.getParagraphElement(TextEditor.this, getSelectionStart()); int start = el.getStartOffset(); TextEditor.this.setSelectionStart(start); // remove text and reselect the text String text = tabsAsSpaces ? TAB_BACK_PATTERN.matcher(getSelectedText()).replaceAll("") : getSelectedText().replaceAll("^\t", ""); TextEditor.this.replaceSelection(text); TextEditor.this.select(start, start + text.length()); } } catch (Exception e) { e.printStackTrace(); } } } private class TabAction extends AbstractAction { public void actionPerformed(ActionEvent ae) { try { Document doc = TextEditor.this.getDocument(); String text = tabsAsSpaces ? TABBED_SPACES : "\t"; if (multiLineTab && getSelectedText() != null) { int end = Utilities.getRowEnd(TextEditor.this, getSelectionEnd()); TextEditor.this.setSelectionEnd(end); Element el = Utilities.getParagraphElement(TextEditor.this, getSelectionStart()); int start = el.getStartOffset(); TextEditor.this.setSelectionStart(start); String toReplace = TextEditor.this.getSelectedText(); toReplace = LINE_START.matcher(toReplace).replaceAll(text); TextEditor.this.replaceSelection(toReplace); TextEditor.this.select(start, start + toReplace.length()); } else { int pos = TextEditor.this.getCaretPosition(); doc.insertString(pos, text, null); } } catch (Exception e) { e.printStackTrace(); } } } /** * Paint a horizontal line the width of a column and 1 pixel high */ private class OvertypeCaret extends DefaultCaret { //The overtype caret will simply be a horizontal line one pixel high // (once we determine where to paint it) public void paint(Graphics g) { if (isVisible()) { try { JTextComponent component = getComponent(); Rectangle r = component.getUI().modelToView(component, getDot()); Color c = g.getColor(); g.setColor(component.getBackground()); g.setXORMode(component.getCaretColor()); r.setBounds(r.x, r.y, g.getFontMetrics().charWidth('w'), g.getFontMetrics().getHeight()); g.fillRect(r.x, r.y, r.width, r.height); g.setPaintMode(); g.setColor(c); } catch (BadLocationException e) { e.printStackTrace(); } } } /* * Damage must be overridden whenever the paint method is overridden * (The damaged area is the area the caret is painted in. We must * consider the area for the default caret and this caret) */ protected synchronized void damage(Rectangle r) { if (r != null) { JTextComponent component = getComponent(); x = r.x; y = r.y; Font font = component.getFont(); width = component.getFontMetrics(font).charWidth('w'); height = r.height; repaint(); } } } } groovy-1.8.6/src/main/groovy/ui/text/FindReplaceUtility.java0000644001501200150120000004664211627206700023452 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.TextEvent; import java.awt.event.TextListener; import java.util.EventListener; import javax.swing.Action; import javax.swing.AbstractAction; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.event.EventListenerList; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; /** * @author Evan "Hippy" Slatis */ public final class FindReplaceUtility { public static final String FIND_ACTION_COMMAND = "Find"; public static final String REPLACE_ACTION_COMMAND = "Replace"; public static final String REPLACE_ALL_ACTION_COMMAND = "Replace All"; public static final String CLOSE_ACTION_COMMAND = "Close"; public static final Action FIND_ACTION = new FindAction(); private static final JDialog FIND_REPLACE_DIALOG = new JDialog(); private static final JPanel TEXT_FIELD_PANEL = new JPanel(new GridLayout(2, 1)); private static final JPanel ENTRY_PANEL = new JPanel(); private static final JPanel FIND_PANEL = new JPanel(); private static final JLabel FIND_LABEL = new JLabel("Find What: "); private static final JComboBox FIND_FIELD = new JComboBox(); private static final JPanel REPLACE_PANEL = new JPanel(); private static final JLabel REPLACE_LABEL = new JLabel("Replace With:"); private static final JComboBox REPLACE_FIELD = new JComboBox(); private static final JPanel BUTTON_PANEL = new JPanel(); private static final JButton FIND_BUTTON = new JButton(); private static final JButton REPLACE_BUTTON = new JButton(); private static final JButton REPLACE_ALL_BUTTON = new JButton(); private static final JButton CLOSE_BUTTON = new JButton(); private static final Action CLOSE_ACTION = new CloseAction(); private static final Action REPLACE_ACTION = new ReplaceAction(); private static final JPanel CHECK_BOX_PANEL = new JPanel(new GridLayout(3, 1)); private static final JCheckBox MATCH_CASE_CHECKBOX = new JCheckBox("Match Case "); private static final JCheckBox IS_BACKWARDS_CHECKBOX = new JCheckBox("Search Backwards"); private static final JCheckBox WRAP_SEARCH_CHECKBOX = new JCheckBox("Wrap Search "); private static JTextComponent textComponent; private static AttributeSet attributeSet; private static int findReplaceCount; private static String lastAction; private static final EventListenerList EVENT_LISTENER_LIST = new EventListenerList(); // the document segment private static final Segment SEGMENT = new Segment(); private static final FocusAdapter TEXT_FOCUS_LISTENER = new FocusAdapter() { public void focusGained(FocusEvent fe) { textComponent = (JTextComponent) fe.getSource(); attributeSet = textComponent.getDocument().getDefaultRootElement().getAttributes(); } }; static { FIND_REPLACE_DIALOG.setResizable(false); FIND_REPLACE_DIALOG.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // is next line needed at all? /* KeyStroke keyStroke = */ KeyStroke.getKeyStroke("enter"); KeyAdapter keyAdapter = new KeyAdapter() { public void keyTyped(KeyEvent ke) { if (ke.getKeyChar() == KeyEvent.VK_ENTER) { FIND_BUTTON.doClick(); } } }; FIND_PANEL.setLayout(new FlowLayout(FlowLayout.RIGHT)); FIND_PANEL.add(FIND_LABEL); FIND_PANEL.add(FIND_FIELD); FIND_FIELD.addItem(""); FIND_FIELD.setEditable(true); FIND_FIELD.getEditor().getEditorComponent().addKeyListener(keyAdapter); Dimension d = FIND_FIELD.getPreferredSize(); d.width = 225; FIND_FIELD.setPreferredSize(d); REPLACE_PANEL.add(REPLACE_LABEL); REPLACE_PANEL.add(REPLACE_FIELD); REPLACE_FIELD.setEditable(true); REPLACE_FIELD.getEditor().getEditorComponent().addKeyListener(keyAdapter); REPLACE_FIELD.setPreferredSize(d); TEXT_FIELD_PANEL.setLayout(new BoxLayout(TEXT_FIELD_PANEL, BoxLayout.Y_AXIS)); TEXT_FIELD_PANEL.add(FIND_PANEL); TEXT_FIELD_PANEL.add(REPLACE_PANEL); ENTRY_PANEL.add(TEXT_FIELD_PANEL); FIND_REPLACE_DIALOG.getContentPane().add(ENTRY_PANEL, BorderLayout.WEST); CHECK_BOX_PANEL.add(MATCH_CASE_CHECKBOX); CHECK_BOX_PANEL.add(IS_BACKWARDS_CHECKBOX); CHECK_BOX_PANEL.add(WRAP_SEARCH_CHECKBOX); ENTRY_PANEL.add(CHECK_BOX_PANEL); ENTRY_PANEL.setLayout(new BoxLayout(ENTRY_PANEL, BoxLayout.Y_AXIS)); REPLACE_ALL_BUTTON.setAction(new ReplaceAllAction()); REPLACE_ALL_BUTTON.setHorizontalAlignment(JButton.CENTER); d = REPLACE_ALL_BUTTON.getPreferredSize(); BUTTON_PANEL.setLayout(new BoxLayout(BUTTON_PANEL, BoxLayout.Y_AXIS)); FIND_BUTTON.setAction(FIND_ACTION); FIND_BUTTON.setPreferredSize(d); FIND_BUTTON.setHorizontalAlignment(JButton.CENTER); JPanel panel = new JPanel(); panel.add(FIND_BUTTON); BUTTON_PANEL.add(panel); FIND_REPLACE_DIALOG.getRootPane().setDefaultButton(FIND_BUTTON); REPLACE_BUTTON.setAction(REPLACE_ACTION); REPLACE_BUTTON.setPreferredSize(d); REPLACE_BUTTON.setHorizontalAlignment(JButton.CENTER); panel = new JPanel(); panel.add(REPLACE_BUTTON); BUTTON_PANEL.add(panel); panel = new JPanel(); panel.add(REPLACE_ALL_BUTTON); BUTTON_PANEL.add(panel); CLOSE_BUTTON.setAction(CLOSE_ACTION); CLOSE_BUTTON.setPreferredSize(d); CLOSE_BUTTON.setHorizontalAlignment(JButton.CENTER); panel = new JPanel(); panel.add(CLOSE_BUTTON); BUTTON_PANEL.add(panel); FIND_REPLACE_DIALOG.getContentPane().add(BUTTON_PANEL); KeyStroke stroke = (KeyStroke) CLOSE_ACTION.getValue(Action.ACCELERATOR_KEY); JRootPane rPane = FIND_REPLACE_DIALOG.getRootPane(); rPane.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW).put(stroke, "exit"); rPane.getActionMap().put("exit", CLOSE_ACTION); } // Singleton private FindReplaceUtility() { } public static void addTextListener(TextListener tl) { EVENT_LISTENER_LIST.add(TextListener.class, tl); } private static void fireTextEvent() { EventListener[] lstrs = EVENT_LISTENER_LIST.getListeners(TextListener.class); if (lstrs != null && lstrs.length > 0) { TextEvent te = new TextEvent(FIND_REPLACE_DIALOG, TextEvent.TEXT_VALUE_CHANGED); for (int i = 0; i < lstrs.length; i++) { ((TextListener) lstrs[i]).textValueChanged(te); } } } /** * @return the last action */ public static String getLastAction() { return lastAction; } /** * @return the replacement count */ public static int getReplacementCount() { return findReplaceCount; } /** * @return the search text */ public static String getSearchText() { return (String) FIND_FIELD.getSelectedItem(); } /** * @param textComponent the text component to listen to */ public static void registerTextComponent(JTextComponent textComponent) { textComponent.addFocusListener(TEXT_FOCUS_LISTENER); } public static void removeTextListener(TextListener tl) { EVENT_LISTENER_LIST.remove(TextListener.class, tl); } /** * Find and select the next searchable matching text. * * @param reverse look forwards or backwards * @param pos the starting index to start finding from * @return the location of the next selected, or -1 if not found */ private static int findNext(boolean reverse, int pos) { boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected(); backwards = backwards ? !reverse : reverse; String pattern = (String) FIND_FIELD.getSelectedItem(); if (pattern != null && pattern.length() > 0) { try { Document doc = textComponent.getDocument(); doc.getText(0, doc.getLength(), SEGMENT); } catch (Exception e) { // should NEVER reach here e.printStackTrace(); } pos += textComponent.getSelectedText() == null ? (backwards ? -1 : 1) : 0; char first = backwards ? pattern.charAt(pattern.length() - 1) : pattern.charAt(0); char oppFirst = Character.isUpperCase(first) ? Character.toLowerCase(first) : Character.toUpperCase(first); int start = pos; boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected(); int end = backwards ? 0 : SEGMENT.getEndIndex(); pos += backwards ? -1 : 1; int length = textComponent.getDocument().getLength(); if (pos > length) { pos = wrapped ? 0 : length; } boolean found = false; while (!found && (backwards ? pos > end : pos < end)) { found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst; found = found ? found : SEGMENT.array[pos] == first; if (found) { pos += backwards ? -(pattern.length() - 1) : 0; for (int i = 0; found && i < pattern.length(); i++) { char c = pattern.charAt(i); found = SEGMENT.array[pos + i] == c; if (!MATCH_CASE_CHECKBOX.isSelected() && !found) { c = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c); found = SEGMENT.array[pos + i] == c; } } } if (!found) { pos += backwards ? -1 : 1; if (pos == end && wrapped) { pos = backwards ? SEGMENT.getEndIndex() : 0; end = start; wrapped = false; } } } pos = found ? pos : -1; } return pos; } private static void setListStrings() { Object findObject = FIND_FIELD.getSelectedItem(); Object replaceObject = REPLACE_FIELD.isShowing() ? (String) REPLACE_FIELD.getSelectedItem() : ""; if (findObject != null && replaceObject != null) { boolean found = false; for (int i = 0; !found && i < FIND_FIELD.getItemCount(); i++) { found = FIND_FIELD.getItemAt(i).equals(findObject); } if (!found) { FIND_FIELD.insertItemAt(findObject, 0); if (FIND_FIELD.getItemCount() > 7) { FIND_FIELD.removeItemAt(7); } } if (REPLACE_FIELD.isShowing()) { found = false; for (int i = 0; !found && i < REPLACE_FIELD.getItemCount(); i++) { found = REPLACE_FIELD.getItemAt(i).equals(findObject); } if (!found) { REPLACE_FIELD.insertItemAt(replaceObject, 0); if (REPLACE_FIELD.getItemCount() > 7) { REPLACE_FIELD.removeItemAt(7); } } } } } public static void showDialog() { showDialog(false); } /** * @param isReplace show a replace dialog rather than a find dialog if true */ public static void showDialog(boolean isReplace) { String title = isReplace ? REPLACE_ACTION_COMMAND : FIND_ACTION_COMMAND; FIND_REPLACE_DIALOG.setTitle(title); String text = textComponent.getSelectedText(); if (text == null) { text = ""; } FIND_FIELD.getEditor().setItem(text); FIND_FIELD.getEditor().selectAll(); REPLACE_PANEL.setVisible(isReplace); REPLACE_ALL_BUTTON.setVisible(isReplace); CLOSE_BUTTON.setVisible(isReplace); Action action = isReplace ? REPLACE_ACTION : CLOSE_ACTION; REPLACE_BUTTON.setAction(action); REPLACE_BUTTON.setPreferredSize(null); Dimension d = isReplace ? REPLACE_ALL_BUTTON.getPreferredSize() : REPLACE_BUTTON.getPreferredSize(); FIND_BUTTON.setPreferredSize(d); REPLACE_BUTTON.setPreferredSize(d); CLOSE_BUTTON.setPreferredSize(d); FIND_REPLACE_DIALOG.invalidate(); FIND_REPLACE_DIALOG.repaint(); FIND_REPLACE_DIALOG.pack(); java.awt.Frame[] frames = java.awt.Frame.getFrames(); for (int i = 0; i < frames.length; i++) { if (frames[i].isFocused()) { FIND_REPLACE_DIALOG.setLocationRelativeTo(frames[i]); } } FIND_REPLACE_DIALOG.setVisible(true); FIND_FIELD.requestFocusInWindow(); } /** * @param textComponent the text component to stop listening to */ public static void unregisterTextComponent(JTextComponent textComponent) { textComponent.removeFocusListener(TEXT_FOCUS_LISTENER); } private static class FindAction extends AbstractAction { public FindAction() { putValue(Action.NAME, FIND_ACTION_COMMAND); putValue(Action.ACTION_COMMAND_KEY, FIND_ACTION_COMMAND); putValue(Action.MNEMONIC_KEY, Integer.valueOf(KeyEvent.VK_F)); } public void actionPerformed(ActionEvent ae) { lastAction = FIND_ACTION_COMMAND; findReplaceCount = 0; if (FIND_REPLACE_DIALOG.isVisible() && FIND_REPLACE_DIALOG.getTitle().equals(FIND_ACTION_COMMAND)) { } int pos = textComponent.getSelectedText() == null ? textComponent.getCaretPosition() : textComponent.getSelectionStart(); boolean reverse = (ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0; pos = findNext(reverse, pos); if (pos > -1) { String pattern = (String) FIND_FIELD.getSelectedItem(); textComponent.select(pos, pos + pattern.length()); findReplaceCount = 1; } setListStrings(); fireTextEvent(); } } private static class ReplaceAction extends AbstractAction { public ReplaceAction() { putValue(Action.NAME, REPLACE_ACTION_COMMAND); putValue(Action.ACTION_COMMAND_KEY, REPLACE_ACTION_COMMAND); putValue(Action.MNEMONIC_KEY, Integer.valueOf(KeyEvent.VK_R)); } public void actionPerformed(ActionEvent ae) { lastAction = ae.getActionCommand(); findReplaceCount = 0; int pos = textComponent.getSelectedText() == null ? textComponent.getCaretPosition() : textComponent.getSelectionStart(); pos = findNext(false, pos - 1); if (pos > -1) { String find = (String) FIND_FIELD.getSelectedItem(); String replace = (String) REPLACE_FIELD.getSelectedItem(); replace = replace == null ? "" : replace; Document doc = textComponent.getDocument(); try { doc.remove(pos, find.length()); doc.insertString(pos, replace, attributeSet); int last = pos; pos = findNext(false, pos); if (pos > -1) { textComponent.select(pos, pos + find.length()); } else { textComponent.setCaretPosition(last + replace.length()); } } catch (BadLocationException ble) { ble.printStackTrace(); } findReplaceCount = 1; } setListStrings(); fireTextEvent(); } } private static class ReplaceAllAction extends AbstractAction { public ReplaceAllAction() { putValue(Action.NAME, REPLACE_ALL_ACTION_COMMAND); putValue(Action.ACTION_COMMAND_KEY, REPLACE_ALL_ACTION_COMMAND); putValue(Action.MNEMONIC_KEY, Integer.valueOf(KeyEvent.VK_A)); } public void actionPerformed(ActionEvent ae) { lastAction = ae.getActionCommand(); findReplaceCount = 0; int last = textComponent.getSelectedText() == null ? textComponent.getCaretPosition() : textComponent.getSelectionStart(); int pos = findNext(false, last - 1); String find = (String) FIND_FIELD.getSelectedItem(); String replace = (String) REPLACE_FIELD.getSelectedItem(); replace = replace == null ? "" : replace; while (pos > -1) { Document doc = textComponent.getDocument(); try { doc.remove(pos, find.length()); doc.insertString(pos, replace, attributeSet); last = pos; pos = findNext(false, pos); } catch (BadLocationException ble) { ble.printStackTrace(); } findReplaceCount++; } if (pos > -1) { textComponent.select(pos, pos + find.length()); } else { textComponent.setCaretPosition(last + replace.length()); } setListStrings(); fireTextEvent(); } } private static class CloseAction extends AbstractAction { public CloseAction() { putValue(Action.NAME, CLOSE_ACTION_COMMAND); putValue(Action.ACTION_COMMAND_KEY, CLOSE_ACTION_COMMAND); putValue(Action.MNEMONIC_KEY, Integer.valueOf(KeyEvent.VK_C)); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ESCAPE")); } public void actionPerformed(ActionEvent ae) { FIND_REPLACE_DIALOG.dispose(); } } public static void dispose() { FIND_REPLACE_DIALOG.dispose(); } } groovy-1.8.6/src/main/groovy/ui/text/GroovyFilter.java0000644001501200150120000002236311707612044022340 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.StyleContext; /** * @author Evan "Hippy" Slatis */ public class GroovyFilter extends StructuredSyntaxDocumentFilter { // java tab policy action private static final Action AUTO_TAB_ACTION = new AutoTabAction(); // Style names public static final String COMMENT = "comment"; public static final String SLASH_STAR_COMMENT = "/\\*(?s:.)*?(?:\\*/|\\z)"; public static final String SLASH_SLASH_COMMENT = "//.*"; public static final String QUOTES = "(?ms:\"{3}(?!\\\"{1,3}).*?(?:\"{3}|\\z))|(?:\"{1}(?!\\\").*?(?:\"|\\Z))"; public static final String SINGLE_QUOTES = "(?ms:'{3}(?!'{1,3}).*?(?:'{3}|\\z))|(?:'[^'].*?(?:'|\\z))"; public static final String SLASHY_QUOTES = "(?:/[^/*].*?/|(?ms:\\$/.*?(?:/\\$|\\z)))"; public static final String DIGIT = "\\d+?[efld]?"; public static final String IDENT = "[\\w\\$&&[\\D]][\\w\\$]*"; public static final String OPERATION = "[\\w\\$&&[\\D]][\\w\\$]* *\\("; public static final String LEFT_PARENS = "\\("; private static final Color COMMENT_COLOR = Color.LIGHT_GRAY.darker().darker(); public static final String RESERVED_WORD = "reserved"; public static final String[] RESERVED_WORDS = {"\\babstract\\b", "\\bassert\\b", "\\bdefault\\b", "\\bif\\b", "\\bprivate\\b", "\\bthis\\b", "\\bboolean\\b", "\\bdo\\b", "\\bimplements\\b", "\\bprotected\\b", "\\bthrow\\b", "\\bbreak\\b", "\\bdouble\\b", "\\bimport\\b", "\\bpublic\\b", "\\bthrows\\b", "\\bbyte\\b", "\\belse\\b", "\\binstanceof\\b", "\\breturn\\b", "\\btransient\\b", "\\bcase\\b", "\\bextends\\b", "\\bint\\b", "\\bshort\\b", "\\btry\\b", "\\bcatch\\b", "\\bfinal\\b", "\\binterface\\b", "\\benum\\b", "\\bstatic\\b", "\\bvoid\\b", "\\bchar\\b", "\\bfinally\\b", "\\blong\\b", "\\bstrictfp\\b", "\\bvolatile\\b", "\\bclass\\b", "\\bfloat\\b", "\\bnative\\b", "\\bsuper\\b", "\\bwhile\\b", "\\bconst\\b", "\\bfor\\b", "\\bnew\\b", "\\bswitch\\b", "\\bcontinue\\b", "\\bgoto\\b", "\\bpackage\\b", "\\bdef\\b", "\\bas\\b", "\\bin\\b", "\\bsynchronized\\b", "\\bnull\\b"}; /** * Creates a new instance of GroovyFilter */ public GroovyFilter(DefaultStyledDocument doc) { super(doc); init(); } private void init() { StyleContext styleContext = StyleContext.getDefaultStyleContext(); Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE); Style comment = styleContext.addStyle(COMMENT, defaultStyle); StyleConstants.setForeground(comment, COMMENT_COLOR); StyleConstants.setItalic(comment, true); Style quotes = styleContext.addStyle(QUOTES, defaultStyle); StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker()); Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle); StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker()); Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle); StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker()); Style digit = styleContext.addStyle(DIGIT, defaultStyle); StyleConstants.setForeground(digit, Color.RED.darker()); Style operation = styleContext.addStyle(OPERATION, defaultStyle); StyleConstants.setBold(operation, true); Style ident = styleContext.addStyle(IDENT, defaultStyle); Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle); StyleConstants.setBold(reservedWords, true); StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker()); Style leftParens = styleContext.addStyle(IDENT, defaultStyle); getRootNode().putStyle(SLASH_STAR_COMMENT, comment); getRootNode().putStyle(SLASH_SLASH_COMMENT, comment); getRootNode().putStyle(QUOTES, quotes); getRootNode().putStyle(SINGLE_QUOTES, charQuotes); getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes); getRootNode().putStyle(DIGIT, digit); getRootNode().putStyle(OPERATION, operation); StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); node.putStyle(LEFT_PARENS, leftParens); getRootNode().putChild(OPERATION, node); getRootNode().putStyle(IDENT, ident); node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); getRootNode().putChild(IDENT, node); } public static void installAutoTabAction(JTextComponent tComp) { tComp.getActionMap().put("GroovyFilter-autoTab", AUTO_TAB_ACTION); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false); tComp.getInputMap().put(keyStroke, "GroovyFilter-autoTab"); } private static class AutoTabAction extends AbstractAction { private StyledDocument doc; private final Segment segment = new Segment(); private final StringBuffer buffer = new StringBuffer(); public void actionPerformed(ActionEvent ae) { JTextComponent tComp = (JTextComponent) ae.getSource(); if (tComp.getDocument() instanceof StyledDocument) { doc = (StyledDocument) tComp.getDocument(); try { doc.getText(0, doc.getLength(), segment); } catch (Exception e) { // should NEVER reach here e.printStackTrace(); } int offset = tComp.getCaretPosition(); int index = findTabLocation(offset); buffer.delete(0, buffer.length()); buffer.append('\n'); if (index > -1) { for (int i = 0; i < index + 4; i++) { buffer.append(' '); } } try { doc.insertString(offset, buffer.toString(), doc.getDefaultRootElement().getAttributes()); } catch (BadLocationException ble) { ble.printStackTrace(); } } } public int findTabLocation(int offset) { // find first { boolean cont = true; while (offset > -1 && cont) { Element el = doc.getCharacterElement(offset); Object color = el.getAttributes().getAttribute(StyleConstants.Foreground); if (!COMMENT_COLOR.equals(color)) { cont = segment.array[offset] != '{' && segment.array[offset] != '}'; } offset -= cont ? 1 : 0; } if (offset > -1 && segment.array[offset] == '{') { while (offset > -1 && !Character.isWhitespace(segment.array[offset--])) { } } int index = offset < 0 || segment.array[offset] == '}' ? -4 : 0; if (offset > -1) { Element top = doc.getDefaultRootElement(); offset = top.getElement(top.getElementIndex(offset)).getStartOffset(); while (Character.isWhitespace(segment.array[offset++])) { index++; } } return index; } } } groovy-1.8.6/src/main/groovy/ui/text/AutoIndentAction.groovy0000644001501200150120000000362511627206700023520 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.ui.text import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.text.AttributeSet import javax.swing.text.SimpleAttributeSet class AutoIndentAction extends AbstractAction { AttributeSet simpleAttributeSet = new SimpleAttributeSet() public void actionPerformed(ActionEvent evt) { def inputArea = evt.source def rootElement = inputArea.document.defaultRootElement def cursorPos = inputArea.getCaretPosition() int rowNum = rootElement.getElementIndex(cursorPos) def rowElement = rootElement.getElement(rowNum) int startOffset = rowElement.getStartOffset() int endOffset = rowElement.getEndOffset() String rowContent = inputArea.document.getText(startOffset, endOffset - startOffset); String contentBeforeCursor = inputArea.document.getText(startOffset, cursorPos - startOffset); String whitespaceStr = '' def matcher = (rowContent =~ /(?m)^(\s*).*\n$/) matcher.each { all, ws -> whitespaceStr = ws } if (contentBeforeCursor ==~ /(\s)*/) { whitespaceStr = contentBeforeCursor } inputArea.document.insertString(cursorPos, '\n' + whitespaceStr, simpleAttributeSet) } }groovy-1.8.6/src/main/groovy/io/0000755001501200150120000000000011707612044016042 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/io/package.html0000644001501200150120000000021211627206700020315 0ustar miguelmiguel package groovy.io.*

    Classes for Groovier Input/Output.

    groovy-1.8.6/src/main/groovy/io/LineColumnReader.java0000644001501200150120000001642211707612044022102 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; /** * The LineColumnReader is an extension to BufferedReader * that keeps track of the line and column information of where the cursor is. * * @author Guillaume Laforge * @since 1.8.0 */ public class LineColumnReader extends BufferedReader { /** * The current line position */ private long line = 1; /** * The current column position */ private long column = 1; /** * The latest marked line position */ private long lineMark = 1; /** * The latest marked line position */ private long columnMark = 1; private boolean newLineWasRead = false; /** * Constructor wrapping a Reader * (FileReader, FileReader, InputStreamReader, etc.) * * @param reader the reader to wrap */ public LineColumnReader(Reader reader) { super(reader); } /** * Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point. * * @param readAheadLimit Limit on the number of characters that may be read while still preserving the mark. * An attempt to reset the stream after reading characters up to this limit or beyond may fail. * A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. * Therefore large values should be used with care. */ @Override public void mark(int readAheadLimit) throws IOException { lineMark = line; columnMark = column; super.mark(readAheadLimit); } /** * Resets the stream to the most recent mark. */ @Override public void reset() throws IOException { line = lineMark; column = columnMark; super.reset(); } /** * Reads a single character. * * @return The character read, as an integer in the range 0 to 65535 (0x00-0xffff), * or -1 if the end of the stream has been reached */ @Override public int read() throws IOException { if (newLineWasRead) { line += 1; column = 1; newLineWasRead = false; } int charRead = super.read(); if (charRead > -1) { char c = (char)charRead; // found a \r or \n, like on Mac or Unix // could also be Windows' \r\n if (c == '\r' || c == '\n') { newLineWasRead = true; if (c == '\r') { mark(1); c = (char)super.read(); // check if we have \r\n like on Windows // if it's not \r\n we reset, otherwise, the \n is just consummed if (c != '\n') { reset(); } } } else { column += 1; } } return charRead; } /** * Reads characters into a portion of an array. * * @param chars Destination array of char * @param startOffset Offset at which to start storing characters * @param length Maximum number of characters to read * @return an exception if an error occurs */ @Override public int read(char[] chars, int startOffset, int length) throws IOException { for (int i = startOffset; i <= startOffset + length; i++) { int readInt = read(); if (readInt == -1) return i - startOffset; chars[i] = (char)readInt; } return length; } /** * Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), * a carriage return ('\r'), or a carriage return followed immediately by a linefeed. * * @return A String containing the contents of the line, not including any line-termination characters, * or null if the end of the stream has been reached */ @Override public String readLine() throws IOException { StringBuilder result = new StringBuilder(); for (;;) { int intRead = read(); if (intRead == -1) { return result.length() == 0 ? null : result.toString(); } char c = (char)intRead; if (c == '\n' || c == '\r') break; result.append(c); } return result.toString(); } /** * Skips characters. * * @param toSkip the number of characters to skip * @return The number of characters actually skipped */ @Override public long skip(long toSkip) throws IOException { for (long i = 0; i < toSkip; i++) { int intRead = read(); if (intRead == -1) return i; } return toSkip; } /** * Reads characters into an array. * This method will block until some input is available, an I/O error occurs, * or the end of the stream is reached. * * @param chars Destination buffer * @return The number of characters read, or -1 if the end of the stream has been reached */ @Override public int read(char[] chars) throws IOException { return read(chars, 0, chars.length - 1); } /** * Not implemented. * * @param buffer Destination buffer * @return The number of characters read, or -1 if the end of the stream has been reached * @throws UnsupportedOperationException as the method is not implemented */ @Override public int read(CharBuffer buffer) { throw new UnsupportedOperationException("read(CharBuffer) not yet implemented"); } /** * Closes the stream and releases any system resources associated with it. * Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations * will throw an IOException. Closing a previously closed stream has no effect. */ @Override public void close() throws IOException { super.close(); } public long getColumn() { return column; } public void setColumn(long column) { this.column = column; } public long getColumnMark() { return columnMark; } public void setColumnMark(long columnMark) { this.columnMark = columnMark; } public long getLine() { return line; } public void setLine(long line) { this.line = line; } public long getLineMark() { return lineMark; } public void setLineMark(long lineMark) { this.lineMark = lineMark; } } groovy-1.8.6/src/main/groovy/io/FileVisitResult.java0000644001501200150120000000250611627206700022004 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; /** * Represents special return values for the 'preDir', 'postDir' and 'visit'/supplied Closures used with * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#traverse(java.io.File, java.util.Map, groovy.lang.Closure)} * and related methods to control subsequent traversal behavior. */ public enum FileVisitResult { /** Continue processing; the default */ CONTINUE, /** Skip processing sibling files/directories within the current directory being processed */ SKIP_SIBLINGS, /** Do not process the child files/subdirectories within the current directory being processed */ SKIP_SUBTREE, /** Do not process any more files */ TERMINATE } groovy-1.8.6/src/main/groovy/io/PlatformLineWriter.java0000644001501200150120000000344311627206700022501 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; import java.io.BufferedWriter; import java.io.Writer; import java.io.IOException; /** * A buffered writer that gobbles any \r characters * and replaces every \n with a platform specific newline. * In many places Groovy normalises streams to only have \n * characters but when creating files that must be used * by other platform-aware tools, you sometimes want the * newlines to match what the platform expects. * * @author Paul King */ public class PlatformLineWriter extends Writer { private BufferedWriter writer; public PlatformLineWriter(Writer out) { writer = new BufferedWriter(out); } public PlatformLineWriter(Writer out, int sz) { writer = new BufferedWriter(out, sz); } public void write(char cbuf[], int off, int len) throws IOException { for (; len > 0; len--) { char c = cbuf[off++]; if (c == '\n') { writer.newLine(); } else if (c != '\r') { writer.write(c); } } } public void flush() throws IOException { writer.flush(); } public void close() throws IOException { writer.close(); } } groovy-1.8.6/src/main/groovy/io/GroovyPrintWriter.java0000644001501200150120000000523211627206700022405 0ustar miguelmiguel/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; import java.io.File; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import org.codehaus.groovy.runtime.InvokerHelper; /** * A PrintWriter that outputs objects in Groovy style. * That means print(Object) uses InvokerHelper.toString(Object) * to produce the same results as Writer.print(Object). * * @author Jim White * @since 1.6 */ public class GroovyPrintWriter extends PrintWriter { public GroovyPrintWriter(File file) throws FileNotFoundException { super(file); } public GroovyPrintWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(file, csn); } public GroovyPrintWriter(Writer out) { super(out); } public GroovyPrintWriter(Writer out, boolean autoflush) { super(out, autoflush); } public GroovyPrintWriter(OutputStream out) { super(out); } public GroovyPrintWriter(OutputStream out, boolean autoflush) { super(out, autoflush); } public GroovyPrintWriter(String filename) throws FileNotFoundException { super(filename); } public GroovyPrintWriter(String filename, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(filename, csn); } // Don't need to do this if Groovy is going to print char[] like a string. // public void print(char[] x) // { // write(InvokerHelper.toString(x)); // } public void print(Object x) { write(InvokerHelper.toString(x)); } public void println(Object x) { // JDK 1.6 has changed the implementation to do a // String.valueOf(x) rather than call print(x). // Probably to improve performance by doing the conversion outside the lock. // This will do the same thing for us, and we don't have to have access to the lock. println(InvokerHelper.toString(x)); } } groovy-1.8.6/src/main/groovy/io/FileType.java0000644001501200150120000000161211627206700020425 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; /** * Represents particular files of interest. */ public enum FileType { /** Represents normal files */ FILES, /** Represents directories */ DIRECTORIES, /** Represents both normal files and directories */ ANY } groovy-1.8.6/src/main/groovy/io/GroovyPrintStream.java0000644001501200150120000000712411627206700022366 0ustar miguelmiguel/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; import java.io.File; import java.io.OutputStream; import java.io.PrintStream; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import org.codehaus.groovy.runtime.InvokerHelper; /** * A PrintStream that outputs objects in Groovy style. * That means print(Object) uses InvokerHelper.toString(Object) * to produce the same results as Writer.print(Object). * * @author Jim White * @since 1.6 */ public class GroovyPrintStream extends PrintStream { /** * Creates a new print stream. This stream will not flush automatically. * * @see java.io.PrintStream#PrintStream(java.io.OutputStream) */ public GroovyPrintStream(OutputStream out) { super(out, false); } /** * Creates a new print stream. * * @see java.io.PrintStream#PrintStream(java.io.OutputStream, boolean) */ public GroovyPrintStream(OutputStream out, boolean autoFlush) { super(out, autoFlush); } /** * Creates a new print stream. * * @see java.io.PrintStream#PrintStream(java.io.OutputStream, boolean, String) */ public GroovyPrintStream(OutputStream out, boolean autoFlush, String encoding) throws UnsupportedEncodingException { super(out, autoFlush, encoding); } /** * Creates a new print stream, without automatic line flushing, with the * specified file name. * * @see java.io.PrintStream#PrintStream(String) */ public GroovyPrintStream(String fileName) throws FileNotFoundException { super(fileName); } /** * Creates a new print stream, without automatic line flushing, with the * specified file name and charset. * * @see java.io.PrintStream#PrintStream(String, String) */ public GroovyPrintStream(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(fileName, csn); } /** * Creates a new print stream, without automatic line flushing, with the * specified file. * * @see java.io.PrintStream#PrintStream(File) */ public GroovyPrintStream(File file) throws FileNotFoundException { super(file); } /** * Creates a new print stream, without automatic line flushing, with the * specified file and charset. * * @see java.io.PrintStream#PrintStream(File, String) */ public GroovyPrintStream(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(file, csn); } /** * Prints an object Groovy style. * * @param obj The Object to be printed */ public void print(Object obj) { print(InvokerHelper.toString(obj)); } /** * Prints an object Groovy style followed by a newline. * * @param obj The Object to be printed */ public void println(Object obj) { println(InvokerHelper.toString(obj)); } } groovy-1.8.6/src/main/groovy/io/EncodingAwareBufferedWriter.java0000644001501200150120000000314511627206700024255 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.io; import java.io.*; import java.nio.charset.Charset; /** * A buffered writer only for OutputStreamWriter that is aware of * the encoding of the OutputStreamWriter. * * @author Paul King */ public class EncodingAwareBufferedWriter extends BufferedWriter { private OutputStreamWriter out; public EncodingAwareBufferedWriter(OutputStreamWriter out) { super(out); this.out = out; } /** * The encoding as returned by the underlying OutputStreamWriter. Can be the historical name. * * @return the encoding * @see java.io.OutputStreamWriter#getEncoding() */ public String getEncoding() { return out.getEncoding(); } /** * The encoding as returned by the underlying OutputStreamWriter. Will be the preferred name. * * @return the encoding * @see java.io.OutputStreamWriter#getEncoding() */ public String getNormalizedEncoding() { return Charset.forName(getEncoding()).name(); } } groovy-1.8.6/src/main/groovy/inspect/0000755001501200150120000000000011715031256017077 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/inspect/package.html0000644001501200150120000000025411627206702021363 0ustar miguelmiguel package groovy.inspect.*

    Classes for inspecting object properties through introspection.

    groovy-1.8.6/src/main/groovy/inspect/swingui/0000755001501200150120000000000011715031256020564 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/inspect/swingui/ObjectBrowser.groovy0000644001501200150120000001520011627206702024605 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui import java.awt.* import javax.swing.* import groovy.swing.SwingBuilder import groovy.inspect.Inspector /** A little GUI to show some of the Inspector capabilities. Starting this script opens the ObjectBrowser on "some String". Use it in groovysh or groovyConsole to inspect your object of interest with ObjectBrowser.inspect(myObject) . @author Dierk Koenig **/ class ObjectBrowser { def inspector def swing, frame, fieldTable, methodTable, itemTable, mapTable static void main(args) { inspect("some String") } static void inspect(objectUnderInspection){ def browser = new ObjectBrowser() browser.inspector = new Inspector(objectUnderInspection) browser.run() } void run() { swing = new SwingBuilder() frame = swing.frame(title:'Groovy Object Browser', location:[200,200], size:[800,600], pack: true, show:true, iconImage: swing.imageIcon(groovy.ui.Console.ICON_PATH).image, defaultCloseOperation:WindowConstants.DISPOSE_ON_CLOSE) { menuBar { menu(text:'Help') { menuItem() {action(name:'About', closure: this.&showAbout)} } } panel() { borderLayout() panel( name:"Class Info", border: emptyBorder([5,10,5,10]), constraints:NORTH) { flowLayout(alignment:FlowLayout.LEFT) def props = inspector.classProps def classLabel = '' + props.join('
    ') label(classLabel) } tabbedPane(constraints:CENTER){ if (inspector.object instanceof Collection) { scrollPane(name: ' Collection data ') { itemTable = table() { int i = 0 def data = inspector.object.collect { val -> [i++, val] } tableModel(list:data) { closureColumn(header:'Index', read:{it[0]}) closureColumn(header:'Value', read:{it[1]}) } } } } if (inspector.object instanceof Map) { scrollPane(name: ' Map data ') { itemTable = table() { int i = 0 def data = inspector.object.collect { key, val -> [i++, key, val] } tableModel(list:data) { closureColumn(header:'Index', read:{it[0]}) closureColumn(header:'Key', read:{it[1]}) closureColumn(header:'Value', read:{it[2]}) } } } } scrollPane(name: ' Public Fields and Properties ') { fieldTable = table() { def data = Inspector.sort(inspector.publicFields.toList()) data.addAll(Inspector.sort(inspector.propertyInfo.toList())) tableModel(list:data) { closureColumn(header:'Name', read:{it[Inspector.MEMBER_NAME_IDX]}) closureColumn(header:'Value', read:{it[Inspector.MEMBER_VALUE_IDX]}) closureColumn(header:'Type', read:{it[Inspector.MEMBER_TYPE_IDX]}) closureColumn(header:'Origin', read:{it[Inspector.MEMBER_ORIGIN_IDX]}) closureColumn(header:'Modifier', read:{it[Inspector.MEMBER_MODIFIER_IDX]}) closureColumn(header:'Declarer', read:{it[Inspector.MEMBER_DECLARER_IDX]}) } } } scrollPane(name:' (Meta) Methods ' ) { methodTable = table() { def data = Inspector.sort(inspector.methods.toList()) data.addAll(Inspector.sort(inspector.metaMethods.toList())) tableModel(list:data) { closureColumn(header:'Name', read:{it[Inspector.MEMBER_NAME_IDX]}) closureColumn(header:'Params', read:{it[Inspector.MEMBER_PARAMS_IDX]}) closureColumn(header:'Type', read:{it[Inspector.MEMBER_TYPE_IDX]}) closureColumn(header:'Origin', read:{it[Inspector.MEMBER_ORIGIN_IDX]}) closureColumn(header:'Modifier', read:{it[Inspector.MEMBER_MODIFIER_IDX]}) closureColumn(header:'Declarer', read:{it[Inspector.MEMBER_DECLARER_IDX]}) closureColumn(header:'Exceptions', read:{it[Inspector.MEMBER_EXCEPTIONS_IDX]}) } } } } } } // Add a bit of formatting addSorter(itemTable) addSorter(mapTable) addSorter(fieldTable) addSorter(methodTable) frame.toFront() } void addSorter(table) { if (table != null) { def sorter = new TableSorter(table.model) table.model = sorter sorter.addMouseListenerToHeaderInTable(table) } } void showAbout(EventObject evt) { def pane = swing.optionPane() // work around GROOVY-1048 pane.setMessage('An interactive GUI to explore object capabilities.') def dialog = pane.createDialog(frame, 'About Groovy Object Browser') dialog.show() } } groovy-1.8.6/src/main/groovy/inspect/swingui/AstBrowser.groovy0000644001501200150120000004504011715031256024131 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui import groovy.swing.SwingBuilder import java.awt.Cursor import java.awt.Font import java.awt.event.KeyEvent import java.util.prefs.Preferences import javax.swing.JSplitPane import javax.swing.KeyStroke import javax.swing.UIManager import javax.swing.WindowConstants import javax.swing.event.TreeSelectionEvent import javax.swing.event.TreeSelectionListener import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreeNode import javax.swing.tree.TreeSelectionModel import org.codehaus.groovy.control.Phases import static java.awt.GridBagConstraints.* import java.awt.Component /** * This object is a GUI for looking at the AST that Groovy generates. * * Usage: java groovy.inspect.swingui.AstBrowser [filename] * where [filename] is an existing Groovy script. * * @author Hamlet D'Arcy (hamletdrc@gmail.com) * @author Guillaume Laforge, highlighting the code corresponding to a node selected in the tree view * @author Roshan Dawrani - separated out the swing UI related code from the model part so model could be used for various UIs */ public class AstBrowser { private inputArea, rootElement, decompiledSource, jTree, propertyTable, splitterPane, mainSplitter boolean showScriptFreeForm, showScriptClass, showTreeView GroovyClassLoader classLoader def prefs = new AstBrowserUiPreferences() AstBrowser(inputArea, rootElement, classLoader) { this.inputArea = inputArea this.rootElement = rootElement this.classLoader = classLoader } def swing, frame public static void main(args) { if (!args) { println "Usage: java groovy.inspect.swingui.AstBrowser [filename]\nwhere [filename] is a Groovy script" } else { def file = new File((String) args[0]) if (!file.exists()) { println "File $args[0] cannot be found." } else { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); new AstBrowser(null, null, new GroovyClassLoader()).run({file.text}, file.path) } } } void run(Closure script) { run(script, null) } void run(Closure script, String name) { swing = new SwingBuilder() def phasePicker showScriptFreeForm = prefs.showScriptFreeForm showScriptClass = prefs.showScriptClass showTreeView = prefs.showTreeView frame = swing.frame(title: 'Groovy AST Browser' + (name ? " - $name" : ''), location: prefs.frameLocation, size: prefs.frameSize, iconImage: swing.imageIcon(groovy.ui.Console.ICON_PATH).image, defaultCloseOperation: WindowConstants.DISPOSE_ON_CLOSE, windowClosing: { event -> prefs.save(frame, splitterPane, mainSplitter, showScriptFreeForm, showScriptClass, phasePicker.selectedItem, showTreeView) }) { menuBar { menu(text: 'Show Script', mnemonic: 'S') { checkBoxMenuItem(selected: showScriptFreeForm) { action(name: 'Free Form', closure: this.&showScriptFreeForm, mnemonic: 'F',) } checkBoxMenuItem(selected: showScriptClass) { action(name: 'Class Form', closure: this.&showScriptClass, mnemonic: 'C') } checkBoxMenuItem(selected: showTreeView) { action(name: 'Tree View', closure: this.&showTreeView, mnemonic: 'T') } } menu(text: 'View', mnemonic: 'V') { menuItem() {action(name: 'Larger Font', closure: this.&largerFont, mnemonic: 'L', accelerator: shortcut('shift L'))} menuItem() {action(name: 'Smaller Font', closure: this.&smallerFont, mnemonic: 'S', accelerator: shortcut('shift S'))} menuItem() { action(name: 'Refresh', closure: { decompile(phasePicker.selectedItem.phaseId, script()) compile(jTree, script(), phasePicker.selectedItem.phaseId) }, mnemonic: 'R', accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)) } } menu(text: 'Help', mnemonic: 'H') { menuItem() {action(name: 'About', closure: this.&showAbout, mnemonic: 'A')} } } panel { gridBagLayout() label(text: "At end of Phase: ", constraints: gbc(gridx: 0, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 0, weighty: 0, anchor: WEST, fill: HORIZONTAL, insets: [2, 2, 2, 2])) phasePicker = comboBox(items: CompilePhaseAdapter.values(), selectedItem: prefs.selectedPhase, actionPerformed: { decompile(phasePicker.selectedItem.phaseId, script()) compile(jTree, script(), phasePicker.selectedItem.phaseId) }, constraints: gbc(gridx: 1, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 1.0, weighty: 0, anchor: NORTHWEST, fill: NONE, insets: [2, 2, 2, 2])) button(text: 'Refresh', actionPerformed: { decompile(phasePicker.selectedItem.phaseId, script()) compile(jTree, script(), phasePicker.selectedItem.phaseId) }, constraints: gbc(gridx: 2, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 0, weighty: 0, anchor: NORTHEAST, fill: NONE, insets: [2, 2, 2, 3])) splitterPane = splitPane( visible: showTreeView, leftComponent: scrollPane() { jTree = tree( name: "AstTreeView", model: new DefaultTreeModel(new DefaultMutableTreeNode("Loading..."))) {} }, rightComponent: scrollPane() { propertyTable = table() { tableModel(list: [[:]]) { propertyColumn(header: 'Name', propertyName: 'name') propertyColumn(header: 'Value', propertyName: 'value') propertyColumn(header: 'Type', propertyName: 'type') } } } ) { } mainSplitter = splitPane( orientation: JSplitPane.VERTICAL_SPLIT, topComponent: splitterPane, bottomComponent: decompiledSource = new groovy.ui.ConsoleTextEditor(editable: false, showLineNumbers: false), constraints: gbc(gridx: 0, gridy: 2, gridwidth: 3, gridheight: 1, weightx: 1.0, weighty: 1.0, anchor: NORTHWEST, fill: BOTH, insets: [2, 2, 2, 2])) { } } } propertyTable.model.rows.clear() //for some reason this suppress an empty row jTree.cellRenderer.setLeafIcon(swing.imageIcon(groovy.ui.Console.NODE_ICON_PATH)); jTree.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION; jTree.addTreeSelectionListener({ TreeSelectionEvent e -> propertyTable.model.rows.clear() TreeNode node = jTree.lastSelectedPathComponent if (node instanceof TreeNodeWithProperties) { node.properties.each { propertyTable.model.rows << ["name": it[0], "value": it[1], "type": it[2]] } if (inputArea && rootElement) { // get the line / column information to select the text represented by the current selected node def lineInfo = node.properties.findAll { it[0] in ['lineNumber', 'columnNumber', 'lastLineNumber', 'lastColumnNumber'] } def lineInfoMap = lineInfo.inject([:]) { map, info -> map[(info[0])] = Integer.valueOf(info[1]); return map } // when there are valid line / column information (ie. != -1), create a selection in the input area if (!lineInfoMap.every { k, v -> v == -1 }) { def startOffset = rootElement.getElement(lineInfoMap.lineNumber - 1).startOffset inputArea.setCaretPosition(startOffset + lineInfoMap.columnNumber - 1) def endOffset = rootElement.getElement(lineInfoMap.lastLineNumber - 1).startOffset inputArea.moveCaretPosition(endOffset + lineInfoMap.lastColumnNumber - 1) } else { // if no line number is provided, unselect the current selection // but keep the caret at the same position inputArea.moveCaretPosition(inputArea.getCaretPosition()) } } } propertyTable.model.fireTableDataChanged() } as TreeSelectionListener) updateFontSize(prefs.decompiledSourceFontSize) frame.pack() frame.location = prefs.frameLocation frame.size = prefs.frameSize splitterPane.dividerLocation = prefs.verticalDividerLocation mainSplitter.dividerLocation = prefs.horizontalDividerLocation frame.show() String source = script() decompile(phasePicker.selectedItem.phaseId, source) compile(jTree, source, phasePicker.selectedItem.phaseId) jTree.rootVisible = false jTree.showsRootHandles = true // some OS's require this as a step to show nodes } void largerFont(EventObject evt = null) { updateFontSize(decompiledSource.textEditor.font.size + 2) } void smallerFont(EventObject evt = null) { updateFontSize(decompiledSource.textEditor.font.size - 2) } private updateFontSize = {newFontSize -> if (newFontSize > 40) { newFontSize = 40 } else if (newFontSize < 4) { newFontSize = 4 } prefs.decompiledSourceFontSize = newFontSize def newDecompilerFont = new Font(decompiledSource.textEditor.font.name, decompiledSource.textEditor.font.style, newFontSize) decompiledSource.textEditor.font = newDecompilerFont def newFont = new Font(jTree.cellRenderer.font.name, jTree.cellRenderer.font.style, newFontSize) jTree.cellRenderer.font = newFont jTree.model.reload(jTree.model.root) propertyTable.tableHeader.font = newFont propertyTable.font = newFont propertyTable.rowHeight = newFontSize + 2 } void showAbout(EventObject evt) { def pane = swing.optionPane() pane.setMessage('An interactive GUI to explore AST capabilities.') def dialog = pane.createDialog(frame, 'About Groovy AST Browser') dialog.show() } void showScriptFreeForm(EventObject evt) { showScriptFreeForm = evt.source.selected } void showScriptClass(EventObject evt) { showScriptClass = evt.source.selected } void showTreeView(EventObject evt = null) { showTreeView = !showTreeView splitterPane.visible = showTreeView if (showTreeView) { mainSplitter.dividerLocation = 100 } else { mainSplitter.dividerLocation = 0 } } void decompile(phaseId, source) { decompiledSource.textEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); decompiledSource.textEditor.text = 'Loading...'; swing.doOutside { try { String result = new AstNodeToScriptAdapter().compileToScript(source, phaseId, classLoader, showScriptFreeForm, showScriptClass) swing.doLater { decompiledSource.textEditor.text = result decompiledSource.textEditor.setCaretPosition(0) decompiledSource.textEditor.setCursor(Cursor.defaultCursor); } } catch (Throwable t) { swing.doLater { decompiledSource.textEditor.text = t.getMessage(); decompiledSource.textEditor.setCaretPosition(0) decompiledSource.textEditor.setCursor(Cursor.defaultCursor); } throw t } } } void compile(jTree, String script, int compilePhase) { jTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)) def model = jTree.model swing.edt { def root = model.getRoot(); root.removeAllChildren() root.add(new DefaultMutableTreeNode(new DefaultMutableTreeNode('Loading...'))); model.reload(root); } swing.doOutside { try { def nodeMaker = new SwingTreeNodeMaker() def adapter = new ScriptToTreeNodeAdapter(classLoader, showScriptFreeForm, showScriptClass, nodeMaker) def result = adapter.compile(script, compilePhase) swing.doLater { model.setRoot(result) model.reload() jTree.setCursor(Cursor.defaultCursor) } } catch (Throwable t) { swing.doLater { jTree.setCursor(Cursor.defaultCursor) } throw t } } } } /** * This class sets and restores control positions in the browser. * * @author Hamlet D'Arcy */ class AstBrowserUiPreferences { final def frameLocation final def frameSize final def verticalDividerLocation final def horizontalDividerLocation final boolean showScriptFreeForm final boolean showTreeView final boolean showScriptClass int decompiledSourceFontSize final CompilePhaseAdapter selectedPhase def AstBrowserUiPreferences() { Preferences prefs = Preferences.userNodeForPackage(AstBrowserUiPreferences) frameLocation = [ prefs.getInt("frameX", 200), prefs.getInt("frameY", 200)] frameSize = [ prefs.getInt("frameWidth", 800), prefs.getInt("frameHeight", 600)] decompiledSourceFontSize = prefs.getInt("decompiledFontSize", 12) verticalDividerLocation = Math.max(prefs.getInt("verticalSplitterLocation", 100), 100) horizontalDividerLocation = Math.max(prefs.getInt("horizontalSplitterLocation", 100), 100) showScriptFreeForm = prefs.getBoolean("showScriptFreeForm", false) showScriptClass = prefs.getBoolean("showScriptClass", true) showTreeView = prefs.getBoolean("showTreeView", true) int phase = prefs.getInt('compilerPhase', Phases.SEMANTIC_ANALYSIS) selectedPhase = CompilePhaseAdapter.values().find { it.phaseId == phase } } def save(frame, vSplitter, hSplitter, scriptFreeFormPref, scriptClassPref, CompilePhaseAdapter phase, showTreeView) { Preferences prefs = Preferences.userNodeForPackage(AstBrowserUiPreferences) prefs.putInt("decompiledFontSize", decompiledSourceFontSize as int) prefs.putInt("frameX", frame.location.x as int) prefs.putInt("frameY", frame.location.y as int) prefs.putInt("frameWidth", frame.size.width as int) prefs.putInt("frameHeight", frame.size.height as int) prefs.putInt("verticalSplitterLocation", vSplitter.dividerLocation) prefs.putInt("horizontalSplitterLocation", hSplitter.dividerLocation) prefs.putBoolean("showScriptFreeForm", scriptFreeFormPref) prefs.putBoolean("showScriptClass", scriptClassPref) prefs.putBoolean("showTreeView", showTreeView) prefs.putInt('compilerPhase', phase.phaseId) } } /** * An adapter for the CompilePhase enum that can be entered into a Swing combobox. * * @author Hamlet D'Arcy */ enum CompilePhaseAdapter { INITIALIZATION(Phases.INITIALIZATION, "Initialization"), PARSING(Phases.PARSING, "Parsing"), CONVERSION(Phases.CONVERSION, "Conversion"), SEMANTIC_ANALYSIS(Phases.SEMANTIC_ANALYSIS, "Semantic Analysis"), CANONICALIZATION(Phases.CANONICALIZATION, "Canonicalization"), INSTRUCTION_SELECTION(Phases.INSTRUCTION_SELECTION, "Instruction Selection"), CLASS_GENERATION(Phases.CLASS_GENERATION, "Class Generation"), OUTPUT(Phases.OUTPUT, "Output"), FINALIZATION(Phases.FINALIZATION, "Finalization") final int phaseId final String string def CompilePhaseAdapter(phaseId, string) { this.phaseId = phaseId this.string = string } public String toString() { return string } } /** * This class is a TreeNode and you can store additional properties on it. * * @author Hamlet D'Arcy */ class TreeNodeWithProperties extends DefaultMutableTreeNode { List> properties /** * Creates a tree node and attaches properties to it. * @param userObject same as a DefaultMutableTreeNode requires * @param properties a list of String lists */ def TreeNodeWithProperties(userObject, List> properties) { super(userObject) this.properties = properties } } /** * This interface is used to create tree nodes of various types * * @author Roshan Dawrani */ interface AstBrowserNodeMaker { T makeNode(Object userObject) T makeNodeWithProperties(Object userObject, List> properties) } /** * Creates tree nodes for swing UI * * @author Roshan Dawrani */ class SwingTreeNodeMaker implements AstBrowserNodeMaker { DefaultMutableTreeNode makeNode(Object userObject) { new DefaultMutableTreeNode(userObject) } DefaultMutableTreeNode makeNodeWithProperties(Object userObject, List> properties) { new TreeNodeWithProperties(userObject, properties) } } groovy-1.8.6/src/main/groovy/inspect/swingui/package.html0000644001501200150120000000026211627206702023047 0ustar miguelmiguel package groovy.inspect.swingui.*

    Classes associated with the Swing GUI for inspecting objects.

    groovy-1.8.6/src/main/groovy/inspect/swingui/AstBrowserProperties.groovy0000644001501200150120000000705311627206702026212 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui org { codehaus { groovy { ast { ClassNode = "ClassNode - \$expression.name" InnerClassNode = "InnerClassNode - \$expression.name" ConstructorNode = "ConstructorNode - \$expression.name" MethodNode = "MethodNode - \$expression.name" FieldNode = "FieldNode - \$expression.name : \$expression.type" PropertyNode = "PropertyNode - \${expression.field?.name} : \${expression.field?.type}" AnnotationNode = "AnnotationNode - \${expression.classNode?.name}" Parameter = "Parameter - \$expression.name" DynamicVariable = "DynamicVariable - \$expression.name" stmt { BlockStatement = "BlockStatement - (\${expression.statements ? expression.statements.size() : 0})" ExpressionStatement = "ExpressionStatement - \${expression?.expression.getClass().simpleName}" ReturnStatement = "ReturnStatement - \$expression.text" TryCatchStatement = "TryCatchStatement - \${expression.catchStatements?.size ?: 0} catch, \${expression.finallyStatement ? 1 : 0} finally" CatchStatement = "CatchStatement - \$expression.exceptionType]" } expr { ConstructorCallExpression = "ConstructorCall - \$expression.text" SpreadExpression = "Spread - \$expression.text" ArgumentListExpression = "ArgumentList - \$expression.text" MethodCallExpression = "MethodCall - \$expression.text" GStringExpression = "GString - \$expression.text" AttributeExpression = "Attribute - \$expression.text" DeclarationExpression = "Declaration - \$expression.text" VariableExpression = "Variable - \$expression.name : \$expression.type" ConstantExpression = "Constant - \$expression.value : \$expression.type" BinaryExpression = "Binary - \$expression.text" ClassExpression = "Class - \$expression.text" BooleanExpression = "Boolean - \$expression.text" ArrayExpression = "Array - \$expression.text" ListExpression = "List - \$expression.text" TupleExpression = "Tuple - \$expression.text" FieldExpression = "Field - \$expression.text" PropertyExpression = "Property - \$expression.propertyAsString" NotExpression = "Not - \$expression.text" CastExpression = "Cast - \$expression.text" } } } } } groovy-1.8.6/src/main/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy0000644001501200150120000007457111715030632026374 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.* import org.codehaus.groovy.ast.stmt.* import org.codehaus.groovy.classgen.BytecodeExpression import org.codehaus.groovy.control.CompilePhase import java.lang.reflect.Modifier import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.CompilationFailedException import org.codehaus.groovy.classgen.GeneratorContext import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation import org.codehaus.groovy.classgen.Verifier /** * This class takes Groovy source code, compiles it to a specific compile phase, and then decompiles it * back to the groovy source. It is used by GroovyConsole's AST Browser, but can also be invoked from * the command line. * * @author Hamlet D'Arcy */ public class AstNodeToScriptAdapter { /** * Run this class as a script to compile a groovy file and print out the resulting source. * @param args * a filename to compile and a CompilePhase to run to */ public static void main(args) { if (!args || args.length < 2) { println """ Usage: java groovy.inspect.swingui.AstNodeToScriptAdapter [filename] [compilephase] where [filename] is a Groovy script and [compilephase] is a valid Integer based org.codehaus.groovy.control.CompilePhase""" } else { def file = new File((String) args[0]) def phase = CompilePhase.fromPhaseNumber(args[1] as int) if (!file.exists()) { println "File ${args[0]} cannot be found." } else if (phase == null) { println "Compile phase ${args[1]} cannot be mapped to a org.codehaus.groovy.control.CompilePhase." } else { println new AstNodeToScriptAdapter().compileToScript(file.text, phase.getPhaseNumber()) } } } /** * This method takes source code, compiles it, then reverses it back to source. * @param script * the source code to be compiled. If invalid, a compile error occurs * @param compilePhase * the CompilePhase. Must be an int mapped in @{link CompilePhase} * @param classLoader * (optional) the classloader to use. If missing/null then the current is used. * This parameter enables things like ASTBrowser to invoke this with the correct classpath * @param showScriptFreeForm * Whether or not to show the script portion of the source code * @param showScriptClass * Whether or not to show the Script class from the source code * @returns the source code from the AST state */ public String compileToScript(String script, int compilePhase, ClassLoader classLoader = null, boolean showScriptFreeForm = true, boolean showScriptClass = true) { def writer = new StringWriter() classLoader = classLoader ?: new GroovyClassLoader(getClass().classLoader) def scriptName = "script" + System.currentTimeMillis() + ".groovy" GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptName, "/groovy/script") CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.codeSource, classLoader) cu.addPhaseOperation(new AstNodeToScriptVisitor(writer, showScriptFreeForm, showScriptClass), compilePhase) cu.addSource(codeSource.getName(), script); try { cu.compile(compilePhase) } catch (CompilationFailedException cfe) { writer.println "Unable to produce AST for this phase due to earlier compilation error:" cfe.message.eachLine { writer.println it } writer.println "Fix the above error(s) and then press Refresh" } catch (Throwable t) { writer.println "Unable to produce AST for this phase due to an error:" writer.println t.getMessage() writer.println "Fix the above error(s) and then press Refresh" } return writer.toString() } } /** * An adapter from ASTNode tree to source code. * * @author Hamlet D'Arcy */ class AstNodeToScriptVisitor extends PrimaryClassNodeOperation implements GroovyCodeVisitor, GroovyClassVisitor { private Writer _out Stack classNameStack = new Stack(); String _indent = "" boolean readyToIndent = true boolean showScriptFreeForm boolean showScriptClass boolean scriptHasBeenVisited def AstNodeToScriptVisitor(Writer writer, boolean showScriptFreeForm = true, boolean showScriptClass = true) { this._out = writer; this.showScriptFreeForm = showScriptFreeForm this.showScriptClass = showScriptClass this.scriptHasBeenVisited = false } void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { visitPackage(source?.getAST()?.getPackage()) visitAllImports(source) if (showScriptFreeForm && !scriptHasBeenVisited) { scriptHasBeenVisited = true source?.getAST()?.getStatementBlock()?.visit(this) } if (showScriptClass || !classNode.isScript()) { visitClass classNode } } private def visitAllImports(SourceUnit source) { boolean staticImportsPresent = false boolean importsPresent = false source?.getAST()?.getStaticImports()?.values()?.each { visitImport(it) staticImportsPresent = true } source?.getAST()?.getStaticStarImports()?.values()?.each { visitImport(it) staticImportsPresent = true } if (staticImportsPresent) { printDoubleBreak() } source?.getAST()?.getImports()?.each { visitImport(it) importsPresent = true } source?.getAST()?.getStarImports()?.each { visitImport(it) importsPresent = true } if (importsPresent) { printDoubleBreak() } } void print(parameter) { def output = parameter.toString() if (readyToIndent) { _out.print _indent readyToIndent = false while (output.startsWith(' ')) { output = output[1..-1] // trim left } } if (_out.toString().endsWith(' ')) { if (output.startsWith(' ')) { output = output[1..-1] } } _out.print output } def println(parameter) { throw new UnsupportedOperationException('Wrong API') } def indented(Closure block) { String startingIndent = _indent _indent = _indent + " " block() _indent = startingIndent } def printLineBreak() { if (!_out.toString().endsWith('\n')) { _out.print '\n' } readyToIndent = true } def printDoubleBreak() { if (_out.toString().endsWith('\n\n')) { // do nothing } else if (_out.toString().endsWith('\n')) { _out.print '\n' } else { _out.print '\n' _out.print '\n' } readyToIndent = true } void visitPackage(PackageNode packageNode) { if (packageNode) { packageNode.annotations?.each { visitAnnotationNode(it) printLineBreak() } if (packageNode.text.endsWith(".")) { print packageNode.text[0..-2] } else { print packageNode.text } printDoubleBreak() } } void visitImport(ImportNode node) { if (node) { node.annotations?.each { visitAnnotationNode(it) printLineBreak() } print node.text printLineBreak() } } @Override public void visitClass(ClassNode node) { classNameStack.push(node.name) node?.annotations?.each { visitAnnotationNode(it) printLineBreak() } visitModifiers(node.modifiers) print "class $node.name" visitGenerics node?.genericsTypes boolean first = true node.interfaces?.each { if (!first) { print ', ' } else { print ' implements ' } first = false visitType it } print ' extends ' visitType node.superClass print " { " printDoubleBreak() indented { node?.properties?.each { visitProperty(it) } printLineBreak() node?.fields?.each { visitField(it) } printDoubleBreak() node?.declaredConstructors?.each { visitConstructor(it) } printLineBreak() node?.methods?.each { visitMethod(it) } } print '}' printLineBreak() classNameStack.pop() } private void visitGenerics(GenericsType[] generics) { if (generics) { print '<' boolean first = true generics.each { GenericsType it -> if (!first) { print ', ' } first = false print it.name if (it.upperBounds) { print ' extends ' boolean innerFirst = true it.upperBounds.each { ClassNode upperBound -> if (!innerFirst) { print ' & ' } innerFirst = false visitType upperBound } } if (it.lowerBound) { print ' super ' visitType it.lowerBound } } print '>' } } @Override public void visitConstructor(ConstructorNode node) { visitMethod(node) } private String visitParameters(parameters) { boolean first = true parameters.each { Parameter it -> if (!first) { print ', ' } first = false it.annotations?.each { visitAnnotationNode(it) print(' ') } visitModifiers(it.modifiers) visitType it.type print ' ' + it.name if (it.initialExpression && !(it.initialExpression instanceof EmptyExpression)) { print ' = ' it.initialExpression.visit this } } } @Override public void visitMethod(MethodNode node) { node?.annotations?.each { visitAnnotationNode(it) printLineBreak() } visitModifiers(node.modifiers) if (node.name == '') { print "${classNameStack.peek()}(" visitParameters(node.parameters) print ") {" printLineBreak() } else if (node.name == '') { print 'static { ' printLineBreak() } else { visitType node.returnType print " $node.name(" visitParameters(node.parameters) print ")" if (node.exceptions) { boolean first = true print ' throws ' node.exceptions.each { if (!first) { print ', ' } first = false visitType it } } print " {" printLineBreak() } indented { node?.code?.visit(this) } printLineBreak() print '}' printDoubleBreak() } private def visitModifiers(int modifiers) { if (Modifier.isAbstract(modifiers)) { print 'abstract ' } if (Modifier.isFinal(modifiers)) { print 'final ' } if (Modifier.isInterface(modifiers)) { print 'interface ' } if (Modifier.isNative(modifiers)) { print 'native ' } if (Modifier.isPrivate(modifiers)) { print 'private ' } if (Modifier.isProtected(modifiers)) { print 'protected ' } if (Modifier.isPublic(modifiers)) { print 'public ' } if (Modifier.isStatic(modifiers)) { print 'static ' } if (Modifier.isSynchronized(modifiers)) { print 'synchronized ' } if (Modifier.isTransient(modifiers)) { print 'transient ' } if (Modifier.isVolatile(modifiers)) { print 'volatile ' } } @Override public void visitField(FieldNode node) { node?.annotations?.each { visitAnnotationNode(it) printLineBreak() } visitModifiers(node.modifiers) visitType node.type print " $node.name " // do not print initial expression, as this is executed as part of the constructor, unless on static constant Expression exp = node.initialValueExpression if (exp instanceof ConstantExpression) exp = Verifier.transformToPrimitiveConstantIfPossible(exp) ClassNode type = exp?.type if (Modifier.isStatic(node.modifiers) && Modifier.isFinal(node.getModifiers()) && exp instanceof ConstantExpression && type == node.type && ClassHelper.isStaticConstantInitializerType(type)) { // GROOVY-5150: final constants may be initialized directly print " = " if (ClassHelper.STRING_TYPE == type) { print "'"+node.initialValueExpression.text.replaceAll("'", "\\\\'")+"'" } else if (ClassHelper.char_TYPE == type) { print "'${node.initialValueExpression.text}'" } else { print node.initialValueExpression.text } } printLineBreak() } public void visitAnnotationNode(AnnotationNode node) { print '@' + node?.classNode?.name if (node?.members) { print '(' boolean first = true node.members.each { String name, Expression value -> if (first) { first = false } else { print ', ' } print name + ' = ' value.visit(this) } print ')' } } @Override public void visitProperty(PropertyNode node) { // is a FieldNode, avoid double dispatch } @Override public void visitBlockStatement(BlockStatement block) { block?.statements?.each { it.visit(this); printLineBreak() } if (!_out.toString().endsWith('\n')) { printLineBreak() } } @Override public void visitForLoop(ForStatement statement) { print 'for (' if (statement?.variable != ForStatement.FOR_LOOP_DUMMY) { visitParameters([statement.variable]) print ' : ' } if (statement?.collectionExpression instanceof ListExpression) { statement?.collectionExpression?.visit this } else { statement?.collectionExpression?.visit this } print ') {' printLineBreak() indented { statement?.loopBlock?.visit this } print '}' printLineBreak() } @Override public void visitIfElse(IfStatement ifElse) { print 'if (' ifElse?.booleanExpression?.visit this print ') {' printLineBreak() indented { ifElse?.ifBlock?.visit this } printLineBreak() if (ifElse?.elseBlock && !(ifElse.elseBlock instanceof EmptyStatement)) { print "} else {" printLineBreak() indented { ifElse?.elseBlock?.visit this } printLineBreak() } print '}' printLineBreak() } @Override public void visitExpressionStatement(ExpressionStatement statement) { statement.expression.visit this } @Override public void visitReturnStatement(ReturnStatement statement) { printLineBreak() print "return " statement.getExpression().visit(this); printLineBreak() } @Override public void visitSwitch(SwitchStatement statement) { print 'switch (' statement?.expression?.visit this print ') {' printLineBreak() indented { statement?.caseStatements?.each { visitCaseStatement it } if (statement?.defaultStatement) { print 'default: ' printLineBreak() statement?.defaultStatement?.visit this } } print '}' printLineBreak() } @Override public void visitCaseStatement(CaseStatement statement) { print 'case ' statement?.expression?.visit this print ':' printLineBreak() indented { statement?.code?.visit this } } @Override public void visitBreakStatement(BreakStatement statement) { print 'break' printLineBreak() } @Override public void visitContinueStatement(ContinueStatement statement) { print 'continue' printLineBreak() } @Override public void visitMethodCallExpression(MethodCallExpression expression) { Expression objectExp = expression.getObjectExpression() if (objectExp instanceof VariableExpression) { visitVariableExpression(objectExp, false) } else { objectExp.visit(this); } if (expression.spreadSafe) { print '*' } if (expression.safe) { print '?' } print '.' Expression method = expression.getMethod() if (method instanceof ConstantExpression) { visitConstantExpression(method, true) } else { method.visit(this); } expression.getArguments().visit(this) } @Override public void visitStaticMethodCallExpression(StaticMethodCallExpression expression) { print expression?.ownerType?.name + "." + expression?.method if (expression?.arguments instanceof VariableExpression) { print '(' expression?.arguments?.visit this print ')' } else { expression?.arguments?.visit this } } @Override public void visitConstructorCallExpression(ConstructorCallExpression expression) { if (expression?.isSuperCall()) { print 'super' } else if (expression?.isThisCall()) { print 'this ' } else { print 'new ' visitType expression?.type } expression?.arguments?.visit this } @Override public void visitBinaryExpression(BinaryExpression expression) { expression?.leftExpression?.visit this print " $expression.operation.text " expression.rightExpression.visit this if (expression?.operation?.text == '[') { print ']' } } @Override public void visitPostfixExpression(PostfixExpression expression) { print '(' expression?.expression?.visit this print ')' print expression?.operation?.text } @Override public void visitPrefixExpression(PrefixExpression expression) { print expression?.operation?.text print '(' expression?.expression?.visit this print ')' } @Override public void visitClosureExpression(ClosureExpression expression) { print '{ ' if (expression?.parameters) { visitParameters(expression?.parameters) print ' ->' } printLineBreak() indented { expression?.code?.visit this } print '}' } @Override public void visitTupleExpression(TupleExpression expression) { print '(' visitExpressionsAndCommaSeparate(expression?.expressions) print ')' } @Override public void visitRangeExpression(RangeExpression expression) { print '(' expression?.from?.visit this print '..' expression?.to?.visit this print ')' } @Override public void visitPropertyExpression(PropertyExpression expression) { expression?.objectExpression?.visit this if (expression?.spreadSafe) { print '*' } else if (expression?.isSafe()) { print '?' } print '.' if (expression?.property instanceof ConstantExpression) { visitConstantExpression(expression?.property, true) } else { expression?.property?.visit this } } @Override public void visitAttributeExpression(AttributeExpression attributeExpression) { visitPropertyExpression attributeExpression } @Override public void visitFieldExpression(FieldExpression expression) { print expression?.field?.name } @Override public void visitConstantExpression(ConstantExpression expression, boolean unwrapQuotes = false) { if (expression.value instanceof String && !unwrapQuotes) { // string reverse escaping is very naive def escaped = ((String) expression.value).replaceAll('\n', '\\\\n').replaceAll("'", "\\\\'") print "'$escaped'" } else { print expression.value } } @Override public void visitClassExpression(ClassExpression expression) { print expression.text } @Override public void visitVariableExpression(VariableExpression expression, boolean spacePad = true) { if (spacePad) { print ' ' + expression.name + ' ' } else { print expression.name } } @Override public void visitDeclarationExpression(DeclarationExpression expression) { // handle multiple assignment expressions if (expression?.leftExpression instanceof ArgumentListExpression) { print 'def ' visitArgumentlistExpression expression?.leftExpression, true print " $expression.operation.text " expression.rightExpression.visit this if (expression?.operation?.text == '[') { print ']' } } else { visitType expression?.leftExpression?.type visitBinaryExpression expression // is a BinaryExpression } } @Override public void visitGStringExpression(GStringExpression expression) { print '"' + expression.text + '"' } @Override public void visitSpreadExpression(SpreadExpression expression) { print '*' expression?.expression?.visit this } @Override public void visitNotExpression(NotExpression expression) { print '!(' expression?.expression?.visit this print ')' } @Override public void visitUnaryMinusExpression(UnaryMinusExpression expression) { print '-(' expression?.expression?.visit this print ')' } @Override public void visitUnaryPlusExpression(UnaryPlusExpression expression) { print '+(' expression?.expression?.visit this print ')' } @Override public void visitCastExpression(CastExpression expression) { print '((' expression?.expression?.visit this print ') as ' visitType(expression?.type) print ')' } /** * Prints out the type, safely handling arrays. * @param classNode * classnode */ public void visitType(ClassNode classNode) { def name = classNode.name if (name =~ /^\[+L/ && name.endsWith(";")) { int numDimensions = name.indexOf('L') print "${classNode.name[(numDimensions + 1)..-2]}" + ('[]' * numDimensions) } else { print name } visitGenerics classNode?.genericsTypes } @Override public void visitArgumentlistExpression(ArgumentListExpression expression, boolean showTypes = false) { print '(' int count = expression?.expressions?.size() expression.expressions.each { if (showTypes) { visitType it.type print ' ' } if (it instanceof VariableExpression) { visitVariableExpression it, false } else if (it instanceof ConstantExpression) { visitConstantExpression it, false } else { it.visit this } count-- if (count) print ', ' } print ')' } @Override public void visitBytecodeExpression(BytecodeExpression expression) { print "/*BytecodeExpression*/" printLineBreak() } @Override public void visitMapExpression(MapExpression expression) { print '[' visitExpressionsAndCommaSeparate(expression?.mapEntryExpressions) print ']' } @Override public void visitMapEntryExpression(MapEntryExpression expression) { if (expression?.keyExpression instanceof SpreadMapExpression) { print '*' // is this correct? } else { expression?.keyExpression?.visit this } print ': ' expression?.valueExpression?.visit this } @Override public void visitListExpression(ListExpression expression) { print '[' visitExpressionsAndCommaSeparate(expression?.expressions) print ']' } @Override public void visitTryCatchFinally(TryCatchStatement statement) { print 'try {' printLineBreak() indented { statement?.tryStatement?.visit this } printLineBreak() print '} ' printLineBreak() statement?.catchStatements?.each { CatchStatement catchStatement -> visitCatchStatement(catchStatement) } print 'finally { ' printLineBreak() indented { statement?.finallyStatement?.visit this } print '} ' printLineBreak() } @Override public void visitThrowStatement(ThrowStatement statement) { print 'throw ' statement?.expression?.visit this printLineBreak() } @Override public void visitSynchronizedStatement(SynchronizedStatement statement) { print 'synchronized (' statement?.expression?.visit this print ') {' printLineBreak() indented { statement?.code?.visit this } print '}' } @Override public void visitTernaryExpression(TernaryExpression expression) { expression?.booleanExpression?.visit this print ' ? ' expression?.trueExpression?.visit this print ' : ' expression?.falseExpression?.visit this } @Override public void visitShortTernaryExpression(ElvisOperatorExpression expression) { visitTernaryExpression(expression) } @Override public void visitBooleanExpression(BooleanExpression expression) { expression?.expression?.visit this } @Override public void visitWhileLoop(WhileStatement statement) { print 'while (' statement?.booleanExpression?.visit this print ') {' printLineBreak() indented { statement?.loopBlock?.visit this } printLineBreak() print '}' printLineBreak() } @Override public void visitDoWhileLoop(DoWhileStatement statement) { print 'do {' printLineBreak() indented { statement?.loopBlock?.visit this } print '} while (' statement?.booleanExpression?.visit this print ')' printLineBreak() } @Override public void visitCatchStatement(CatchStatement statement) { print 'catch (' visitParameters([statement.variable]) print ') {' printLineBreak() indented { statement.code?.visit this } print '} ' printLineBreak() } @Override public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) { print '~(' expression?.expression?.visit this print ') ' } @Override public void visitAssertStatement(AssertStatement statement) { print 'assert ' statement?.booleanExpression?.visit this print ' : ' statement?.messageExpression?.visit this } @Override public void visitClosureListExpression(ClosureListExpression expression) { boolean first = true expression?.expressions?.each { if (!first) { print ';' } first = false it.visit this } } @Override public void visitMethodPointerExpression(MethodPointerExpression expression) { expression?.expression?.visit this print '.&' expression?.methodName?.visit this } @Override public void visitArrayExpression(ArrayExpression expression) { print 'new ' visitType expression?.elementType print '[' visitExpressionsAndCommaSeparate(expression?.sizeExpression) print ']' } private void visitExpressionsAndCommaSeparate(List expressions) { boolean first = true expressions?.each { if (!first) { print ', ' } first = false it.visit this } } @Override public void visitSpreadMapExpression(SpreadMapExpression expression) { print '*:' expression?.expression?.visit this } } groovy-1.8.6/src/main/groovy/inspect/swingui/TableSorter.java0000644001501200150120000002615111713765676023704 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui; /** * A sorter for TableModels. The sorter has a model (conforming to TableModel) * and itself implements TableModel. TableSorter does not store or copy * the data in the TableModel, instead it maintains an array of * integers which it keeps the same size as the number of rows in its * model. When the model changes it notifies the sorter that something * has changed eg. "rowsAdded" so that its internal array of integers * can be reallocated. As requests are made of the sorter (like * getValueAt(row, col) it redirects them to its model via the mapping * array. That way the TableSorter appears to hold another copy of the table * with the rows in a different order. The sorting algorithm used is stable * which means that it does not move around rows when its comparison * function returns 0 to denote that they are equivalent. * * @version 1.12 01/23/03 * @author Philip Milne * @author Minimal adjustments by Dierk Koenig, June 2005 */ import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Date; import java.util.Vector; public class TableSorter extends TableMap { int indexes[]; Vector sortingColumns = new Vector(); boolean ascending = true; int lastSortedColumn = -1; public TableSorter() { indexes = new int[0]; // For consistency. } public TableSorter(TableModel model) { setModel(model); } public void setModel(TableModel model) { super.setModel(model); reallocateIndexes(); } public int compareRowsByColumn(int row1, int row2, int column) { Class type = model.getColumnClass(column); TableModel data = model; // Check for nulls Object o1 = data.getValueAt(row1, column); Object o2 = data.getValueAt(row2, column); // If both values are null return 0 if (o1 == null && o2 == null) { return 0; } else if (o1 == null) { // Define null less than everything. return -1; } else if (o2 == null) { return 1; } /* We copy all returned values from the getValue call in case an optimised model is reusing one object to return many values. The Number subclasses in the JDK are immutable and so will not be used in this way but other subclasses of Number might want to do this to save space and avoid unnecessary heap allocation. */ if (type.getSuperclass() == java.lang.Number.class) { return compareNumbers(data, row1, column, row2); } if (type == java.util.Date.class) { return compareDates(data, row1, column, row2); } if (type == String.class) { return compareStrings(data, row1, column, row2); } if (type == Boolean.class) { return compareBooleans(data, row1, column, row2); } return compareObjects(data, row1, column, row2); } private int compareObjects(TableModel data, int row1, int column, int row2) { Object v1 = data.getValueAt(row1, column); String s1 = v1.toString(); Object v2 = data.getValueAt(row2, column); String s2 = v2.toString(); int result = s1.compareTo(s2); if (result < 0) return -1; if (result > 0) return 1; return 0; } private int compareBooleans(TableModel data, int row1, int column, int row2) { Boolean bool1 = (Boolean) data.getValueAt(row1, column); boolean b1 = bool1.booleanValue(); Boolean bool2 = (Boolean) data.getValueAt(row2, column); boolean b2 = bool2.booleanValue(); if (b1 == b2) return 0; if (b1) // Define false < true return 1; return -1; } private int compareStrings(TableModel data, int row1, int column, int row2) { String s1 = (String) data.getValueAt(row1, column); String s2 = (String) data.getValueAt(row2, column); int result = s1.compareTo(s2); if (result < 0) return -1; if (result > 0) return 1; return 0; } private int compareDates(TableModel data, int row1, int column, int row2) { Date d1 = (Date) data.getValueAt(row1, column); long n1 = d1.getTime(); Date d2 = (Date) data.getValueAt(row2, column); long n2 = d2.getTime(); if (n1 < n2) return -1; if (n1 > n2) return 1; return 0; } private int compareNumbers(TableModel data, int row1, int column, int row2) { Number n1 = (Number) data.getValueAt(row1, column); double d1 = n1.doubleValue(); Number n2 = (Number) data.getValueAt(row2, column); double d2 = n2.doubleValue(); if (d1 < d2) return -1; if (d1 > d2) return 1; return 0; } public int compare(int row1, int row2) { for (int level = 0; level < sortingColumns.size(); level++) { Integer column = (Integer) sortingColumns.elementAt(level); int result = compareRowsByColumn(row1, row2, column.intValue()); if (result != 0) return ascending ? result : -result; } return 0; } public void reallocateIndexes() { int rowCount = model.getRowCount(); // Set up a new array of indexes with the right number of elements // for the new data model. indexes = new int[rowCount]; // Initialise with the identity mapping. for (int row = 0; row < rowCount; row++) indexes[row] = row; } public void tableChanged(TableModelEvent e) { reallocateIndexes(); super.tableChanged(e); } public void checkModel() { if (indexes.length != model.getRowCount()) { System.err.println("Sorter not informed of a change in model."); } } public void sort(Object sender) { checkModel(); shuttlesort((int[]) indexes.clone(), indexes, 0, indexes.length); } public void n2sort() { for (int i = 0; i < getRowCount(); i++) { for (int j = i + 1; j < getRowCount(); j++) { if (compare(indexes[i], indexes[j]) == -1) { swap(i, j); } } } } // This is a home-grown implementation which we have not had time // to research - it may perform poorly in some circumstances. It // requires twice the space of an in-place algorithm and makes // NlogN assignments shuttling the values between the two // arrays. The number of compares appears to vary between N-1 and // NlogN depending on the initial order but the main reason for // using it here is that, unlike qsort, it is stable. public void shuttlesort(int from[], int to[], int low, int high) { if (high - low < 2) { return; } int middle = (low + high) / 2; shuttlesort(to, from, low, middle); shuttlesort(to, from, middle, high); int p = low; int q = middle; /* This is an optional short-cut; at each recursive call, check to see if the elements in this subset are already ordered. If so, no further comparisons are needed; the sub-array can just be copied. The array must be copied rather than assigned otherwise sister calls in the recursion might get out of sync. When the number of elements is three they are partitioned so that the first set, [low, mid), has one element and and the second, [mid, high), has two. We skip the optimisation when the number of elements is three or less as the first compare in the normal merge will produce the same sequence of steps. This optimisation seems to be worthwhile for partially ordered lists but some analysis is needed to find out how the performance drops to Nlog(N) as the initial order diminishes - it may drop very quickly. */ if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) { System.arraycopy(from, low, to, low, high - low); return; } // A normal merge. for (int i = low; i < high; i++) { if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) { to[i] = from[p++]; } else { to[i] = from[q++]; } } } public void swap(int i, int j) { int tmp = indexes[i]; indexes[i] = indexes[j]; indexes[j] = tmp; } // The mapping only affects the contents of the data rows. // Pass all requests to these rows through the mapping array: "indexes". public Object getValueAt(int aRow, int aColumn) { checkModel(); return model.getValueAt(indexes[aRow], aColumn); } public void setValueAt(Object aValue, int aRow, int aColumn) { checkModel(); model.setValueAt(aValue, indexes[aRow], aColumn); } public void sortByColumn(int column) { sortByColumn(column, true); } public void sortByColumn(int column, boolean ascending) { this.ascending = ascending; sortingColumns.removeAllElements(); sortingColumns.addElement(Integer.valueOf(column)); sort(this); super.tableChanged(new TableModelEvent(this)); } // There is no-where else to put this. // Add a mouse listener to the Table to trigger a table sort // when a column heading is clicked in the JTable. public void addMouseListenerToHeaderInTable(JTable table) { final TableSorter sorter = this; final JTable tableView = table; tableView.setColumnSelectionAllowed(false); MouseAdapter listMouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (e.getClickCount() == 1 && column != -1) { if (lastSortedColumn == column) ascending = !ascending; sorter.sortByColumn(column, ascending); lastSortedColumn = column; } } }; JTableHeader th = tableView.getTableHeader(); th.addMouseListener(listMouseListener); } } groovy-1.8.6/src/main/groovy/inspect/swingui/ScriptToTreeNodeAdapter.groovy0000644001501200150120000005624111715031256026541 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui import groovy.text.GStringTemplateEngine import groovy.text.Template import java.util.concurrent.atomic.AtomicBoolean import org.codehaus.groovy.GroovyBugError import org.codehaus.groovy.classgen.BytecodeExpression import org.codehaus.groovy.classgen.GeneratorContext import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.* import org.codehaus.groovy.ast.stmt.* import org.codehaus.groovy.control.CompilationFailedException /** * This class controls the conversion from a Groovy script as a String into * a tree representation of the AST of that script. The script itself * will be a tree node, and each class in the script will be a tree node. The * conversion creates tree nodes for any concrete class found within an AST * visitor. So, if a tree node should be shown once for each ASTNode and the parent * types will not appear as nodes. Custom subclasses of expression types will * not appear in the tree. * * The String label of a tree node is defined by classname in AstBrowserProperties.properties. * * @author Hamlet D'Arcy * @author Roshan Dawrani */ class ScriptToTreeNodeAdapter { def static Properties classNameToStringForm boolean showScriptFreeForm, showScriptClass final GroovyClassLoader classLoader final AstBrowserNodeMaker nodeMaker static { try { URL url = ClassLoader.getSystemResource("groovy/inspect/swingui/AstBrowserProperties.groovy") def config = new ConfigSlurper().parse(url) classNameToStringForm = config.toProperties() String home = System.getProperty("user.home") if (home) { File userFile = new File(home + File.separator + ".groovy/AstBrowserProperties.groovy") if (userFile.exists()) { def customConfig = new ConfigSlurper().parse(userFile.toURL()) // layer custom string forms onto defaults with putAll, do not replace them classNameToStringForm.putAll(customConfig.toProperties()) } } }catch(ex) { // on restricted environments like, such calls may fail, but that should not prevent the class // from being loaded. Tree nodes can still get rendered with their simple names. classNameToStringForm = new Properties() } } def ScriptToTreeNodeAdapter(classLoader, showScriptFreeForm, showScriptClass, nodeMaker) { this.classLoader = classLoader ?: new GroovyClassLoader(getClass().classLoader) this.showScriptFreeForm = showScriptFreeForm this.showScriptClass = showScriptClass this.nodeMaker = nodeMaker } /** * Performs the conversion from script to TreeNode. * * @param script * a Groovy script in String form * @param compilePhase * the int based CompilePhase to compile it to. */ def compile(String script, int compilePhase) { def scriptName = "script" + System.currentTimeMillis() + ".groovy" GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptName, "/groovy/script") CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.codeSource, classLoader) TreeNodeBuildingNodeOperation operation = new TreeNodeBuildingNodeOperation(this, showScriptFreeForm, showScriptClass) cu.addPhaseOperation(operation, compilePhase) cu.addSource(codeSource.getName(), script); try { cu.compile(compilePhase) } catch (CompilationFailedException cfe) { operation.root.add(nodeMaker.makeNode("Unable to produce AST for this phase due to earlier compilation error:")) cfe.message.eachLine { operation.root.add(nodeMaker.makeNode(it)) } operation.root.add(nodeMaker.makeNode("Fix the above error(s) and then press Refresh")) } catch (Throwable t) { operation.root.add(nodeMaker.makeNode("Unable to produce AST for this phase due to an error:")) operation.root.add(nodeMaker.makeNode(t)) operation.root.add(nodeMaker.makeNode("Fix the above error(s) and then press Refresh")) } return operation.root } def make(node) { nodeMaker.makeNodeWithProperties(getStringForm(node), getPropertyTable(node)) } /** * Creates the property table for the node so that the properties view can display nicely. */ private List> getPropertyTable(node) { node.metaClass.properties?. findAll { it.getter }?. collect { def name = it.name.toString() def value try { // multiple assignment statements cannot be cast to VariableExpression so // instead reference the value through the leftExpression property, which is the same if (node instanceof DeclarationExpression && (name == 'variableExpression' || name == 'tupleExpression')) { value = node.leftExpression.toString() } else { value = it.getProperty(node).toString() } } catch (GroovyBugError reflectionArtefact) { // compiler throws error if it thinks a field is being accessed // before it is set under certain conditions. It wasn't designed // to be walked reflectively like this. value = null } def type = it.type.simpleName.toString() [name, value, type] }?. sort() { it[0] } } /** * Handles the property file templating for node types. */ private String getStringForm(node) { def templateTextForNode = classNameToStringForm[node.class.name] if (templateTextForNode) { GStringTemplateEngine engine = new GStringTemplateEngine() Template template = engine.createTemplate(templateTextForNode) Writable writable = template.make([expression: node]) StringWriter result = new StringWriter() writable.writeTo(result) result.toString() } else { node.class.simpleName } } } /** * This Node Operation builds up a root tree node for the viewer. * @author Hamlet D'Arcy */ private class TreeNodeBuildingNodeOperation extends PrimaryClassNodeOperation { final def root final def sourceCollected = new AtomicBoolean(false) final ScriptToTreeNodeAdapter adapter final def showScriptFreeForm final def showScriptClass final def nodeMaker def TreeNodeBuildingNodeOperation(ScriptToTreeNodeAdapter adapter, showScriptFreeForm, showScriptClass) { if (!adapter) throw new IllegalArgumentException("Null: adapter") this.adapter = adapter this.showScriptFreeForm = showScriptFreeForm this.showScriptClass = showScriptClass nodeMaker = adapter.nodeMaker root = nodeMaker.makeNode("root") } public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { // module node if (!sourceCollected.getAndSet(true) && showScriptFreeForm) { // display the source unit AST ModuleNode ast = source.getAST() TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) ast.getStatementBlock().visit(visitor) if (visitor.currentNode) root.add(visitor.currentNode) collectModuleNodeMethodData("Methods", ast.getMethods()) } if(classNode.isScript() && !showScriptClass) return def child = adapter.make(classNode) root.add(child) collectConstructorData(child, "Constructors", classNode) collectMethodData(child, "Methods", classNode) collectFieldData(child, "Fields", classNode) collectPropertyData(child, "Properties", classNode) collectAnnotationData(child, "Annotations", classNode) } private List collectAnnotationData(parent, String name, ClassNode classNode) { def allAnnotations = nodeMaker.makeNode(name) if (classNode.annotations) parent.add(allAnnotations) classNode.annotations?.each {AnnotationNode annotationNode -> def ggrandchild = adapter.make(annotationNode) allAnnotations.add(ggrandchild) } } private def collectPropertyData(parent, String name, ClassNode classNode) { def allProperties = nodeMaker.makeNode(name) if (classNode.properties) parent.add(allProperties) classNode.properties?.each {PropertyNode propertyNode -> def ggrandchild = adapter.make(propertyNode) allProperties.add(ggrandchild) TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) if (propertyNode.field?.initialValueExpression) { propertyNode.field.initialValueExpression.visit(visitor) ggrandchild.add(visitor.currentNode) } } } private def collectFieldData(parent, String name, ClassNode classNode) { def allFields = nodeMaker.makeNode(name) if (classNode.fields) parent.add(allFields) classNode.fields?.each {FieldNode fieldNode -> def ggrandchild = adapter.make(fieldNode) allFields.add(ggrandchild) TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) if (fieldNode.initialValueExpression) { fieldNode.initialValueExpression.visit(visitor) if (visitor.currentNode) ggrandchild.add(visitor.currentNode) } } } private def collectMethodData(parent, String name, ClassNode classNode) { def allMethods = nodeMaker.makeNode(name) if (classNode.methods) parent.add(allMethods) doCollectMethodData(allMethods, classNode.methods) } private def collectModuleNodeMethodData(String name, List methods) { if(!methods) return def allMethods = nodeMaker.makeNode(name) root.add(allMethods) doCollectMethodData(allMethods, methods) } private def doCollectMethodData(allMethods, List methods) { methods?.each {MethodNode methodNode -> def ggrandchild = adapter.make(methodNode) allMethods.add(ggrandchild) // print out parameters of method methodNode.parameters?.each {Parameter parameter -> def gggrandchild = adapter.make(parameter) ggrandchild.add(gggrandchild) if (parameter.initialExpression) { TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) parameter.initialExpression.visit(visitor) if (visitor.currentNode) gggrandchild.add(visitor.currentNode) } } // print out code of method TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) if (methodNode.code) { methodNode.code.visit(visitor) if (visitor.currentNode) ggrandchild.add(visitor.currentNode) } } } private def collectConstructorData(parent, String name, ClassNode classNode) { def allCtors = nodeMaker.makeNode(name) if (classNode.declaredConstructors) parent.add(allCtors) classNode.declaredConstructors?.each {ConstructorNode ctorNode -> def ggrandchild = adapter.make(ctorNode) allCtors.add(ggrandchild) TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter) if (ctorNode.code) { ctorNode.code.visit(visitor) if (visitor.currentNode) ggrandchild.add(visitor.currentNode) } } } } /** * This AST visitor builds up a TreeNode. * * @author Hamlet D'Arcy */ private class TreeNodeBuildingVisitor extends CodeVisitorSupport { def currentNode private adapter /** * Creates the visitor. A file named AstBrowserProperties.groovy is located which is * a property files the describes how to represent ASTNode types as Strings. */ private TreeNodeBuildingVisitor(adapter) { if (!adapter) throw new IllegalArgumentException("Null: adapter") this.adapter = adapter; } /** * This method looks at the AST node and decides how to represent it in a TreeNode, then it * continues walking the tree. If the node and the expectedSubclass are not exactly the same * Class object then the node is not added to the tree. This is to eliminate seeing duplicate * nodes, for instance seeing an ArgumentListExpression and a TupleExpression in the tree, when * an ArgumentList is-a Tuple. */ private void addNode(node, Class expectedSubclass, Closure superMethod) { if (expectedSubclass.getName() == node.getClass().getName()) { if (currentNode == null) { currentNode = adapter.make(node) superMethod.call(node) } else { // visitor works off void methods... so we have to // perform a swap to get accumulation like behavior. def temp = currentNode; currentNode = adapter.make(node) temp.add(currentNode) currentNode.parent = temp superMethod.call(node) currentNode = temp } } else { superMethod.call(node) } } public void visitBlockStatement(BlockStatement node) { addNode(node, BlockStatement, { super.visitBlockStatement(it) }); } public void visitForLoop(ForStatement node) { addNode(node, ForStatement, { super.visitForLoop(it) }); } public void visitWhileLoop(WhileStatement node) { addNode(node, WhileStatement, { super.visitWhileLoop(it) }); } public void visitDoWhileLoop(DoWhileStatement node) { addNode(node, DoWhileStatement, { super.visitDoWhileLoop(it) }); } public void visitIfElse(IfStatement node) { addNode(node, IfStatement, { super.visitIfElse(it) }); } public void visitExpressionStatement(ExpressionStatement node) { addNode(node, ExpressionStatement, { super.visitExpressionStatement(it) }); } public void visitReturnStatement(ReturnStatement node) { addNode(node, ReturnStatement, { super.visitReturnStatement(it) }); } public void visitAssertStatement(AssertStatement node) { addNode(node, AssertStatement, { super.visitAssertStatement(it) }); } public void visitTryCatchFinally(TryCatchStatement node) { addNode(node, TryCatchStatement, { super.visitTryCatchFinally(it) }); } protected void visitEmptyStatement(EmptyStatement node) { addNode(node, EmptyStatement, { super.visitEmptyStatement(it) }); } public void visitSwitch(SwitchStatement node) { addNode(node, SwitchStatement, { super.visitSwitch(it) }); } public void visitCaseStatement(CaseStatement node) { addNode(node, CaseStatement, { super.visitCaseStatement(it) }); } public void visitBreakStatement(BreakStatement node) { addNode(node, BreakStatement, { super.visitBreakStatement(it) }); } public void visitContinueStatement(ContinueStatement node) { addNode(node, ContinueStatement, { super.visitContinueStatement(it) }); } public void visitSynchronizedStatement(SynchronizedStatement node) { addNode(node, SynchronizedStatement, { super.visitSynchronizedStatement(it) }); } public void visitThrowStatement(ThrowStatement node) { addNode(node, ThrowStatement, { super.visitThrowStatement(it) }); } public void visitMethodCallExpression(MethodCallExpression node) { addNode(node, MethodCallExpression, { super.visitMethodCallExpression(it) }); } public void visitStaticMethodCallExpression(StaticMethodCallExpression node) { addNode(node, StaticMethodCallExpression, { super.visitStaticMethodCallExpression(it) }); } public void visitConstructorCallExpression(ConstructorCallExpression node) { addNode(node, ConstructorCallExpression, { super.visitConstructorCallExpression(it) }); } public void visitBinaryExpression(BinaryExpression node) { addNode(node, BinaryExpression, { super.visitBinaryExpression(it) }); } public void visitTernaryExpression(TernaryExpression node) { addNode(node, TernaryExpression, { super.visitTernaryExpression(it) }); } public void visitShortTernaryExpression(ElvisOperatorExpression node) { addNode(node, ElvisOperatorExpression, { super.visitShortTernaryExpression(it) }); } public void visitPostfixExpression(PostfixExpression node) { addNode(node, PostfixExpression, { super.visitPostfixExpression(it) }); } public void visitPrefixExpression(PrefixExpression node) { addNode(node, PrefixExpression, { super.visitPrefixExpression(it) }); } public void visitBooleanExpression(BooleanExpression node) { addNode(node, BooleanExpression, { super.visitBooleanExpression(it) }); } public void visitNotExpression(NotExpression node) { addNode(node, NotExpression, { super.visitNotExpression(it) }); } public void visitClosureExpression(ClosureExpression node) { addNode(node, ClosureExpression, { it.parameters?.each { parameter -> visitParameter(parameter) } super.visitClosureExpression(it) }); } /** * Makes walking parameters look like others in the visitor. */ public void visitParameter(Parameter node) { addNode(node, Parameter, { if (node.initialExpression) { node.initialExpression?.visit(this) } }); } public void visitTupleExpression(TupleExpression node) { addNode(node, TupleExpression, { super.visitTupleExpression(it) }); } public void visitListExpression(ListExpression node) { addNode(node, ListExpression, { super.visitListExpression(it) }); } public void visitArrayExpression(ArrayExpression node) { addNode(node, ArrayExpression, { super.visitArrayExpression(it) }); } public void visitMapExpression(MapExpression node) { addNode(node, MapExpression, { super.visitMapExpression(it) }); } public void visitMapEntryExpression(MapEntryExpression node) { addNode(node, MapEntryExpression, { super.visitMapEntryExpression(it) }); } public void visitRangeExpression(RangeExpression node) { addNode(node, RangeExpression, { super.visitRangeExpression(it) }); } public void visitSpreadExpression(SpreadExpression node) { addNode(node, SpreadExpression, { super.visitSpreadExpression(it) }); } public void visitSpreadMapExpression(SpreadMapExpression node) { addNode(node, SpreadMapExpression, { super.visitSpreadMapExpression(it) }); } public void visitMethodPointerExpression(MethodPointerExpression node) { addNode(node, MethodPointerExpression, { super.visitMethodPointerExpression(it) }); } public void visitUnaryMinusExpression(UnaryMinusExpression node) { addNode(node, UnaryMinusExpression, { super.visitUnaryMinusExpression(it) }); } public void visitUnaryPlusExpression(UnaryPlusExpression node) { addNode(node, UnaryPlusExpression, { super.visitUnaryPlusExpression(it) }); } public void visitBitwiseNegationExpression(BitwiseNegationExpression node) { addNode(node, BitwiseNegationExpression, { super.visitBitwiseNegationExpression(it) }); } public void visitCastExpression(CastExpression node) { addNode(node, CastExpression, { super.visitCastExpression(it) }); } public void visitConstantExpression(ConstantExpression node) { addNode(node, ConstantExpression, { super.visitConstantExpression(it) }); } public void visitClassExpression(ClassExpression node) { addNode(node, ClassExpression, { super.visitClassExpression(it) }); } public void visitVariableExpression(VariableExpression node) { addNode(node, VariableExpression, { VariableExpression it -> if (it.accessedVariable) { if (it.accessedVariable instanceof Parameter) { visitParameter((Parameter)it.accessedVariable) } else if (it.accessedVariable instanceof DynamicVariable) { addNode(it.accessedVariable, DynamicVariable,{ it.initialExpression?.visit(this)}); } } }); } public void visitDeclarationExpression(DeclarationExpression node) { addNode(node, DeclarationExpression, { super.visitDeclarationExpression(it) }); } public void visitPropertyExpression(PropertyExpression node) { addNode(node, PropertyExpression, { super.visitPropertyExpression(it) }); } public void visitAttributeExpression(AttributeExpression node) { addNode(node, AttributeExpression, { super.visitAttributeExpression(it) }); } public void visitFieldExpression(FieldExpression node) { addNode(node, FieldExpression, { super.visitFieldExpression(it) }); } public void visitGStringExpression(GStringExpression node) { addNode(node, GStringExpression, { super.visitGStringExpression(it) }); } public void visitCatchStatement(CatchStatement node) { addNode(node, CatchStatement, { if (it.variable) visitParameter(it.variable) super.visitCatchStatement(it) }); } public void visitArgumentlistExpression(ArgumentListExpression node) { addNode(node, ArgumentListExpression, { super.visitArgumentlistExpression(it) }); } public void visitClosureListExpression(ClosureListExpression node) { addNode(node, ClosureListExpression, { super.visitClosureListExpression(it) }); } public void visitBytecodeExpression(BytecodeExpression node) { addNode(node, BytecodeExpression, { super.visitBytecodeExpression(it) }); } protected void visitListOfExpressions(List list) { list.each { Expression node -> if (node instanceof NamedArgumentListExpression ) { addNode(node, NamedArgumentListExpression, { it.visit(this) }); } else { node.visit(this) } } } } groovy-1.8.6/src/main/groovy/inspect/swingui/TableMap.java0000644001501200150120000000507711707612044023126 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect.swingui; /** * In a chain of data manipulators some behaviour is common. TableMap * provides most of this behaviour and can be subclassed by filters * that only need to override a handful of specific methods. TableMap * implements TableModel by routing all requests to its model, and * TableModelListener by routing all events to its listeners. Inserting * a TableMap which has not been subclassed into a chain of table filters * should have no effect. * * @version 1.11 01/23/03 * @author Philip Milne */ import javax.swing.table.*; import javax.swing.event.TableModelListener; import javax.swing.event.TableModelEvent; public class TableMap extends AbstractTableModel implements TableModelListener { protected TableModel model; public TableModel getModel() { return model; } public void setModel(TableModel model) { this.model = model; model.addTableModelListener(this); } // By default, Implement TableModel by forwarding all messages // to the model. public Object getValueAt(int aRow, int aColumn) { return model.getValueAt(aRow, aColumn); } public void setValueAt(Object aValue, int aRow, int aColumn) { model.setValueAt(aValue, aRow, aColumn); } public int getRowCount() { return (model == null) ? 0 : model.getRowCount(); } public int getColumnCount() { return (model == null) ? 0 : model.getColumnCount(); } public String getColumnName(int aColumn) { return model.getColumnName(aColumn); } public Class getColumnClass(int aColumn) { return model.getColumnClass(aColumn); } public boolean isCellEditable(int row, int column) { return model.isCellEditable(row, column); } // // Implementation of the TableModelListener interface, // // By default forward all events to all the listeners. public void tableChanged(TableModelEvent e) { fireTableChanged(e); } } groovy-1.8.6/src/main/groovy/inspect/TextNode.groovy0000644001501200150120000000271711715031256022107 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Represents a plain text node for use in the AST tree made by ASTBrowser * * @author Roshan Dawrani */ package groovy.inspect import groovy.inspect.swingui.AstBrowserNodeMaker class TextNode { Object userObject List> properties TextNode parent List children TextNode(Object userObject) { this.userObject = userObject children = new ArrayList() } TextNode(Object userObject, List> properties) { this(userObject) this.properties = properties } public void add(TextNode child) { children << child } public void setParent(TextNode newParent) { parent = newParent } String toString() { userObject ? userObject.toString() : "null" } } groovy-1.8.6/src/main/groovy/inspect/TextTreeNodeMaker.groovy0000644001501200150120000000216511707612044023705 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A factory class for plain text nodes for use in the AST tree made by ASTBrowser * * @author Roshan Dawrani */ package groovy.inspect import groovy.inspect.swingui.AstBrowserNodeMaker class TextTreeNodeMaker implements AstBrowserNodeMaker { TextNode makeNode(Object userObject) { new TextNode(userObject) } TextNode makeNodeWithProperties(Object userObject, List> properties) { new TextNode(userObject, properties) } }groovy-1.8.6/src/main/groovy/inspect/Inspector.java0000644001501200150120000003253111627206700021714 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.inspect; import groovy.lang.GroovyObject; import groovy.lang.MetaClass; import groovy.lang.MetaMethod; import groovy.lang.PropertyValue; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; /** * The Inspector provides a unified access to an object's * information that can be determined by introspection. * * @author Dierk Koenig */ public class Inspector { protected Object objectUnderInspection; // Indexes to retrieve Class Property information public static final int CLASS_PACKAGE_IDX = 0; public static final int CLASS_CLASS_IDX = 1; public static final int CLASS_INTERFACE_IDX = 2; public static final int CLASS_SUPERCLASS_IDX = 3; public static final int CLASS_OTHER_IDX = 4; // Indexes to retrieve field and method information public static final int MEMBER_ORIGIN_IDX = 0; public static final int MEMBER_MODIFIER_IDX = 1; public static final int MEMBER_DECLARER_IDX = 2; public static final int MEMBER_TYPE_IDX = 3; public static final int MEMBER_NAME_IDX = 4; public static final int MEMBER_PARAMS_IDX = 5; public static final int MEMBER_VALUE_IDX = 5; public static final int MEMBER_EXCEPTIONS_IDX = 6; public static final String NOT_APPLICABLE = "n/a"; public static final String GROOVY = "GROOVY"; public static final String JAVA = "JAVA"; /** * @param objectUnderInspection must not be null */ public Inspector(Object objectUnderInspection) { if (null == objectUnderInspection) { throw new IllegalArgumentException("argument must not be null"); } this.objectUnderInspection = objectUnderInspection; } /** * Get the Class Properties of the object under inspection. * * @return String array to be indexed by the CLASS_xxx_IDX constants */ public String[] getClassProps() { String[] result = new String[CLASS_OTHER_IDX + 1]; Package pack = getClassUnderInspection().getPackage(); result[CLASS_PACKAGE_IDX] = "package " + ((pack == null) ? NOT_APPLICABLE : pack.getName()); String modifiers = Modifier.toString(getClassUnderInspection().getModifiers()); result[CLASS_CLASS_IDX] = modifiers + " class " + shortName(getClassUnderInspection()); result[CLASS_INTERFACE_IDX] = "implements "; Class[] interfaces = getClassUnderInspection().getInterfaces(); for (Class anInterface : interfaces) { result[CLASS_INTERFACE_IDX] += shortName(anInterface) + " "; } result[CLASS_SUPERCLASS_IDX] = "extends " + shortName(getClassUnderInspection().getSuperclass()); result[CLASS_OTHER_IDX] = "is Primitive: " + getClassUnderInspection().isPrimitive() + ", is Array: " + getClassUnderInspection().isArray() + ", is Groovy: " + isGroovy(); return result; } public boolean isGroovy() { return GroovyObject.class.isAssignableFrom(getClassUnderInspection()); } /** * Gets the object being inspected. * * @return the object */ public Object getObject() { return objectUnderInspection; } /** * Get info about usual Java instance and class Methods as well as Constructors. * * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants */ public Object[] getMethods() { Method[] methods = getClassUnderInspection().getMethods(); Constructor[] ctors = getClassUnderInspection().getConstructors(); Object[] result = new Object[methods.length + ctors.length]; int resultIndex = 0; for (; resultIndex < methods.length; resultIndex++) { Method method = methods[resultIndex]; result[resultIndex] = methodInfo(method); } for (int i = 0; i < ctors.length; i++, resultIndex++) { Constructor ctor = ctors[i]; result[resultIndex] = methodInfo(ctor); } return result; } /** * Get info about instance and class Methods that are dynamically added through Groovy. * * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants */ public Object[] getMetaMethods() { MetaClass metaClass = InvokerHelper.getMetaClass(objectUnderInspection); List metaMethods = metaClass.getMetaMethods(); Object[] result = new Object[metaMethods.size()]; int i = 0; for (Iterator iter = metaMethods.iterator(); iter.hasNext(); i++) { MetaMethod metaMethod = (MetaMethod) iter.next(); result[i] = methodInfo(metaMethod); } return result; } /** * Get info about usual Java public fields incl. constants. * * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants */ public Object[] getPublicFields() { Field[] fields = getClassUnderInspection().getFields(); Object[] result = new Object[fields.length]; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; result[i] = fieldInfo(field); } return result; } /** * Get info about Properties (Java and Groovy alike). * * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants */ public Object[] getPropertyInfo() { List props = DefaultGroovyMethods.getMetaPropertyValues(objectUnderInspection); Object[] result = new Object[props.size()]; int i = 0; for (Iterator iter = props.iterator(); iter.hasNext(); i++) { PropertyValue pv = (PropertyValue) iter.next(); result[i] = fieldInfo(pv); } return result; } protected String[] fieldInfo(Field field) { String[] result = new String[MEMBER_VALUE_IDX + 1]; result[MEMBER_ORIGIN_IDX] = JAVA; result[MEMBER_MODIFIER_IDX] = Modifier.toString(field.getModifiers()); result[MEMBER_DECLARER_IDX] = shortName(field.getDeclaringClass()); result[MEMBER_TYPE_IDX] = shortName(field.getType()); result[MEMBER_NAME_IDX] = field.getName(); try { result[MEMBER_VALUE_IDX] = InvokerHelper.inspect(field.get(objectUnderInspection)); } catch (IllegalAccessException e) { result[MEMBER_VALUE_IDX] = NOT_APPLICABLE; } return withoutNulls(result); } protected String[] fieldInfo(PropertyValue pv) { String[] result = new String[MEMBER_VALUE_IDX + 1]; result[MEMBER_ORIGIN_IDX] = GROOVY; result[MEMBER_MODIFIER_IDX] = "public"; result[MEMBER_DECLARER_IDX] = NOT_APPLICABLE; result[MEMBER_TYPE_IDX] = shortName(pv.getType()); result[MEMBER_NAME_IDX] = pv.getName(); try { result[MEMBER_VALUE_IDX] = InvokerHelper.inspect(pv.getValue()); } catch (Exception e) { result[MEMBER_VALUE_IDX] = NOT_APPLICABLE; } return withoutNulls(result); } protected Class getClassUnderInspection() { return objectUnderInspection.getClass(); } public static String shortName(Class clazz) { if (null == clazz) return NOT_APPLICABLE; String className = clazz.getName(); if (null == clazz.getPackage()) return className; String packageName = clazz.getPackage().getName(); int offset = packageName.length(); if (offset > 0) offset++; className = className.substring(offset); return className; } protected String[] methodInfo(Method method) { String[] result = new String[MEMBER_EXCEPTIONS_IDX + 1]; int mod = method.getModifiers(); result[MEMBER_ORIGIN_IDX] = JAVA; result[MEMBER_DECLARER_IDX] = shortName(method.getDeclaringClass()); result[MEMBER_MODIFIER_IDX] = Modifier.toString(mod); result[MEMBER_NAME_IDX] = method.getName(); result[MEMBER_TYPE_IDX] = shortName(method.getReturnType()); Class[] params = method.getParameterTypes(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < params.length; j++) { sb.append(shortName(params[j])); if (j < (params.length - 1)) sb.append(", "); } result[MEMBER_PARAMS_IDX] = sb.toString(); sb.setLength(0); Class[] exceptions = method.getExceptionTypes(); for (int k = 0; k < exceptions.length; k++) { sb.append(shortName(exceptions[k])); if (k < (exceptions.length - 1)) sb.append(", "); } result[MEMBER_EXCEPTIONS_IDX] = sb.toString(); return withoutNulls(result); } protected String[] methodInfo(Constructor ctor) { String[] result = new String[MEMBER_EXCEPTIONS_IDX + 1]; int mod = ctor.getModifiers(); result[MEMBER_ORIGIN_IDX] = JAVA; result[MEMBER_MODIFIER_IDX] = Modifier.toString(mod); result[MEMBER_DECLARER_IDX] = shortName(ctor.getDeclaringClass()); result[MEMBER_TYPE_IDX] = shortName(ctor.getDeclaringClass()); result[MEMBER_NAME_IDX] = ctor.getName(); Class[] params = ctor.getParameterTypes(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < params.length; j++) { sb.append(shortName(params[j])); if (j < (params.length - 1)) sb.append(", "); } result[MEMBER_PARAMS_IDX] = sb.toString(); sb.setLength(0); Class[] exceptions = ctor.getExceptionTypes(); for (int k = 0; k < exceptions.length; k++) { sb.append(shortName(exceptions[k])); if (k < (exceptions.length - 1)) sb.append(", "); } result[MEMBER_EXCEPTIONS_IDX] = sb.toString(); return withoutNulls(result); } protected String[] methodInfo(MetaMethod method) { String[] result = new String[MEMBER_EXCEPTIONS_IDX + 1]; int mod = method.getModifiers(); result[MEMBER_ORIGIN_IDX] = GROOVY; result[MEMBER_MODIFIER_IDX] = Modifier.toString(mod); result[MEMBER_DECLARER_IDX] = shortName(method.getDeclaringClass().getTheClass()); result[MEMBER_TYPE_IDX] = shortName(method.getReturnType()); result[MEMBER_NAME_IDX] = method.getName(); CachedClass[] params = method.getParameterTypes(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < params.length; j++) { sb.append(shortName(params[j].getTheClass())); if (j < (params.length - 1)) sb.append(", "); } result[MEMBER_PARAMS_IDX] = sb.toString(); result[MEMBER_EXCEPTIONS_IDX] = NOT_APPLICABLE; // no exception info for Groovy MetaMethods return withoutNulls(result); } protected String[] withoutNulls(String[] toNormalize) { for (int i = 0; i < toNormalize.length; i++) { String s = toNormalize[i]; if (null == s) toNormalize[i] = NOT_APPLICABLE; } return toNormalize; } public static void print(Object[] memberInfo) { print(System.out, memberInfo); } static void print(final PrintStream out, Object[] memberInfo) { for (int i = 0; i < memberInfo.length; i++) { String[] metaMethod = (String[]) memberInfo[i]; out.print(i + ":\t"); for (String s : metaMethod) { out.print(s + " "); } out.println(""); } } public static Collection sort(List memberInfo) { Collections.sort(memberInfo, new MemberComparator()); return memberInfo; } public static class MemberComparator implements Comparator { public int compare(Object a, Object b) { String[] aStr = (String[]) a; String[] bStr = (String[]) b; int result = aStr[Inspector.MEMBER_NAME_IDX].compareTo(bStr[Inspector.MEMBER_NAME_IDX]); if (0 != result) return result; result = aStr[Inspector.MEMBER_TYPE_IDX].compareTo(bStr[Inspector.MEMBER_TYPE_IDX]); if (0 != result) return result; result = aStr[Inspector.MEMBER_PARAMS_IDX].compareTo(bStr[Inspector.MEMBER_PARAMS_IDX]); if (0 != result) return result; result = aStr[Inspector.MEMBER_DECLARER_IDX].compareTo(bStr[Inspector.MEMBER_DECLARER_IDX]); if (0 != result) return result; result = aStr[Inspector.MEMBER_MODIFIER_IDX].compareTo(bStr[Inspector.MEMBER_MODIFIER_IDX]); if (0 != result) return result; result = aStr[Inspector.MEMBER_ORIGIN_IDX].compareTo(bStr[Inspector.MEMBER_ORIGIN_IDX]); return result; } } } groovy-1.8.6/src/main/groovy/swing/0000755001501200150120000000000011707612044016562 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/swing/package.html0000644001501200150120000000026011627206700021040 0ustar miguelmiguel package groovy.swing.*

    A GroovyMarkup builder for creating Swing user interfaces

    groovy-1.8.6/src/main/groovy/swing/factory/0000755001501200150120000000000011715031256020230 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/swing/factory/MatteBorderFactory.groovy0000644001501200150120000000623011707612044025241 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.BorderFactory /** * matteBorder requires essentially two parameter, a mat definition and a * border size definition. The value argument can accept either of these: * any of a java.awt.Color, a javax.swing.Icon, an integer, or a 4 arg * integer array. The remaining parameter must be define via attributes, * either an icon: or color: attribute and a size: or top:, left:, bottom:, * and right: attribute. */ class MatteBorderFactory extends SwingBorderFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') def matte def border if (attributes.containsKey('icon')) { matte = attributes.remove('icon') } else if (attributes.containsKey('color')) { matte = attributes.remove('color') } else if (value != null) { matte = value } else { throw new RuntimeException("$name must have a matte defined, either as a value argument or as a color: or icon: attribute"); } if (attributes.containsKey('size')) { border = attributes.remove('size'); border = [border, border, border, border] } else if (attributes.containsKey('top')) { def top = attributes.remove('top') def left = attributes.remove('left') def bottom = attributes.remove('bottom') def right = attributes.remove('right') if ((top == null) || (left == null) || (bottom == null) || (right == null)) { throw new RuntimeException("In $name if one of top:, left:, bottom: or right: is specified all must be specified") } border = [top, left, bottom, right] } else if (value != null) { if (matte == value) { throw new RuntimeException("In $name some attributes are required in addition to the value argument") } if (value instanceof Integer) { border = [value, value, value, value] } else { border = value } } if (attributes) { throw new RuntimeException("$name only supports the attributes [ icon: | color:] [ size: | ( top: left: bottom: right: ) }") } // spread list and multi-dispatch. That's groovy! return BorderFactory.createMatteBorder(*border, matte) } }groovy-1.8.6/src/main/groovy/swing/factory/SwingBorderFactory.groovy0000644001501200150120000000310211627206700025250 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JComponent import javax.swing.RootPaneContainer abstract class SwingBorderFactory extends AbstractFactory { public boolean isLeaf() { // no children return true; } public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object node, Map attributes) { // never do bean apply return false; } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (builder.context.applyBorderToParent) { if (parent instanceof JComponent) { parent.setBorder(child); } else if (parent instanceof RootPaneContainer) { setParent(builder, parent.contentPane, child) } else { throw new RuntimeException("Border cannot be applied to parent, it is neither a JComponent or a RootPaneContainer") } } } }groovy-1.8.6/src/main/groovy/swing/factory/TableFactory.groovy0000644001501200150120000000307711627206700024065 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.binding.JTableMetaMethods import javax.swing.JTable import javax.swing.table.TableColumn import javax.swing.table.TableModel class TableFactory extends BeanFactory { public TableFactory() { this(JTable) } public TableFactory(Class klass) { super(klass, false) } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { Object table = super.newInstance(builder, name, value, attributes); // insure metaproperties are registered JTableMetaMethods.enhanceMetaClass(table) return table } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (child instanceof TableColumn) { parent.addColumn(child); } else if (child instanceof TableModel) { parent.model = child; } } } groovy-1.8.6/src/main/groovy/swing/factory/BeanFactory.groovy0000644001501200150120000000355311627206700023702 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory /** * @author Danno Ferrin * @version $Revision: 7953 $ * @since Groovy 1.1 */ class BeanFactory extends AbstractFactory { final Class beanClass final protected boolean leaf public BeanFactory(Class beanClass) { this(beanClass, false) } public BeanFactory(Class beanClass, boolean leaf) { this.beanClass = beanClass this.leaf = leaf } public boolean isLeaf() { return leaf } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (value instanceof GString) value = value as String if (FactoryBuilderSupport.checkValueIsTypeNotString(value, name, beanClass)) { return value } Object bean = beanClass.newInstance() if (value instanceof String) { try { bean.text = value } catch (MissingPropertyException mpe) { throw new RuntimeException("In $name value argument of type String cannot be applied to property text:"); } } return bean } } groovy-1.8.6/src/main/groovy/swing/factory/ColumnModelFactory.groovy0000644001501200150120000000345411715031256025253 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.util.logging.Logger import javax.swing.JTable import javax.swing.table.TableColumnModel import groovy.util.logging.Log /** * @author Alexander Klein * @author Hamlet D'Arcy */ @Log class ColumnModelFactory extends AbstractFactory { Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { if (value instanceof TableColumnModel) { return value } Class jxTableClass = null try { jxTableClass = Class.forName("org.jdesktop.swingx.JXTable") } catch (ClassNotFoundException ex) {} if (jxTableClass != null && jxTableClass.isAssignableFrom(builder.current.getClass())) { return Class.forName("org.jdesktop.swingx.table.DefaultTableColumnModelExt").newInstance() } else{ return new javax.swing.table.DefaultTableColumnModel() } } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { if (!(parent instanceof JTable)) { log.warning("ColumnModel must be a child of a table. Found: " + parent.getClass()); } parent.columnModel = node } } groovy-1.8.6/src/main/groovy/swing/factory/BoxLayoutFactory.groovy0000644001501200150120000000376511627206700024770 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Container import javax.swing.BoxLayout import org.codehaus.groovy.runtime.InvokerHelper public class BoxLayoutFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); Object parent = builder.getCurrent(); if (parent instanceof Container) { Object axisObject = attributes.remove("axis"); int axis = BoxLayout.X_AXIS; if (axisObject != null) { Integer i = (Integer) axisObject; axis = i.intValue(); } Container target = LayoutFactory.getLayoutTarget(parent); BoxLayout answer = new BoxLayout(target, axis); // now let's try to set the layout property InvokerHelper.setProperty(target, "layout", answer); return answer; } else { throw new RuntimeException("Must be nested inside a Container"); } } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (parent instanceof Container) { Container target = LayoutFactory.getLayoutTarget(parent); InvokerHelper.setProperty(target, "layout", child); } } } groovy-1.8.6/src/main/groovy/swing/factory/TabbedPaneFactory.groovy0000644001501200150120000002077311627206700025025 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window class TabbedPaneFactory extends BeanFactory { public static final String DELEGATE_PROPERTY_TITLE = "_delegateProperty:title"; public static final String DEFAULT_DELEGATE_PROPERTY_TITLE = "title"; public static final String DELEGATE_PROPERTY_TAB_ICON = "_delegateProperty:tabIcon"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_ICON = "tabIcon"; public static final String DELEGATE_PROPERTY_TAB_DISABLED_ICON = "_delegateProperty:tabDisabledIcon"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_DISABLED_ICON = "tabDisabledIcon"; public static final String DELEGATE_PROPERTY_TAB_TOOL_TIP = "_delegateProperty:tabToolTip"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_TOOL_TIP = "tabToolTip"; public static final String DELEGATE_PROPERTY_TAB_FOREGROUND = "_delegateProperty:tabForeground"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_FOREGROUND = "tabForeground"; public static final String DELEGATE_PROPERTY_TAB_BACKGROUND = "_delegateProperty:tabBackground"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_BACKGROUND = "tabBackground"; public static final String DELEGATE_PROPERTY_TAB_ENABLED = "_delegateProperty:tabEnabled"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_ENABLED = "tabEnabled"; public static final String DELEGATE_PROPERTY_TAB_MNEMONIC = "_delegateProperty:tabMnemonic"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_MNEMONIC = "tabMnemonic"; public static final String DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX = "_delegateProperty:tabDisplayedMnemonicIndex"; public static final String DEFAULT_DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX = "tabDisplayedMnemonicIndex"; public static final String CONTEXT_DATA_KEY = "TabbdePaneFactoryData"; public TabbedPaneFactory(Class beanClass) { super(beanClass, false) } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { def newChild = super.newInstance(builder, name, value, attributes) builder.context.tabbedPaneFactoryClosure = { FactoryBuilderSupport cBuilder, Object cNode, Map cAttributes -> if (builder.current == newChild) inspectChild(cBuilder, cNode, cAttributes) } builder.addAttributeDelegate(builder.context.tabbedPaneFactoryClosure) builder.context.selectedIndex = attributes.remove('selectedIndex') builder.context.selectedComponent = attributes.remove('selectedComponent') builder.context[DELEGATE_PROPERTY_TITLE] = attributes.remove("titleProperty") ?: DEFAULT_DELEGATE_PROPERTY_TITLE builder.context[DELEGATE_PROPERTY_TAB_ICON] = attributes.remove("tabIconProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_ICON builder.context[DELEGATE_PROPERTY_TAB_DISABLED_ICON] = attributes.remove("tabDisabledIconProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_DISABLED_ICON builder.context[DELEGATE_PROPERTY_TAB_TOOL_TIP] = attributes.remove("tabToolTipProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_TOOL_TIP builder.context[DELEGATE_PROPERTY_TAB_BACKGROUND] = attributes.remove("tabBackgroundProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_BACKGROUND builder.context[DELEGATE_PROPERTY_TAB_FOREGROUND] = attributes.remove("tabForegroundProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_FOREGROUND builder.context[DELEGATE_PROPERTY_TAB_ENABLED] = attributes.remove("tabEnabledProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_ENABLED builder.context[DELEGATE_PROPERTY_TAB_MNEMONIC] = attributes.remove("tabMnemonicProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_MNEMONIC builder.context[DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX] = attributes.remove("tabDisplayedMnemonicIndexProperty") ?: DEFAULT_DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX return newChild; } public static void inspectChild(FactoryBuilderSupport builder, Object node, Map attributes) { if (!(node instanceof Component) || (node instanceof Window)) { return; } def name = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TITLE) ?: DEFAULT_DELEGATE_PROPERTY_TITLE) def icon = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_ICON) ?: DEFAULT_DELEGATE_PROPERTY_TAB_ICON) def disabledIcon = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_DISABLED_ICON) ?: DEFAULT_DELEGATE_PROPERTY_TAB_DISABLED_ICON) def toolTip = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_TOOL_TIP) ?: DEFAULT_DELEGATE_PROPERTY_TAB_TOOL_TIP) def background = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_BACKGROUND) ?: DEFAULT_DELEGATE_PROPERTY_TAB_BACKGROUND) def foreground = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_FOREGROUND) ?: DEFAULT_DELEGATE_PROPERTY_TAB_FOREGROUND) def enabled = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_ENABLED) ?: DEFAULT_DELEGATE_PROPERTY_TAB_ENABLED) def mnemonic = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_MNEMONIC) ?: DEFAULT_DELEGATE_PROPERTY_TAB_MNEMONIC) def displayedMnemonicIndex = attributes.remove(builder?.parentContext?.getAt(DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX) ?: DEFAULT_DELEGATE_PROPERTY_TAB_DISPLAYED_MNEMONIC_INDEX) def tabbedPaneContext = builder.context.get(CONTEXT_DATA_KEY) ?: [:]; if (tabbedPaneContext.isEmpty()) { builder.context.put(CONTEXT_DATA_KEY, tabbedPaneContext) } tabbedPaneContext.put(node, [name, icon, disabledIcon, toolTip, background, foreground, enabled, mnemonic, displayedMnemonicIndex]) } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } try { def title = builder.context[CONTEXT_DATA_KEY]?.get(child) ?: [null, null, null, null, null, null, null, null, null] if (title[0] == null) { title[0] = child.name } parent.addTab(title[0], title[1], child, title[3]) int index = parent.indexOfComponent(child) if (title[2]) { parent.setDisabledIconAt(index, title[2]) } if (title[4]) { parent.setBackgroundAt(index, title[4]) } if (title[5]) { parent.setForegroundAt(index, title[5]) } if (title[6] != null) { parent.setEnabledAt(index, title[6]) } if (title[7]) { def mnemonic = title[7] if ((mnemonic instanceof String) || (mnemonic instanceof GString)) { parent.setMnemonicAt(index, mnemonic.charAt(0) as int) } else { parent.setMnemonicAt(index, mnemonic as int) } } if (title[8]) { parent.setDisplayedMnemonicIndexAt(index, title[8]) } } catch (MissingPropertyException mpe) { parent.add(child) } } public void onNodeCompleted( FactoryBuilderSupport builder, Object parent, Object node ) { super.onNodeCompleted (builder, parent, node) builder.removeAttributeDelegate(builder.context.tabbedPaneFactoryClosure) if (builder.context.selectedComponent != null) { node.selectedComponent = builder.context.selectedComponent } if (builder.context.selectedIndex != null) { node.selectedIndex = builder.context.selectedIndex } } }groovy-1.8.6/src/main/groovy/swing/factory/EtchedBorderFactory.groovy0000644001501200150120000000324111627206700025361 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Color import javax.swing.BorderFactory class EtchedBorderFactory extends SwingBorderFactory { final int type; public EtchedBorderFactory(int newType) { type = newType; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') // no if-else-if chain so that we can have one attribute failure block if (attributes.containsKey("highlight")) { Color highlight = attributes.remove("highlight") Color shadow = attributes.remove("shadow") if (highlight && shadow && !attributes) { return BorderFactory.createEtchedBorder(type, highlight, shadow); } } if (attributes) { throw new RuntimeException("$name only accepts no attributes, or highlight: and shadow: attributes") } return BorderFactory.createEtchedBorder(type); } }groovy-1.8.6/src/main/groovy/swing/factory/RichActionWidgetFactory.groovy0000644001501200150120000000560511627206700026224 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.util.logging.Level import java.util.logging.Logger import javax.swing.Action import javax.swing.Icon /** * * @author shemnon */ public class RichActionWidgetFactory extends AbstractFactory { static final Class[] ACTION_ARGS = [Action]; static final Class[] ICON_ARGS = [Icon]; static final Class[] STRING_ARGS = [String]; final Constructor actionCtor; final Constructor iconCtor; final Constructor stringCtor; final Class klass; public RichActionWidgetFactory(Class klass) { try { actionCtor = klass.getConstructor(ACTION_ARGS); iconCtor = klass.getConstructor(ICON_ARGS); stringCtor = klass.getConstructor(STRING_ARGS); this.klass = klass; } catch (NoSuchMethodException ex) { Logger.getLogger("global").log(Level.INFO, null, ex); } catch (SecurityException ex) { Logger.getLogger("global").log(Level.SEVERE, null, ex); } } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { try { if (value instanceof GString) value = value as String if (value == null) { return klass.newInstance(); } else if (value instanceof Action) { return actionCtor.newInstance(value); } else if (value instanceof Icon) { return iconCtor.newInstance(value); } else if (value instanceof String) { return stringCtor.newInstance(value); } else if (klass.isAssignableFrom(value.getClass())) { return value; } else { throw new RuntimeException("$name can only have a value argument of type javax.swing.Action, javax.swing.Icon, java.lang.String, or $klass.name"); } } catch (IllegalArgumentException e) { throw new RuntimeException("Failed to create component for '$name' reason: $e", e); } catch (InvocationTargetException e) { throw new RuntimeException("Failed to create component for '$name' reason: $e", e); } } } groovy-1.8.6/src/main/groovy/swing/factory/WindowFactory.groovy0000644001501200150120000000320311627206700024274 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JWindow public class WindowFactory extends RootPaneContainerFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { JWindow window; if (FactoryBuilderSupport.checkValueIsType(value, name, JWindow.class)) { window = value } else { LinkedList containingWindows = builder.containingWindows; Object owner = attributes.remove("owner"); // if owner not explicit, use the last window type in the list if ((owner == null) && !containingWindows.empty) { owner = containingWindows.last; } if (owner) { // the joys of the MOP! window = new JWindow(owner); } else { window = new JWindow(); } } handleRootPaneTasks(builder, window, attributes) return window; } } groovy-1.8.6/src/main/groovy/swing/factory/RootPaneContainerFactory.groovy0000644001501200150120000000765511714271434026441 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window import javax.swing.JComponent import javax.swing.JButton import static groovy.swing.factory.LayoutFactory.DEFAULT_DELEGATE_PROPERTY_CONSTRAINT abstract class RootPaneContainerFactory extends AbstractFactory { public static final String DELEGATE_PROPERTY_DEFAULT_BUTTON = "_delegateProperty:defaultButton"; public static final String DEFAULT_DELEGATE_PROPERTY_DEFAULT_BUTTON = "defaultButton"; public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } try { def constraints = builder.context.constraints if (constraints != null) { parent.contentPane.add(child, constraints) if (child instanceof JComponent) { child.putClientProperty(DEFAULT_DELEGATE_PROPERTY_CONSTRAINT, constraints) } builder.context.remove('constraints') } else { parent.contentPane.add(child) } } catch (MissingPropertyException mpe) { parent.contentPane.add(child) } } public void handleRootPaneTasks(FactoryBuilderSupport builder, Window container, Map attributes) { builder.context[DELEGATE_PROPERTY_DEFAULT_BUTTON] = attributes.remove("defaultButtonProperty") ?: DEFAULT_DELEGATE_PROPERTY_DEFAULT_BUTTON builder.context.defaultButtonDelegate = builder.addAttributeDelegate {myBuilder, node, myAttributes -> if ((node instanceof JButton) && (builder.containingWindows[-1] == container)) { // in Java 6 use descending iterator ListIterator li = builder.contexts.listIterator(); Map context while (li.hasNext()) context = li.next() while (context && context[FactoryBuilderSupport.CURRENT_NODE] != container) { context = li.previous() } def defaultButtonProperty = context[DELEGATE_PROPERTY_DEFAULT_BUTTON] ?: DEFAULT_DELEGATE_PROPERTY_DEFAULT_BUTTON def defaultButton = myAttributes.remove(defaultButtonProperty) if (defaultButton) { container.rootPane.defaultButton = node } } } builder.containingWindows.add(container) builder.context.pack = attributes.remove('pack') builder.context.show = attributes.remove('show') builder.addDisposalClosure(container.&dispose) } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { if (node instanceof Window) { def containingWindows = builder.containingWindows if (!containingWindows.empty && containingWindows.last == node) { containingWindows.removeLast(); } } if (builder.context.pack) { node.pack() } if (builder.context.show) { node.visible = true } builder.removeAttributeDelegate(builder.context.defaultButtonDelegate) } }groovy-1.8.6/src/main/groovy/swing/factory/TextArgWidgetFactory.groovy0000644001501200150120000000304111707612044025550 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import org.codehaus.groovy.runtime.InvokerHelper /** * * @author Danno Ferrin */ public class TextArgWidgetFactory extends AbstractFactory { final Class klass; public TextArgWidgetFactory(Class klass) { this.klass = klass; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (value instanceof GString) value = value as String if (FactoryBuilderSupport.checkValueIsTypeNotString(value, name, klass)) { return value; } Object widget = klass.newInstance(); if (value instanceof String) { // this does not create property setting order issues, since the value arg precedes all attributes in the builder element InvokerHelper.setProperty(widget, "text", value); } return widget; } } groovy-1.8.6/src/main/groovy/swing/factory/SplitPaneFactory.groovy0000644001501200150120000000366511627206700024740 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window import javax.swing.JSplitPane public class SplitPaneFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (FactoryBuilderSupport.checkValueIsType(value, name, JSplitPane.class)) { return value; } JSplitPane answer = new JSplitPane(); answer.setLeftComponent(null); answer.setRightComponent(null); answer.setTopComponent(null); answer.setBottomComponent(null); return answer; } public void setChild(FactoryBuilderSupport factory, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } if (parent.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { if (parent.getTopComponent() == null) { parent.setTopComponent(child); } else { parent.setBottomComponent(child); } } else { if (parent.getLeftComponent() == null) { parent.setLeftComponent(child); } else { parent.setRightComponent(child); } } } } groovy-1.8.6/src/main/groovy/swing/factory/FrameFactory.groovy0000644001501200150120000000265211627206700024066 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JFrame import javax.swing.JMenuBar public class FrameFactory extends RootPaneContainerFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { JFrame frame if (FactoryBuilderSupport.checkValueIsType(value, name, JFrame.class)) { frame = value } else { frame = new JFrame() } handleRootPaneTasks(builder, frame, attributes) return frame; } public void setChild(FactoryBuilderSupport build, Object parent, Object child) { if (child instanceof JMenuBar) { parent.JMenuBar = child } else { super.setChild(build, parent, child) } } } groovy-1.8.6/src/main/groovy/swing/factory/MapFactory.groovy0000644001501200150120000000170211627206700023544 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory public class MapFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return attributes; } } groovy-1.8.6/src/main/groovy/swing/factory/BindGroupFactory.groovy0000644001501200150120000000217611627206700024726 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import org.codehaus.groovy.binding.AggregateBinding /** * Factory for aggregate bindings */ class BindGroupFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { AggregateBinding bindGroup = new AggregateBinding(); def bind = attributes.remove('bind') if ((bind == null) || bind) { bindGroup.bind() } return bindGroup } }groovy-1.8.6/src/main/groovy/swing/factory/ComponentFactory.groovy0000644001501200150120000000357611714271434025007 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window import javax.swing.JComponent import static groovy.swing.factory.LayoutFactory.DEFAULT_DELEGATE_PROPERTY_CONSTRAINT class ComponentFactory extends BeanFactory { public ComponentFactory(Class beanClass) { super(beanClass) } public ComponentFactory(Class beanClass, boolean leaf) { super(beanClass, leaf) } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } try { def constraints = builder.context.constraints if (constraints != null) { LayoutFactory.getLayoutTarget(parent).add(child, constraints) if (child instanceof JComponent) { child.putClientProperty(DEFAULT_DELEGATE_PROPERTY_CONSTRAINT, constraints) } builder.context.remove('constraints') } else { LayoutFactory.getLayoutTarget(parent).add(child) } } catch (MissingPropertyException mpe) { LayoutFactory.getLayoutTarget(parent).add(child) } } }groovy-1.8.6/src/main/groovy/swing/factory/LayoutFactory.groovy0000644001501200150120000000555111627206700024312 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Container import javax.swing.RootPaneContainer class LayoutFactory extends BeanFactory { def contextProps public static final String DELEGATE_PROPERTY_CONSTRAINT = "_delegateProperty:Constrinat"; public static final String DEFAULT_DELEGATE_PROPERTY_CONSTRAINT = "constraints"; public LayoutFactory(Class klass) { super(klass) } public LayoutFactory(Class klass, boolean leaf) { super(klass, leaf) } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context[DELEGATE_PROPERTY_CONSTRAINT] = attributes.remove("constraintsProperty") ?: DEFAULT_DELEGATE_PROPERTY_CONSTRAINT Object o = super.newInstance(builder, name, value, attributes); addLayoutProperties(builder.getContext()); return o; } public void addLayoutProperties(context, Class layoutClass) { if (contextProps == null) { contextProps = [:] layoutClass.fields.each { def name = it.name if (name.toUpperCase() == name) { contextProps.put(name, layoutClass."$name") } } } context.putAll(contextProps) } public void addLayoutProperties(context) { addLayoutProperties(context, beanClass) } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (parent instanceof Container) { getLayoutTarget(parent).layout = child } } public static Container getLayoutTarget(Container parent) { if (parent instanceof RootPaneContainer) { RootPaneContainer rpc = (RootPaneContainer) parent; parent = rpc.getContentPane(); } return parent; } public static constraintsAttributeDelegate(def builder, def node, def attributes) { def constraintsAttr = builder?.context?.getAt(DELEGATE_PROPERTY_CONSTRAINT) ?: DEFAULT_DELEGATE_PROPERTY_CONSTRAINT if (attributes.containsKey(constraintsAttr)) { builder.context.constraints = attributes.remove(constraintsAttr) } } }groovy-1.8.6/src/main/groovy/swing/factory/package.html0000644001501200150120000000026211627206700022511 0ustar miguelmiguel package groovy.swing.factory.*

    SwingBuilder helper classes for creating components

    groovy-1.8.6/src/main/groovy/swing/factory/EmptyBorderFactory.groovy0000644001501200150120000000503411707612044025266 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.BorderFactory /** * accepts values in lieu of attributes: * int - all of top, left, bottom, right * [int, int, int, int] - top, left, bottom, right * accepts attributes when no value present: * top: int, left: int, bottom: int, right: int * */ class EmptyBorderFactory extends SwingBorderFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') if (!attributes) { if (value instanceof Integer) { return BorderFactory.createEmptyBorder(value, value, value, value) } else if (value instanceof List && value.size() == 4) { // we need GDK methods on Collection for boolean .any{} and boolean .all{} :( boolean ints = true value.each {ints = ints & it instanceof Integer} if (ints) { return BorderFactory.createEmptyBorder(*value); } } throw new RuntimeException("$name only accepts a single integer or an array of four integers as a value argument"); } if (value == null) { int top = attributes.remove("top") int left = attributes.remove("left") int bottom = attributes.remove("bottom") int right = attributes.remove("right") if ((top == null) || (top == null) || (top == null) || (top == null) || attributes) { throw new RuntimeException("When $name is called it must be call with top:, left:, bottom:, right:, and no other attributes") } return BorderFactory.createEmptyBorder(top, left, bottom, right); } throw new RuntimeException("$name cannot be called with both an argulent value and attributes") } }groovy-1.8.6/src/main/groovy/swing/factory/TableLayoutFactory.groovy0000644001501200150120000000565611715031256025270 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.impl.TableLayout import groovy.swing.impl.TableLayoutCell import groovy.swing.impl.TableLayoutRow import java.awt.Component import java.awt.Window public class TableLayoutFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (FactoryBuilderSupport.checkValueIsType(value, name, TableLayout.class)) { return value; } return new TableLayout(); } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (builder.getParentFactory()) { builder.getParentFactory().setChild (builder, parent, child.getComponent()); } } } public class TRFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); //TODO we could make the value arg the parent Object parent = builder.getCurrent(); if (parent instanceof TableLayout) { return new TableLayoutRow((TableLayout) parent); } else { throw new RuntimeException("'tr' must be within a 'tableLayout'"); } } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { node.addComponentsForRow() } } public class TDFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); //TODO we could make the value arg the TR Object parent = builder.getCurrent(); if (parent instanceof TableLayoutRow) { return new TableLayoutCell((TableLayoutRow) parent); } else { throw new RuntimeException("'td' must be within a 'tr'"); } } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } parent.addComponent(child) } } groovy-1.8.6/src/main/groovy/swing/factory/WidgetFactory.groovy0000644001501200150120000000472111714271434024261 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window import javax.swing.JComponent import static groovy.swing.factory.LayoutFactory.DEFAULT_DELEGATE_PROPERTY_CONSTRAINT public class WidgetFactory extends AbstractFactory { final Class restrictedType; protected final boolean leaf public WidgetFactory(Class restrictedType, boolean leaf) { this.restrictedType = restrictedType this.leaf = leaf } boolean isLeaf() { return leaf } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (value == null) { value = attributes.remove(name); } if ((value != null) && FactoryBuilderSupport.checkValueIsType(value, name, restrictedType)) { return value; } else { throw new RuntimeException("$name must have either a value argument or an attribute named $name that must be of type $restrictedType.name"); } } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } try { def constraints = builder.context.constraints if (constraints != null) { LayoutFactory.getLayoutTarget(parent).add(child, constraints) if (child instanceof JComponent) { child.putClientProperty(DEFAULT_DELEGATE_PROPERTY_CONSTRAINT, constraints) } builder.context.remove('constraints') } else { LayoutFactory.getLayoutTarget(parent).add(child) } } catch (MissingPropertyException mpe) { LayoutFactory.getLayoutTarget(parent).add(child) } } } groovy-1.8.6/src/main/groovy/swing/factory/ComboBoxFactory.groovy0000644001501200150120000000333511627206700024543 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JComboBox import groovy.swing.binding.JComboBoxMetaMethods public class ComboBoxFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsType(value, name, JComboBox) //TODO expand to allow the value arg to be items Object items = attributes.get("items") JComboBox comboBox if (items instanceof Vector) { comboBox = new JComboBox(attributes.remove("items")) } else if (items instanceof List) { List list = (List) attributes.remove("items") comboBox = new JComboBox(list.toArray()) } else if (items instanceof Object[]) { comboBox = new JComboBox(attributes.remove("items")) } else if (value instanceof JComboBox) { comboBox = value } else { comboBox = new JComboBox() } JComboBoxMetaMethods.enhanceMetaClass(comboBox) return comboBox } } groovy-1.8.6/src/main/groovy/swing/factory/ColumnFactory.groovy0000644001501200150120000000674611715031256024301 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.util.logging.Logger import javax.swing.table.TableCellRenderer import javax.swing.table.TableColumn import javax.swing.table.TableColumnModel import groovy.util.logging.Log /** * @author Alexander Klein * @author Hamlet D'Arcy */ @Log class ColumnFactory extends AbstractFactory { Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { if(value instanceof TableColumn) { return value } TableColumn node Class jxTableClass = null try { jxTableClass = Class.forName("org.jdesktop.swingx.JXTable") } catch (ClassNotFoundException ex) { } if(jxTableClass != null && builder.current instanceof TableColumnModel) { node = Class.forName("org.jdesktop.swingx.table.TableColumnExt").newInstance() } else { node = new javax.swing.table.TableColumn() } if(value != null) { node.identifier = value.toString() attributes.remove('identifier') } if(attributes.width) { if(attributes.width instanceof Collection) { // 3 values: min, pref, max // 2 values: min, pref // 1 value: pref def (min, pref, max) = attributes.width if(!pref && !max) { node.minWidth = 0 node.preferredWidth = min as Integer node.maxWidth = Integer.MAX_VALUE } else { if(min) { node.minWidth = min as Integer } if(pref) { node.preferredWidth = pref as Integer } if(max) { node.maxWidth = max as Integer } } } else if(attributes.width instanceof Number) { node.minWidth = attributes.width.intValue() node.preferredWidth = attributes.width.intValue() node.maxWidth = attributes.width.intValue() } attributes.remove('width') } return node } void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { if (!(parent instanceof TableColumnModel)) { log.warning("Column must be a child of a columnModel. Found " + parent.getClass()) } parent.addColumn(node) } void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (!(parent instanceof TableColumn)) { log.warning("Renderer must be a child of a tableColumn. Found " + parent.getClass()) } if (child instanceof TableCellRenderer) { switch (builder.getCurrentName()) { case "headerRenderer": child.tableHeader = true parent.headerRenderer = child break; case "cellRenderer": child.tableHeader = false parent.cellRenderer = child break; } } } } groovy-1.8.6/src/main/groovy/swing/factory/InternalFrameFactory.groovy0000644001501200150120000000217311627206700025561 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JInternalFrame class InternalFrameFactory extends RootPaneContainerFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (FactoryBuilderSupport.checkValueIsType(value, name, JInternalFrame.class)) { return value; } JInternalFrame frame = new JInternalFrame(); return frame; } }groovy-1.8.6/src/main/groovy/swing/factory/GridBagFactory.groovy0000644001501200150120000001172611627206700024335 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.util.FactoryBuilderSupport import javax.swing.RootPaneContainer import java.util.Map import java.awt.Insets import java.awt.GridBagConstraints import java.awt.Container import java.awt.GridBagLayout import java.awt.Component public class GridBagFactory extends LayoutFactory { public GridBagFactory() { super(GridBagLayout, true) } public void addLayoutProperties(context) { addLayoutProperties(context, GridBagConstraints) } public static void processGridBagConstraintsAttributes(FactoryBuilderSupport builder, Object node, Map attributes) { // if we are not a component, don't do anything if (!(node instanceof Component)) { return } // an explicit constraints means don't do anything def constraintsAttr = builder?.context?.getAt(LayoutFactory.DELEGATE_PROPERTY_CONSTRAINT) ?: LayoutFactory.DEFAULT_DELEGATE_PROPERTY_CONSTRAINT if (attributes.containsKey(constraintsAttr)) { return } // if there are cached constraints, don't do it again, we need to be idempotent... if (builder.getContext().containsKey("constraints")) { return } // next, check to be sure we are in an appropriate container Object parent = builder.getCurrent() if (parent instanceof RootPaneContainer) { if (!(((RootPaneContainer)parent).getContentPane().getLayout() instanceof GridBagLayout)) { return } } else if (parent instanceof Container) { if (!(((Container)parent).getLayout() instanceof GridBagLayout)) { return } } else { return } // next, look for matching attrs. boolean anyAttrs = false GridBagConstraints gbc = new GridBagConstraints() Object o o = extractAttribute(attributes, "gridx", Number) if (o != null) { gbc.gridx = o anyAttrs = true } o = extractAttribute(attributes, "gridy", Number) if (o != null) { gbc.gridy = o anyAttrs = true } o = extractAttribute(attributes, "gridwidth", Number) if (o != null) { gbc.gridwidth = o anyAttrs = true } o = extractAttribute(attributes, "gridheight", Number) if (o != null) { gbc.gridheight = o anyAttrs = true } o = extractAttribute(attributes, "weightx", Number) if (o != null) { gbc.weightx = o anyAttrs = true } o = extractAttribute(attributes, "weighty", Number) if (o != null) { gbc.weighty = o anyAttrs = true } o = extractAttribute(attributes, "anchor", Number) if (o != null) { gbc.anchor = o anyAttrs = true } o = extractAttribute(attributes, "fill", Number) if (o != null) { gbc.fill = o anyAttrs = true } o = extractAttribute(attributes, "insets", Object) if (o != null) { gbc.insets = o as Insets anyAttrs = true } o = extractAttribute(attributes, "ipadx", Number) if (o != null) { gbc.ipadx = o anyAttrs = true } o = extractAttribute(attributes, "ipady", Number) if (o != null) { gbc.ipady = o anyAttrs = true } // if we find any attrs, stash the constraints if (anyAttrs) { builder.getContext().put("constraints", gbc) } } /** * @return null if not found. * null as a 'not found' works because all attrs except insets * are primitive types, and insets will crash if set to null */ static Object extractAttribute(Map attrs, String name, Class type) { if (attrs.containsKey(name)) { Object o = attrs.get(name) if ((o != null) && type.isAssignableFrom(type)) { attrs.remove(name) return o } else { return null } } else { return null } } } groovy-1.8.6/src/main/groovy/swing/factory/BoxFactory.groovy0000644001501200150120000001212411627206700023557 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Dimension import javax.swing.Box import javax.swing.BoxLayout public class BoxFactory extends ComponentFactory { public BoxFactory() { super(null); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (FactoryBuilderSupport.checkValueIsType(value, name, Box.class)) { return value; } int axis = BoxLayout.X_AXIS; // default to X so it behaves like FlowLayout if (attributes.containsKey("axis")) { Object o = attributes.remove("axis"); if (o instanceof Number) { axis = ((Number)o).intValue(); } } return new Box(axis); } } public class HBoxFactory extends ComponentFactory { public HBoxFactory() { super(null); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return Box.createHorizontalBox(); } } public class HGlueFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return Box.createHorizontalGlue(); } } public class HStrutFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsType(value, name, Number.class); Object num; if (value != null) { num = value; } else { num = attributes.remove("width"); } if (num instanceof Number) { return Box.createHorizontalStrut(((Number) num).intValue()); } else { return Box.createHorizontalStrut(6); } } } public class VBoxFactory extends ComponentFactory { public VBoxFactory() { super(null); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return Box.createVerticalBox(); } } public class VGlueFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return Box.createVerticalGlue(); } } public class VStrutFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsType(value, name, Number.class); Object num; if (value != null) { num = value; } else { num = attributes.remove("height"); } if (num instanceof Number) { return Box.createVerticalStrut(((Number) num).intValue()); } else { return Box.createVerticalStrut(6); } } } public class GlueFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); return Box.createGlue(); } } public class RigidAreaFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); Dimension dim; Object o = attributes.remove("size"); if (o instanceof Dimension) { dim = (Dimension) o; } else { int w, h; o = attributes.remove("width"); w = ((o instanceof Number)) ? ((Number) o).intValue() : 6; o = attributes.remove("height"); h = ((o instanceof Number)) ? ((Number) o).intValue() : 6; dim = new Dimension(w, h); } return Box.createRigidArea(dim); } } groovy-1.8.6/src/main/groovy/swing/factory/LineBorderFactory.groovy0000644001501200150120000000346111627206700025060 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.border.LineBorder /** * accepts attributes:
    * color: java.awt.Color
    * color: java.awt.Color, thickness: int
    * color: java.awt.Color, thickness: int, roundedBorders: boolean
    * */ class LineBorderFactory extends SwingBorderFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') def color = attributes.remove("color") if (color == null) { throw new RuntimeException("color: is a required attribute for $name") } def thickness = attributes.remove("thickness") if (thickness == null) { thickness = 1 } def roundedCorners = attributes.remove("roundedCorners") if (roundedCorners == null) { roundedCorners = false } if (attributes) { throw new RuntimeException("$name does not know how to handle the remaining attibutes: ${attributes.keySet()}") } return new LineBorder(color, thickness, roundedCorners); } }groovy-1.8.6/src/main/groovy/swing/factory/SeparatorFactory.groovy0000644001501200150120000000266111627206700024774 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JMenu import javax.swing.JPopupMenu.Separator as JPopupMenu_Separator import javax.swing.JSeparator import javax.swing.JToolBar import javax.swing.JToolBar.Separator as JToolBar_Separator // JetGroovy bug public class SeparatorFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); Object parent = builder.getCurrent(); if (parent instanceof JMenu) { return new JPopupMenu_Separator(); } else if (parent instanceof JToolBar) { return new JToolBar_Separator(); } else { return new JSeparator(); } } } groovy-1.8.6/src/main/groovy/swing/factory/BindProxyFactory.groovy0000644001501200150120000000313611627206700024750 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import org.codehaus.groovy.binding.BindingProxy /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.1 */ public class BindProxyFactory extends AbstractFactory { public boolean isLeaf() { return true } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (value == null) { throw new RuntimeException("$name requires a value argument."); } BindingProxy mb = new BindingProxy(value); Object o = attributes.remove("bind"); builder.context.bind = (o instanceof Boolean) && ((Boolean) o).booleanValue() return mb; } public void onNodeCompleted( FactoryBuilderSupport builder, Object parent, Object node ) { if (builder.context.bind) { node.bind() } } } groovy-1.8.6/src/main/groovy/swing/factory/DialogFactory.groovy0000644001501200150120000000340711627206700024232 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Dialog import java.awt.Frame import javax.swing.JDialog public class DialogFactory extends RootPaneContainerFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { JDialog dialog if (FactoryBuilderSupport.checkValueIsType(value, name, JDialog.class)) { dialog = value } else { Object owner = attributes.remove("owner") LinkedList containingWindows = builder.containingWindows // if owner not explicit, use the last window type in the list if ((owner == null) && !containingWindows.isEmpty()) { owner = containingWindows.getLast() } if (owner instanceof Frame) { dialog = new JDialog((Frame) owner) } else if (owner instanceof Dialog) { dialog = new JDialog((Dialog) owner) } else { dialog = new JDialog() } } handleRootPaneTasks(builder, dialog, attributes) return dialog } } groovy-1.8.6/src/main/groovy/swing/factory/CompoundBorderFactory.groovy0000644001501200150120000000447511627206700025763 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.border.Border import javax.swing.border.CompoundBorder class CompoundBorderFactory extends SwingBorderFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') Border border = null if (value instanceof List) { switch (value.size()) { case 0: throw new RuntimeException("$name does not accept an empty array as an value argument") case 1: border = value[0] break case 2: border = new CompoundBorder(value[0], value[1]) break case 3: default: border = new CompoundBorder(value[0], value[1]) border = value[2..-1].inject(border) {that, it -> new CompoundBorder(that, it) } break; } } if (!border && attributes) { if (value) { throw new RuntimeException("$name only accepts an array of borders as a value argument") } def inner = attributes.remove("inner") def outer = attributes.remove("outer") if (inner instanceof Border && outer instanceof Border) { border = new CompoundBorder(outer, inner) } } if (!border) { throw new RuntimeException("$name only accepts an array of javax.swing.border.Border or an inner: and outer: attribute") } return border } }groovy-1.8.6/src/main/groovy/swing/factory/FormattedTextFactory.groovy0000644001501200150120000000263411627206700025626 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.text.Format import javax.swing.JFormattedTextField public class FormattedTextFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); //TODO expand value arg to take format JFormattedTextField ftf; if (attributes.containsKey("format")) { ftf = new JFormattedTextField((Format) attributes.remove("format")); } else if (attributes.containsKey("value")) { ftf = new JFormattedTextField(attributes.remove("value")); } else { ftf = new JFormattedTextField(); } return ftf; } } groovy-1.8.6/src/main/groovy/swing/factory/RendererFactory.groovy0000644001501200150120000000407011627206700024576 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.impl.ClosureRenderer import java.awt.Component import javax.swing.JList import javax.swing.JTree /** * @author Danno Ferrin */ class RendererFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { FactoryBuilderSupport.checkValueIsNull value, name return new ClosureRenderer() } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (child instanceof Component) { parent.children += child } } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { node.update = builder.context.updateClosure if (parent instanceof JTree) { parent.cellRenderer = node } else if (parent instanceof JList) { parent.cellRenderer = node } } } class RendererUpdateFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { return Collections.emptyMap() } public boolean isHandlesNodeChildren() { return true; } public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) { builder.parentContext.updateClosure = childContent return false } } groovy-1.8.6/src/main/groovy/swing/factory/ImageIconFactory.groovy0000644001501200150120000000705111627206700024665 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Image import javax.swing.ImageIcon class ImageIconFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { if (value == null) { if (attributes.containsKey("image")) { value = attributes.remove("image") if (!(value instanceof Image)) { throw new RuntimeException("In $name image: attributes must be of type java.awt.Image") } } else if (attributes.containsKey("url")) { value = attributes.remove("url") if (!(value instanceof URL)) { throw new RuntimeException("In $name url: attributes must be of type java.net.URL") } } else if (attributes.containsKey("file")) { value = attributes.remove("file") if (value instanceof GString) value = value as String if (value instanceof File) { value = value.toURL() } else if (!(value instanceof String)) { throw new RuntimeException("In $name file: attributes must be of type java.io.File or a string") } } } else if (value instanceof GString) { value = value as String } // not else if so we can adjust for the case of file string where the file does not exist def resource = null if ((value == null) && (attributes.containsKey("resource"))) { resource = attributes.remove('resource') } else if ((value instanceof String) && !(new File(value).exists())) { resource = value } if (resource != null) { def klass = builder.context.owner def origValue = value if (attributes.containsKey("class")) { klass = attributes.remove("class") } if (klass == null) { klass = ImageIconFactory } else if (!(klass instanceof Class)) { klass = klass.class } // for now try URL approach. // we may need to extract the byte[] for some packaging cases value = klass.getResource(resource) if (value == null) { throw new RuntimeException("In $name the value argument '$origValue' does not refer to a file or a class resource") } } if (value == null) { throw new RuntimeException("$name has neither a value argument or one of image:, url:, file:, or resource:") } // exploit multi-dispatch in constructor calls if (attributes.containsKey("description")) { return new ImageIcon(value, attributes.remove("description")) } else { return new ImageIcon(value) } } } groovy-1.8.6/src/main/groovy/swing/factory/BindFactory.groovy0000644001501200150120000003261711707612044023715 0ustar miguelmiguel/* * Copyright 2007-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.SwingBuilder import groovy.swing.binding.* import java.util.Map.Entry import org.codehaus.groovy.binding.* /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.1 */ public class BindFactory extends AbstractFactory { public static final String CONTEXT_DATA_KEY = "BindFactoryData"; final Map syntheticBindings public BindFactory() { syntheticBindings = new HashMap() // covers JTextField.text // covers JTextPane.text // covers JTextArea.text // covers JEditorPane.text syntheticBindings.putAll(JTextComponentProperties.syntheticProperties) // covers JCheckBox.selected // covers JCheckBoxMenuItem.selected // covers JRadioButton.selected // covers JRadioButtonMenuItem.selected // covers JToggleButton.selected syntheticBindings.putAll(AbstractButtonProperties.syntheticProperties) // covers JSlider.value syntheticBindings.putAll(JSliderProperties.syntheticProperties) // covers JScrollBar.value syntheticBindings.putAll(JScrollBarProperties.syntheticProperties) // JComboBox.elements / items // JComboBox.selectedElement / selectedItem syntheticBindings.putAll(JComboBoxProperties.syntheticProperties) // JList.selectedElement / selectedItem / selectedElements / selectedItems / selectedIndex syntheticBindings.putAll(JListProperties.syntheticProperties) // JSpinner.value syntheticBindings.putAll(JSpinnerProperties.syntheticProperties) // other properties handled in JSR-295 // JTable.elements // JTable.selectedElement // JTable.selectedElements syntheticBindings.putAll(JTableProperties.syntheticProperties); // JTree.root // JTree.selectedElement // JTree.selectedElements // covers JComponent.size // covers JComponent.width // covers JComponent.height // covers JComponent.bounds // covers JComponent.x // covers JComponent.y // covers JComponent.visible syntheticBindings.putAll(JComponentProperties.syntheticProperties) } /** * Accepted Properties... * * group? * source ((sourceProperty) | (sourceEvent sourceValue)) * (target targetProperty)? (? use default javabeans property if targetProperty is not present?) * * * @param builder * @param name * @param value * @param attributes * @return the newly created instance * @throws InstantiationException * @throws IllegalAccessException */ public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { Object source = attributes.remove("source") Object target = attributes.remove("target") Object update = attributes.get("update") Map bindContext = builder.context.get(CONTEXT_DATA_KEY) ?: [:] if (bindContext.isEmpty()) { builder.context.put(CONTEXT_DATA_KEY, bindContext) } TargetBinding tb = null if (target != null) { String targetProperty = attributes.remove("targetProperty") ?: value tb = new PropertyBinding(target, targetProperty, update) if (source == null) { // if we have a target but no source assume the build context is the source and return def result if (attributes.remove("mutual")) { result = new MutualPropertyBinding(null, null, tb, this.&getTriggerBinding) } else { result = tb } def newAttributes = [:] newAttributes.putAll(attributes) bindContext.put(result, newAttributes) attributes.clear() return result } } FullBinding fb boolean sea = attributes.containsKey("sourceEvent") boolean sva = attributes.containsKey("sourceValue") boolean spa = attributes.containsKey("sourceProperty") || value if (sea && sva && !spa) { // entirely event triggered binding Closure queryValue = (Closure) attributes.remove("sourceValue") ClosureSourceBinding csb = new ClosureSourceBinding(queryValue) String trigger = (String) attributes.remove("sourceEvent") EventTriggerBinding etb = new EventTriggerBinding(source, trigger) fb = etb.createBinding(csb, tb) } else if (spa && !(sea && sva)) { // partially property driven binding String property = attributes.remove("sourceProperty") ?: value PropertyBinding pb = new PropertyBinding(source, property, update) TriggerBinding trigger if (sea) { // source trigger comes from an event String triggerName = (String) attributes.remove("sourceEvent") trigger = new EventTriggerBinding(source, triggerName) } else { // source trigger comes from a property change // this method will also check for synthetic properties trigger = getTriggerBinding(pb) } SourceBinding sb; if (sva) { // source value comes from a value closure Closure queryValue = (Closure) attributes.remove("sourceValue") sb = new ClosureSourceBinding(queryValue) } else { // source value is the property value sb = pb } // check for a mutual binding (bi-directional) if (attributes.remove("mutual")) { fb = new MutualPropertyBinding(trigger, sb, tb, this.&getTriggerBinding) } else { fb = trigger.createBinding(sb, tb) } } else if (!(sea || sva || spa)) { // if no sourcing is defined then assume we are a closure binding and return def newAttributes = [:] newAttributes.putAll(attributes) def ctb = new ClosureTriggerBinding(syntheticBindings) bindContext.put(ctb, newAttributes) attributes.clear() return ctb } else { throw new RuntimeException("Both sourceEvent: and sourceValue: cannot be specified along with sourceProperty: or a value argument") } if (attributes.containsKey("value")) { bindContext.put(fb, [value: attributes.remove("value")]) } bindContext.get(fb, [:]).put('update', update) Object o = attributes.remove("bind") if (((o == null) && !attributes.containsKey('group')) || ((o instanceof Boolean) && ((Boolean) o).booleanValue())) { fb.bind() } if ((attributes.group instanceof AggregateBinding) && (fb instanceof BindingUpdatable)) { attributes.remove('group').addBinding(fb) } builder.addDisposalClosure(fb.&unbind) return fb } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { super.onNodeCompleted(builder, parent, node); if (node instanceof FullBinding && node.sourceBinding && node.targetBinding) { try { node.update() } catch (Exception ignored) { // don't throw out to top } try { node.rebind() } catch (Exception ignored) { // don't throw out to top } } } public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object node, Map attributes) { attributes.remove('update') true } public boolean isLeaf() { return false; } public boolean isHandlesNodeChildren() { return true; } public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) { if ((node instanceof FullBinding) && (node.converter == null)) { node.converter = childContent return false } else if (node instanceof ClosureTriggerBinding) { node.closure = childContent return false; } else if (node instanceof TriggerBinding) { def bindAttrs = builder.context.get(CONTEXT_DATA_KEY)[node] ?: [:] if (!bindAttrs.containsKey("converter")) { bindAttrs["converter"] = childContent return false; } } throw new RuntimeException("Binding nodes do not accept child content when a converter is already specified") } public TriggerBinding getTriggerBinding(PropertyBinding psb) { String property = psb.propertyName Class currentClass = psb.bean.getClass() while (currentClass != null) { // should we check interfaces as well? if so at what level? def trigger = (TriggerBinding) syntheticBindings.get("$currentClass.name#$property" as String) if (trigger != null) { return trigger } currentClass = currentClass.getSuperclass() } //TODO inspect the bean info and throw an error if the property is not observable and not bind:false? return psb } public bindingAttributeDelegate(FactoryBuilderSupport builder, def node, def attributes) { Iterator iter = attributes.entrySet().iterator() Map bindContext = builder.context.get(CONTEXT_DATA_KEY) ?: [:] while (iter.hasNext()) { Entry entry = (Entry) iter.next() String property = entry.key.toString() Object value = entry.value def bindAttrs = bindContext.get(value) ?: [:] def idAttr = builder.getAt(SwingBuilder.DELEGATE_PROPERTY_OBJECT_ID) ?: SwingBuilder.DEFAULT_DELEGATE_PROPERTY_OBJECT_ID def id = bindAttrs.remove(idAttr) if (bindAttrs.containsKey("value")) { node."$property" = bindAttrs.remove("value") } def update = bindAttrs.get('update') FullBinding fb if (value instanceof MutualPropertyBinding) { fb = (FullBinding) value PropertyBinding psb = new PropertyBinding(node, property, update) if (fb.sourceBinding == null) { fb.sourceBinding = psb finishContextualBinding(fb, builder, bindAttrs, id) } else if (fb.targetBinding == null) { fb.targetBinding = psb } } else if (value instanceof FullBinding) { fb = (FullBinding) value fb.targetBinding = new PropertyBinding(node, property, update) } else if (value instanceof TargetBinding) { PropertyBinding psb = new PropertyBinding(node, property, update) fb = getTriggerBinding(psb).createBinding(psb, value) finishContextualBinding(fb, builder, bindAttrs, id) } else if (value instanceof ClosureTriggerBinding) { PropertyBinding psb = new PropertyBinding(node, property, update) fb = value.createBinding(value, psb); finishContextualBinding(fb, builder, bindAttrs, id) } else { continue } try { fb.update() } catch (Exception e) { // just eat it? } try { fb.rebind() } catch (Exception e) { // just eat it? } // this is why we cannot use entrySet().each { } iter.remove() } } private def finishContextualBinding(FullBinding fb, FactoryBuilderSupport builder, bindAttrs, id) { bindAttrs.remove('update') Object bindValue = bindAttrs.remove("bind") bindAttrs.each {k, v -> fb."$k" = v} if ((bindValue == null) || ((bindValue instanceof Boolean) && ((Boolean) bindValue).booleanValue())) { fb.bind() } builder.addDisposalClosure(fb.&unbind) // replaces ourselves in the variables // id: is lost to us by now, so we just assume that any storage of us is a goner as well //builder.getVariables().each{ Map.Entry me -> if (value.is(me.value)) me.setValue fb} if (id) builder.setVariable(id, fb) } } groovy-1.8.6/src/main/groovy/swing/factory/TitledBorderFactory.groovy0000644001501200150120000000700411707612044025414 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Color import java.awt.Font import javax.swing.border.Border import javax.swing.border.TitledBorder /** * The node must be called with either a value argument or a title: attribute.
    * The following attributes are optional.
    * position: one of "default", "aboveTop", "top", "belowTop", "aboveBottom", "bottom", "belowBottom", or a constant from javax.swing.border.TitledBorder * justification: one of "default", "left", "center", "right", "leading", "trailing", or a constant from javax.swing.border.TitledBorder * border: javax.swing.Border, some other border, if unset the look and feel default will be used (re * color: java.awt.Color the color of the text for the title * font: java.awt.Font the font of the text for the title */ class TitledBorderFactory extends SwingBorderFactory { static final Map positions = [ 'default': TitledBorder.DEFAULT_POSITION, aboveTop: TitledBorder.ABOVE_TOP, top: TitledBorder.TOP, belowTop: TitledBorder.BELOW_TOP, aboveBottom: TitledBorder.ABOVE_BOTTOM, bottom: TitledBorder.BOTTOM, belowBottom: TitledBorder.BELOW_BOTTOM, ] static final Map justifications = [ 'default': TitledBorder.DEFAULT_JUSTIFICATION, left: TitledBorder.LEFT, center: TitledBorder.CENTER, right: TitledBorder.RIGHT, leading: TitledBorder.LEADING, trailing: TitledBorder.TRAILING, ] public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') String title if (value) { title = value as String if (attributes.containsKey("title")) { throw new RuntimeException("$name cannot have both a value attribute and an attribute title:") } } else { title = attributes.remove("title") as String } TitledBorder border = new TitledBorder(title) def position = attributes.remove("position") position = positions[position] ?: position if (position instanceof Integer) { border.setTitlePosition(position) } def justification = attributes.remove("justification") justification = justifications[justification] ?: justification if (justification instanceof Integer) { border.setTitleJustification(justification) } Border otherBorder = attributes.remove("border") if (otherBorder != null) { border.setBorder(otherBorder) } Color color = attributes.remove("color") if (color) { border.setTitleColor(color) } Font font = attributes.remove("font") if (font) { border.setTitleFont(font) } return border } } groovy-1.8.6/src/main/groovy/swing/factory/TableModelFactory.groovy0000644001501200150120000001221611627206700025041 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.model.DefaultTableModel import groovy.model.ValueHolder import groovy.model.ValueModel import java.beans.PropertyChangeListener import java.beans.PropertyChangeEvent import javax.swing.JTable import javax.swing.table.TableModel public class TableModelFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { if (FactoryBuilderSupport.checkValueIsType(value, name, TableModel.class)) { return value; } else if (attributes.get(name) instanceof TableModel) { return attributes.remove(name); } else { ValueModel model = (ValueModel) attributes.remove("model"); if (model == null) { Object list = attributes.remove("list"); if (list == null) { list = new ArrayList(); } model = new ValueHolder(list); } return new DefaultTableModel(model); } } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { if ((node.columnCount > 0) && (parent instanceof JTable)) { parent.autoCreateColumnsFromModel = false; PropertyChangeListener listener = {e -> if ((e.propertyName == 'model') && e.newValue instanceof DefaultTableModel) { e.source.columnModel = e.newValue.columnModel e.source.revalidate() e.source.repaint() } } as PropertyChangeListener; parent.addPropertyChangeListener('model', listener) builder.addDisposalClosure( {parent.removePropertyChangeListener('model', listener)}) // the table has already set the model, so fire the listener manually listener.propertyChange(new PropertyChangeEvent(parent, 'model', null, node)) } } } public class PropertyColumnFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); Object current = builder.getCurrent(); if (current instanceof DefaultTableModel) { DefaultTableModel model = (DefaultTableModel) current; String property = (String) attributes.remove("propertyName"); if (property == null) { throw new IllegalArgumentException("Must specify a property for a propertyColumn"); } Object header = attributes.remove("header"); if (header == null) { header = ""; } Class type = (Class) attributes.remove("type"); if (type == null) { type = Object.class; } Boolean editable = (Boolean) attributes.remove("editable"); if (editable == null) { editable = Boolean.TRUE; } return model.addPropertyColumn(header, property, type, editable.booleanValue()); } else { throw new RuntimeException("propertyColumn must be a child of a tableModel"); } } } public class ClosureColumnFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); Object current = builder.getCurrent(); if (current instanceof DefaultTableModel) { DefaultTableModel model = (DefaultTableModel) current; Object header = attributes.remove("header"); if (header == null) { header = ""; } Closure readClosure = (Closure) attributes.remove("read"); if (readClosure == null) { throw new IllegalArgumentException("Must specify 'read' Closure property for a closureColumn"); } Closure writeClosure = (Closure) attributes.remove("write"); Class type = (Class) attributes.remove("type"); if (type == null) { type = Object.class; } return model.addClosureColumn(header, readClosure, writeClosure, type); } else { throw new RuntimeException("closureColumn must be a child of a tableModel"); } } } groovy-1.8.6/src/main/groovy/swing/factory/ScrollPaneFactory.groovy0000644001501200150120000000274211627206700025076 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Component import java.awt.Window import javax.swing.JScrollPane import javax.swing.JViewport class ScrollPaneFactory extends BeanFactory { public ScrollPaneFactory() { this(JScrollPane) } public ScrollPaneFactory(Class klass) { super(klass, false); } public void setChild(FactoryBuilderSupport factory, Object parent, Object child) { if (!(child instanceof Component) || (child instanceof Window)) { return; } if (parent.getViewport()?.getView() != null) { throw new RuntimeException("ScrollPane can only have one child component"); } if (child instanceof JViewport) { parent.setViewport(child); } else { parent.setViewportView(child); } } }groovy-1.8.6/src/main/groovy/swing/factory/ButtonGroupFactory.groovy0000644001501200150120000000404611627206700025323 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory /** * Created by IntelliJ IDEA. * User: Danno.Ferrin * Date: Jul 11, 2008 * Time: 9:08:24 PM * To change this template use File | Settings | File Templates. */ import javax.swing.AbstractButton import javax.swing.ButtonGroup class ButtonGroupFactory extends BeanFactory { public static final String DELEGATE_PROPERTY_BUTTON_GROUP = "_delegateProperty:buttonGroup"; public static final String DEFAULT_DELEGATE_PROPERTY_BUTTON_GROUP = "buttonGroup"; public ButtonGroupFactory() { super(ButtonGroup, true) } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context[DELEGATE_PROPERTY_BUTTON_GROUP] = attributes.remove("buttonGroupProperty") ?: DEFAULT_DELEGATE_PROPERTY_BUTTON_GROUP return super.newInstance(builder, name, value, attributes); } public static buttonGroupAttributeDelegate(def builder, def node, def attributes) { def buttonGroupAttr = builder?.context?.getAt(DELEGATE_PROPERTY_BUTTON_GROUP) ?: DEFAULT_DELEGATE_PROPERTY_BUTTON_GROUP if (attributes.containsKey(buttonGroupAttr)) { def o = attributes.get(buttonGroupAttr) if ((o instanceof ButtonGroup) && (node instanceof AbstractButton)) { node.model.group = o attributes.remove(buttonGroupAttr) } } } }groovy-1.8.6/src/main/groovy/swing/factory/ListFactory.groovy0000644001501200150120000000520211627206700023741 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import javax.swing.JList import groovy.swing.binding.JListMetaMethods /** * Create a JList, and handle the optional items attribute. * * @author HuberB1 */ public class ListFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { // FactoryBuilderSupport.checkValueIsType(value, name, JList) JList list Object items = attributes.get("items") if (items instanceof Vector) { list = new JList(attributes.remove("items")) } else if (items instanceof List) { List l = (List) attributes.remove("items") list = new JList(l.toArray()) } else if (items instanceof Object[]) { list = new JList(attributes.remove("items")) } else if (value instanceof JList) { list = value } else if (value instanceof Vector) { list = new JList(value) } else if (value instanceof List) { List l = (List) value list = new JList(l.toArray()) } else if (value instanceof Object[]) { list = new JList(value) } else { list = new JList() } JListMetaMethods.enhanceMetaClass(list) return list } public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object node, Map attributes) { if (attributes.containsKey("listData")) { def listData = attributes.remove("listData") if (listData instanceof Vector || listData instanceof Object[]) { node.listData = listData } else if (listData instanceof Collection) { node.listData = listData.toArray() } else { // allow any iterable ?? node.listData = listData.collect([]){it} as Object[] } } return true } } groovy-1.8.6/src/main/groovy/swing/factory/BevelBorderFactory.groovy0000644001501200150120000000510611627206700025224 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import java.awt.Color import javax.swing.BorderFactory /** * accepts no value * accepts attributes:
    * none
    * highlight: java.awt.Color, shadow: java.awt.Color
    * highlightOuter: java.awt.Color, highlightInner: java.awt.Color, shadowOuter: java.awt.Color, shadowInner: java.awt.Color
    * */ class BevelBorderFactory extends SwingBorderFactory { final int type; public BevelBorderFactory(int newType) { type = newType; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { builder.context.applyBorderToParent = attributes.remove('parent') // no if-else-if chain so that we can have one attribute failure block if (attributes.containsKey("highlight")) { Color highlight = attributes.remove("highlight") Color shadow = attributes.remove("shadow") if (highlight && shadow && !attributes) { return BorderFactory.createBevelBorder(type, highlight, shadow); } } if (attributes.containsKey("highlightOuter")) { Color highlightOuter = attributes.remove("highlightOuter") Color highlightInner = attributes.remove("highlightInner") Color shadowOuter = attributes.remove("shadowOuter") Color shadowInner = attributes.remove("shadowInner") if (highlightOuter && highlightInner && shadowOuter && shadowInner && !attributes) { return BorderFactory.createBevelBorder(type, highlightOuter, highlightInner, shadowOuter, shadowInner); } } if (attributes) { throw new RuntimeException("$name only accepts no attributes, or highlight: and shadow: attributes, or highlightOuter: and highlightInner: and shadowOuter: and shadowInner: attributes") } return BorderFactory.createBevelBorder(type); } }groovy-1.8.6/src/main/groovy/swing/factory/ActionFactory.groovy0000644001501200150120000001201511707612044024244 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.impl.DefaultAction import javax.swing.Action import javax.swing.JComponent import javax.swing.KeyStroke import org.codehaus.groovy.runtime.InvokerHelper /** * * @author Danno Ferrin */ public class ActionFactory extends AbstractFactory { public boolean isHandlesNodeChildren() { return true } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { Action action if (FactoryBuilderSupport.checkValueIsTypeNotString(value, name, Action.class)) { action = (Action) value } else if (attributes.get(name) instanceof Action) { action = (Action) attributes.remove(name) } else { action = new DefaultAction() } return action } public boolean onHandleNodeAttributes( FactoryBuilderSupport builder, Object action, Map attributes) { if ((attributes.get("closure") instanceof Closure) && (action instanceof DefaultAction)){ Closure closure = (Closure) attributes.remove("closure") ((DefaultAction)action).setClosure(closure) } Object accel = attributes.remove("accelerator") if (accel != null) { KeyStroke stroke = null if (accel instanceof KeyStroke) { stroke = (KeyStroke) accel } else { stroke = KeyStroke.getKeyStroke(accel.toString()) } action.putValue(Action.ACCELERATOR_KEY, stroke) } Object mnemonic = attributes.remove("mnemonic") if (mnemonic != null) { if (!(mnemonic instanceof Number)) { mnemonic = mnemonic.toString().charAt(0) } action.putValue(Action.MNEMONIC_KEY, mnemonic as Integer) } for (entry in attributes.entrySet()) { String propertyName = (String) entry.getKey() // first attempt to set as a straight property try { InvokerHelper.setProperty(action, propertyName, entry.getValue()) } catch (MissingPropertyException mpe) { // failing that store them in the action values list // typically standard Action names start with upper case, so lets upper case it propertyName = capitalize(propertyName) action.putValue(propertyName, entry.getValue()) } } return false } public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) { if (!(node instanceof DefaultAction)) { throw new RuntimeException("$builder.currentName only accepts a closure content when the action is generated by the node") } if (node.closure != null) { throw new RuntimeException("$builder.currentName already has an action set via the closure attribute, child content as action not allowed") } node.closure = childContent return false } public void setParent(FactoryBuilderSupport builder, Object parent, Object action) { try { InvokerHelper.setProperty(parent, "action", action) } catch (RuntimeException re) { // must not have an action property... // so we ignore it and go on } Object keyStroke = action.getValue("KeyStroke") if (parent instanceof JComponent) { JComponent component = (JComponent) parent KeyStroke stroke = null if (keyStroke instanceof GString) keyStroke = keyStroke as String if (keyStroke instanceof String) { stroke = KeyStroke.getKeyStroke((String) keyStroke) } else if (keyStroke instanceof KeyStroke) { stroke = (KeyStroke) keyStroke } if (stroke != null) { String key = action.toString() component.getInputMap().put(stroke, key) component.getActionMap().put(key, action) } } } String capitalize(String text) { char ch = text.charAt(0) if (Character.isUpperCase(ch)) { return text } StringBuffer buffer = new StringBuffer(text.length()) buffer.append(Character.toUpperCase(ch)) buffer.append(text.substring(1)) return buffer.toString() } } groovy-1.8.6/src/main/groovy/swing/factory/CollectionFactory.groovy0000644001501200150120000000276611627206700025135 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory /** * This returns a mutable java.util.Collection of some sort, to which items are added. */ public class CollectionFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException { FactoryBuilderSupport.checkValueIsNull(value, name); if (attributes.isEmpty()) { return new ArrayList(); } else { def item = attributes.entrySet().iterator().next(); throw new MissingPropertyException( "The builder element '$name' is a collections element and accepts no attributes", item.key as String, item.value as Class); } } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { parent.add(child) } } groovy-1.8.6/src/main/groovy/swing/factory/CellEditorFactory.groovy0000644001501200150120000000453711715031256025066 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.factory import groovy.swing.impl.ClosureCellEditor import java.awt.Component import javax.swing.JTree /** * @author Alexander Klein */ class CellEditorFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { FactoryBuilderSupport.checkValueIsNull value, name return new ClosureCellEditor(null, attributes) } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (child instanceof Component) { parent.children += child } } public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { node.editorValue = builder.context.editorValueClosure node.prepareEditor = builder.context.prepareEditorClosure parent.cellEditor = node } } class CellEditorGetValueFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { return Collections.emptyMap() } public boolean isHandlesNodeChildren() { return true; } public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) { builder.parentContext.editorValueClosure = childContent return false } } class CellEditorPrepareFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) { return Collections.emptyMap() } public boolean isHandlesNodeChildren() { return true; } public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) { builder.parentContext.prepareEditorClosure = childContent return false } } groovy-1.8.6/src/main/groovy/swing/LookAndFeelHelper.groovy0000644001501200150120000001600511627206700023315 0ustar miguelmiguel/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing import javax.swing.LookAndFeel import javax.swing.UIManager import javax.swing.plaf.metal.DefaultMetalTheme import javax.swing.plaf.metal.MetalLookAndFeel import javax.swing.plaf.metal.MetalTheme class LookAndFeelHelper { // protected so you can subclass and replace the singleton protected static LookAndFeelHelper instance; private LookAndFeelHelper() { // linux GTK bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6389282 UIManager.getInstalledLookAndFeels(); } public static LookAndFeelHelper getInstance() { return instance ?: (instance = new LookAndFeelHelper()) } private Map lafCodeNames = [ // stuff built into various JDKs metal : 'javax.swing.plaf.metal.MetalLookAndFeel', nimbus : getNimbusLAFName(), mac : getAquaLAFName(), motif : 'com.sun.java.swing.plaf.motif.MotifLookAndFeel', windows : 'com.sun.java.swing.plaf.windows.WindowsLookAndFeel', win2k : 'com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel', gtk : 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel', synth : 'javax.swing.plaf.synth.SynthLookAndFeel', // generic aliases in UIManager system : UIManager.getSystemLookAndFeelClassName(), crossPlatform : UIManager.getCrossPlatformLookAndFeelClassName(), // jgoodies, requires external library plastic : 'com.jgoodies.looks.plastic.PlasticLookAndFeel', plastic3D : 'com.jgoodies.looks.plastic.Plastic3DLookAndFeel', plasticXP : 'com.jgoodies.looks.plastic.PlasticXPLookAndFeel', // substance, requires external library substance : getSubstanceLAFName(), // napkin, requires external library napkin : 'net.sourceforge.napkinlaf.NapkinLookAndFeel' ] public String addLookAndFeelAlias(String alias, String className) { lafCodeNames[alias] = className } private Map extendedAttributes = [ 'javax.swing.plaf.metal.MetalLookAndFeel' : [ theme : { laf, theme -> if (!(theme instanceof MetalTheme)) { if (theme == 'ocean') { theme = Class.forName('javax.swing.plaf.metal.OceanTheme').newInstance() } else if (theme == 'steel') { theme = new DefaultMetalTheme(); } else { theme = Class.forName(theme as String).newInstance() } }; MetalLookAndFeel.currentTheme = theme }, boldFonts : { laf, bold -> UIManager.put('swing.boldMetal', bold as Boolean) }, noxp : { laf, xp -> UIManager.put('swing.noxp', bold as Boolean) }, ], 'org.jvnet.substance.SubstanceLookAndFeel' : [ // use setters instead of properties to get multi-dispatch theme: { laf, theme -> laf.setCurrentTheme(theme) }, skin: { laf, skin -> laf.setSkin(skin) }, watermark : { laf, watermark -> laf.setCurrentWatermark(watermark) }, ], ] public String addLookAndFeelAttributeHandler(String className, String attr, Closure handler) { Map attrs = extendedAttributes[className] if (attrs == null) { attrs = [:] extendedAttributes[className] = attrs } attrs[attr] = handler } public boolean isLeaf() { return true } public LookAndFeel lookAndFeel(Object value, Map attributes, Closure initClosure) { LookAndFeel lafInstance String lafClassName if ((value instanceof Closure) && (initClosure == null)) { initClosure = value value = null } if (value == null) { value = attributes.remove('lookAndFeel') } if (value instanceof GString) value = value as String if (FactoryBuilderSupport.checkValueIsTypeNotString(value, 'lookAndFeel', LookAndFeel)) { lafInstance = value lafClassName = lafInstance.class.name } else if (value != null) { lafClassName = lafCodeNames[value] ?: value lafInstance = Class.forName(lafClassName, true, getClass().classLoader).newInstance() } // assume all configuration must be done prior to LAF being installed Map possibleAttributes = extendedAttributes[lafClassName] ?: [:] attributes.each {k, v -> if (possibleAttributes[k]) { possibleAttributes[k](lafInstance, v) } else { try { lafInstance."$k" = v } catch (MissingPropertyException mpe) { throw new RuntimeException("SwingBuilder initialization for the Look and Feel Class $lafClassName does accept the attribute $k") } } } if (initClosure) { initClosure.call(lafInstance) } UIManager.setLookAndFeel(lafInstance) return lafInstance } static String getNimbusLAFName() { for (klass in [ 'com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel', 'sun.swing.plaf.nimbus.NimbusLookAndFeel', 'org.jdesktop.swingx.plaf.nimbus.NimbusLookAndFeel' ]) { try { return Class.forName(klass).getName() } catch (Throwable t) { // ignore it, try the next on the list } } return null; } static String getAquaLAFName() { for (klass in [ 'com.apple.laf.AquaLookAndFeel', 'apple.laf.AquaLookAndFeel' ]) { try { return Class.forName(klass).getName() } catch (Throwable t) { // ignore it, try the next on the list } } return null; } static String getSubstanceLAFName() { for (klass in [ 'org.pushingpixels.substance.api.SubstanceLookAndFeel', 'org.jvnet.substance.SubstanceLookAndFeel' ]) { try { return Class.forName(klass).getName() } catch (Throwable t) { // ignore it, try the next on the list } } return null; } } groovy-1.8.6/src/main/groovy/swing/impl/0000755001501200150120000000000011715031256017522 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/swing/impl/TableLayout.java0000644001501200150120000000364711715031256022624 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JPanel; /** * Represents a HTML style table layout * * @author James Strachan * @version $Revision$ */ public class TableLayout extends JPanel { private int rowCount; private int cellpadding; public TableLayout() { setLayout(new GridBagLayout()); } /** * @deprecated Simply returns this * @return this */ public Component getComponent() { return this; } public int getCellpadding() { return cellpadding; } public void setCellpadding(int cellpadding) { this.cellpadding = cellpadding; } /** * Adds a new cell to the current grid * @param cell the td component */ public void addCell(TableLayoutCell cell) { GridBagConstraints constraints = cell.getConstraints(); constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding); add(cell.getComponent(), constraints); } /** * Creates a new row index for child tags * @return nextRowIndex the row number */ public int nextRowIndex() { return rowCount++; } } groovy-1.8.6/src/main/groovy/swing/impl/DefaultAction.java0000644001501200150120000000250611627206700023112 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import groovy.lang.Closure; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; /** * A default action implementation * * @author James Strachan * @version $Revision$ */ public class DefaultAction extends AbstractAction { private Closure closure; public void actionPerformed(ActionEvent event) { if (closure == null) { throw new NullPointerException("No closure has been configured for this Action"); } closure.call(event); } public Closure getClosure() { return closure; } public void setClosure(Closure closure) { this.closure = closure; } } groovy-1.8.6/src/main/groovy/swing/impl/TableLayoutCell.java0000644001501200150120000001347211627206700023421 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import java.awt.Component; import java.awt.GridBagConstraints; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents a cell in a table layout. * * @author James Strachan * @version $Revision$ */ public class TableLayoutCell { protected static final Logger LOG = Logger.getLogger(TableLayoutCell.class.getName()); private TableLayoutRow parent; private Component component; private GridBagConstraints constraints; private String align; private String valign; public int getColspan() { return colspan; } public int getRowspan() { return rowspan; } private int colspan = 1; private int rowspan = 1; private boolean colfill; private boolean rowfill; public TableLayoutCell(TableLayoutRow parent) { this.parent = parent; } public void addComponent(Component component) { if (this.component != null) { LOG.log(Level.WARNING, "This td cell already has a component: " + component); } this.component = component; parent.addCell(this); } public Component getComponent() { return component; } /** * Sets the horizontal alignment to a case insensitive value of {LEFT, CENTER, RIGHT} * @param align one of 'left', 'center', or 'right' */ public void setAlign(String align) { this.align = align; } /** * Sets the vertical alignment to a case insensitive value of {TOP, MIDDLE, BOTTOM} * @param valign one of 'top', 'middle', 'bottom' */ public void setValign(String valign) { this.valign = valign; } /** * Sets the number of columns that this cell should span. The default value is 1 * @param colspan The default is 1 */ public void setColspan(int colspan) { this.colspan = colspan; } /** * Sets the number of rows that this cell should span. The default value is 1 * @param rowspan The default is 1 */ public void setRowspan(int rowspan) { this.rowspan = rowspan; } /** * Returns the colfill. * @return boolean */ public boolean isColfill() { return colfill; } /** * Returns the rowfill. * @return boolean */ public boolean isRowfill() { return rowfill; } /** * Sets whether or not this column should allow its component to stretch to fill the space available * @param colfill The default is false */ public void setColfill(boolean colfill) { this.colfill = colfill; } /** * Sets whether or not this row should allow its component to stretch to fill the space available * @param rowfill The default is false */ public void setRowfill(boolean rowfill) { this.rowfill = rowfill; } /** * @return the constraints of this cell */ public GridBagConstraints getConstraints() { if (constraints == null) { constraints = createConstraints(); } return constraints; } // Implementation methods //------------------------------------------------------------------------- protected GridBagConstraints createConstraints() { GridBagConstraints answer = new GridBagConstraints(); answer.anchor = getAnchor(); if (colspan < 1) { colspan = 1; } if (rowspan < 1) { rowspan = 1; } if (isColfill()) { answer.fill = isRowfill() ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL; } else { answer.fill = isRowfill() ? GridBagConstraints.VERTICAL : GridBagConstraints.NONE; } answer.weightx = 0.2; answer.weighty = 0; answer.gridwidth = colspan; answer.gridheight = rowspan; return answer; } /** * @return the GridBagConstraints enumeration for anchor */ protected int getAnchor() { boolean isTop = "top".equalsIgnoreCase(valign); boolean isBottom = "bottom".equalsIgnoreCase(valign); if ("center".equalsIgnoreCase(align)) { if (isTop) { return GridBagConstraints.NORTH; } else if (isBottom) { return GridBagConstraints.SOUTH; } else { return GridBagConstraints.CENTER; } } else if ("right".equalsIgnoreCase(align)) { if (isTop) { return GridBagConstraints.NORTHEAST; } else if (isBottom) { return GridBagConstraints.SOUTHEAST; } else { return GridBagConstraints.EAST; } } else { // defaults to left if (isTop) { return GridBagConstraints.NORTHWEST; } else if (isBottom) { return GridBagConstraints.SOUTHWEST; } else { return GridBagConstraints.WEST; } } } } groovy-1.8.6/src/main/groovy/swing/impl/ContainerFacade.java0000644001501200150120000000206711715031256023400 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import java.awt.Component; /** * A facade to an object to which components can be added. * * @author James Strachan * @version $Revision$ * @deprecated This interface is no longer used internally and there * exists no equivalent functionality * Superceded by FactoryBuilderSupport handling. */ public interface ContainerFacade { void addComponent(Component component); } groovy-1.8.6/src/main/groovy/swing/impl/package.html0000644001501200150120000000024311627206700022002 0ustar miguelmiguel package groovy.swing.impl.*

    Implementation classes for SwingBuilder

    groovy-1.8.6/src/main/groovy/swing/impl/ClosureRenderer.java0000644001501200150120000001276411627206700023502 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import groovy.lang.Closure; import javax.swing.*; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellRenderer; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * @author Danno.Ferrin */ public class ClosureRenderer implements ListCellRenderer, TableCellRenderer, TreeCellRenderer { Closure update; List children = new ArrayList(); JList list; JTable table; JTree tree; Object value; boolean selected; boolean focused; boolean leaf; boolean expanded; int row; int column; boolean tableHeader; private boolean defaultRenderer; public ClosureRenderer() { this(null); } public ClosureRenderer(Closure c) { setUpdate(c); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { this.list = list; this.table = null; this.tree = null; this.value = value; this.row = index; this.column = -1; this.selected = isSelected; this.focused = cellHasFocus; this.leaf = false; this.expanded = false; return render(); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { this.list = null; this.table = table; this.tree = null; this.value = value; this.row = row; this.column = column; this.selected = isSelected; this.focused = hasFocus; this.leaf = false; this.expanded = false; return render(); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { this.list = null; this.table = null; this.tree = tree; this.value = value; this.row = row; this.column = -1; this.selected = selected; this.focused = hasFocus; this.leaf = leaf; this.expanded = expanded; return render(); } private Component render() { if (children.isEmpty() || defaultRenderer) { defaultRenderer = true; children.clear(); if (table != null) { TableCellRenderer tcr; if (tableHeader) { tcr = table.getTableHeader().getDefaultRenderer(); } else { tcr = table.getDefaultRenderer(table.getColumnClass(column)); } children.add(tcr.getTableCellRendererComponent(table, value, selected, focused, row, column)); } else if (tree != null) { TreeCellRenderer tcr; tcr = new DefaultTreeCellRenderer(); children.add(tcr.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, focused)); } else if (list != null) { ListCellRenderer lcr = (ListCellRenderer) UIManager.get("List.cellRenderer"); if (lcr == null) { lcr = new DefaultListCellRenderer(); } children.add(lcr.getListCellRendererComponent(list, value, row, selected, focused)); } } Object o = update.call(); if (o instanceof Component) { return (Component) o; } else { return (Component) children.get(0); } } public Closure getUpdate() { return update; } public void setUpdate(Closure update) { if (update != null) { update.setDelegate(this); update.setResolveStrategy(Closure.DELEGATE_FIRST); } this.update = update; } public void setTableHeader(boolean tableHeader) { this.tableHeader = tableHeader; } public boolean isTableHeader() { return tableHeader; } public List getChildren() { return children; } public JList getList() { return list; } public JTable getTable() { return table; } public Object getValue() { return value; } public boolean isSelected() { return selected; } public boolean isFocused() { return focused; } public int getRow() { return row; } public int getColumn() { return column; } public JTree getTree() { return tree; } public boolean isLeaf() { return leaf; } public boolean isExpanded() { return expanded; } public boolean isDefaultRenderer() { return defaultRenderer; } } groovy-1.8.6/src/main/groovy/swing/impl/ComponentFacade.java0000644001501200150120000000204311715031256023412 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import java.awt.Component; /** * A facade to an object which contains a component. * * @author James Strachan * @version $Revision$ * @deprecated This interface is no longer used internally and there * exists no equivalent functionality * Superceded by FactoryBuilderSupport handling. */ public interface ComponentFacade { Component getComponent(); } groovy-1.8.6/src/main/groovy/swing/impl/ClosureCellEditor.groovy0000644001501200150120000000651611713765676024406 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl import java.awt.Component import javax.swing.table.TableCellEditor import javax.swing.tree.TreeCellEditor import javax.swing.* /** * @author Alexander Klein */ class ClosureCellEditor extends AbstractCellEditor implements TableCellEditor, TreeCellEditor { Map callbacks = [:] Closure prepareEditor Closure editorValue List children = [] boolean defaultEditor JTable table JTree tree Object value boolean selected boolean expanded boolean leaf int row int column ClosureCellEditor(Closure c = null, Map callbacks = [:]) { this.editorValue = c this.callbacks.putAll(callbacks) } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { this.table = table this.tree = null this.value = value this.selected = isSelected this.expanded = false this.leaf = false this.row = row this.column = column return prepare(); } Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { this.table = null this.tree = tree this.value = value this.selected = isSelected this.expanded = expanded this.leaf = leaf this.row = row this.column = -1 return prepare(); } private Component prepare() { if (children.isEmpty() || defaultEditor) { defaultEditor = true children.clear() if (table) { TableCellEditor tce = table.getDefaultEditor(table.getColumnClass(column)) children.add(tce.getTableCellEditorComponent(table, value, selected, row, column)) } else if (tree) { TreeCellEditor tce = new DefaultCellEditor(new JTextField()) children.add(tce.getTreeCellEditorComponent(tree, value, selected, expanded, leaf, row)) } } Object o = prepareEditor.call() if (o instanceof Component) { return (Component) o } else { return (Component) children[0] } } @Override public Object getCellEditorValue() { editorValue.call() } public void setEditorValue(Closure editorValue) { if (editorValue != null) { editorValue.delegate = this editorValue.resolveStrategy = Closure.DELEGATE_FIRST } this.editorValue = editorValue } public void setPrepareEditor(Closure prepareEditor) { if (prepareEditor != null) { prepareEditor.delegate = this prepareEditor.resolveStrategy = Closure.DELEGATE_FIRST } this.prepareEditor = prepareEditor } @Override public Object invokeMethod(String name, Object args) { def calledMethod = ClosureCellEditor.metaClass.getMetaMethod(name, args) if (callbacks."$name" && callbacks."$name" instanceof Closure) return callbacks."$name".call(calledMethod, this, args) else return calledMethod?.invoke(this, args) } } groovy-1.8.6/src/main/groovy/swing/impl/TableLayoutRow.java0000644001501200150120000000423511627206700023306 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents a row in a table layout * * @author James Strachan * @version $Revision$ */ public class TableLayoutRow { private final TableLayout parent; private final List cells = new ArrayList(); private int rowIndex; public TableLayoutRow(TableLayout tableLayoutTag) { this.parent = tableLayoutTag; } /** * Adds a new cell to this row * @param tag the td element */ public void addCell(TableLayoutCell tag) { int gridx = 0; for (Iterator iter = cells.iterator(); iter.hasNext(); ) { TableLayoutCell cell = (TableLayoutCell) iter.next(); gridx += cell.getColspan(); } tag.getConstraints().gridx = gridx; cells.add(tag); } public void addComponentsForRow() { rowIndex = parent.nextRowIndex(); // iterate through the rows and add each one to the layout... for (Iterator iter = cells.iterator(); iter.hasNext(); ) { TableLayoutCell cell = (TableLayoutCell) iter.next(); GridBagConstraints c = cell.getConstraints(); c.gridy = rowIndex; // add the cell to the table parent.addCell(cell); } } /** * @return the row index of this row */ public int getRowIndex() { return rowIndex; } } groovy-1.8.6/src/main/groovy/swing/impl/Startable.java0000644001501200150120000000201211715031256022301 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.impl; /** * A simple lifecycle method called when an object is fully constructed. * * @author James Strachan * @version $Revision$ * @deprecated This interface is no longer used internally and there * exists no equivalent functionality. * Superceded by FactoryBuilderSupport handling. */ public interface Startable { void start(); } groovy-1.8.6/src/main/groovy/swing/SwingBuilder.groovy0000644001501200150120000005213611707612044022436 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing import java.lang.reflect.InvocationTargetException import java.util.logging.Logger import javax.swing.border.BevelBorder import javax.swing.border.EtchedBorder import javax.swing.table.TableColumn import org.codehaus.groovy.runtime.MethodClosure import groovy.swing.factory.* import java.awt.* import javax.swing.* import java.util.concurrent.Executors import java.util.concurrent.ExecutorService /** * A helper class for creating Swing widgets using GroovyMarkup * * @author James Strachan * @version $Revision$ */ public class SwingBuilder extends FactoryBuilderSupport { private static final ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) // local fields private static final Logger LOG = Logger.getLogger(SwingBuilder.name) private static boolean headless = false public static final String DELEGATE_PROPERTY_OBJECT_ID = "_delegateProperty:id"; public static final String DEFAULT_DELEGATE_PROPERTY_OBJECT_ID = "id"; private static final Random random = new Random() public SwingBuilder(boolean init = true) { super(init) //registerWidgets() headless = GraphicsEnvironment.isHeadless() containingWindows = new LinkedList() this[DELEGATE_PROPERTY_OBJECT_ID] = DEFAULT_DELEGATE_PROPERTY_OBJECT_ID } def registerSupportNodes() { registerFactory("action", new ActionFactory()) registerFactory("actions", new CollectionFactory()) registerFactory("map", new MapFactory()) registerFactory("imageIcon", new ImageIconFactory()) registerFactory("buttonGroup", new ButtonGroupFactory()) addAttributeDelegate(ButtonGroupFactory.&buttonGroupAttributeDelegate) //object id delegate, for propertyNotFound addAttributeDelegate(SwingBuilder.&objectIDAttributeDelegate) addAttributeDelegate(SwingBuilder.&clientPropertyAttributeDelegate) registerFactory("noparent", new CollectionFactory()) registerExplicitMethod("keyStrokeAction", this.&createKeyStrokeAction) registerExplicitMethod("shortcut", this.&shortcut) } def registerBinding() { BindFactory bindFactory = new BindFactory() registerFactory("bind", bindFactory) addAttributeDelegate(bindFactory.&bindingAttributeDelegate) registerFactory("bindProxy", new BindProxyFactory()) registerFactory ("bindGroup", new BindGroupFactory()); } def registerPassThruNodes() { registerFactory("widget", new WidgetFactory(Component, true)) registerFactory("container", new WidgetFactory(Component, false)) registerFactory("bean", new WidgetFactory(Object, true)) } def registerWindows() { registerFactory("dialog", new DialogFactory()) registerBeanFactory("fileChooser", JFileChooser) registerFactory("frame", new FrameFactory()) registerBeanFactory("optionPane", JOptionPane) registerFactory("window", new WindowFactory()) } def registerActionButtonWidgets() { registerFactory("button", new RichActionWidgetFactory(JButton)) registerFactory("checkBox", new RichActionWidgetFactory(JCheckBox)) registerFactory("checkBoxMenuItem", new RichActionWidgetFactory(JCheckBoxMenuItem)) registerFactory("menuItem", new RichActionWidgetFactory(JMenuItem)) registerFactory("radioButton", new RichActionWidgetFactory(JRadioButton)) registerFactory("radioButtonMenuItem", new RichActionWidgetFactory(JRadioButtonMenuItem)) registerFactory("toggleButton", new RichActionWidgetFactory(JToggleButton)) } def registerTextWidgets() { registerFactory("editorPane", new TextArgWidgetFactory(JEditorPane)) registerFactory("label", new TextArgWidgetFactory(JLabel)) registerFactory("passwordField", new TextArgWidgetFactory(JPasswordField)) registerFactory("textArea", new TextArgWidgetFactory(JTextArea)) registerFactory("textField", new TextArgWidgetFactory(JTextField)) registerFactory("formattedTextField", new FormattedTextFactory()) registerFactory("textPane", new TextArgWidgetFactory(JTextPane)) } def registerMDIWidgets() { registerBeanFactory("desktopPane", JDesktopPane) registerFactory("internalFrame", new InternalFrameFactory()) } def registerBasicWidgets() { registerBeanFactory("colorChooser", JColorChooser) registerFactory("comboBox", new ComboBoxFactory()) registerFactory("list", new ListFactory()) registerBeanFactory("progressBar", JProgressBar) registerFactory("separator", new SeparatorFactory()) registerBeanFactory("scrollBar", JScrollBar) registerBeanFactory("slider", JSlider) registerBeanFactory("spinner", JSpinner) registerBeanFactory("tree", JTree) } def registerMenuWidgets() { registerBeanFactory("menu", JMenu) registerBeanFactory("menuBar", JMenuBar) registerBeanFactory("popupMenu", JPopupMenu) } def registerContainers() { registerBeanFactory("panel", JPanel) registerFactory("scrollPane", new ScrollPaneFactory()) registerFactory("splitPane", new SplitPaneFactory()) registerFactory("tabbedPane", new TabbedPaneFactory(JTabbedPane)) registerBeanFactory("toolBar", JToolBar) registerBeanFactory("viewport", JViewport) // sub class? registerBeanFactory("layeredPane", JLayeredPane) } def registerDataModels() { registerBeanFactory("boundedRangeModel", DefaultBoundedRangeModel) // spinner models registerBeanFactory("spinnerDateModel", SpinnerDateModel) registerBeanFactory("spinnerListModel", SpinnerListModel) registerBeanFactory("spinnerNumberModel", SpinnerNumberModel) } def registerTableComponents() { registerFactory("table", new TableFactory()) registerBeanFactory("tableColumn", TableColumn) registerFactory("tableModel", new TableModelFactory()) registerFactory("propertyColumn", new PropertyColumnFactory()) registerFactory("closureColumn", new ClosureColumnFactory()) registerFactory("columnModel", new ColumnModelFactory()) registerFactory("column", new ColumnFactory()) } def registerBasicLayouts() { registerFactory("borderLayout", new LayoutFactory(BorderLayout)) registerFactory("cardLayout", new LayoutFactory(CardLayout)) registerFactory("flowLayout", new LayoutFactory(FlowLayout)) registerFactory("gridLayout", new LayoutFactory(GridLayout)) registerFactory("overlayLayout", new LayoutFactory(OverlayLayout)) registerFactory("springLayout", new LayoutFactory(SpringLayout)) registerFactory("gridBagLayout", new GridBagFactory()) registerBeanFactory("gridBagConstraints", GridBagConstraints) registerBeanFactory("gbc", GridBagConstraints) // shortcut name // constraints delegate addAttributeDelegate(GridBagFactory.&processGridBagConstraintsAttributes) addAttributeDelegate(LayoutFactory.&constraintsAttributeDelegate) } def registerBoxLayout() { registerFactory("boxLayout", new BoxLayoutFactory()) registerFactory("box", new BoxFactory()) registerFactory("hbox", new HBoxFactory()) registerFactory("hglue", new HGlueFactory()) registerFactory("hstrut", new HStrutFactory()) registerFactory("vbox", new VBoxFactory()) registerFactory("vglue", new VGlueFactory()) registerFactory("vstrut", new VStrutFactory()) registerFactory("glue", new GlueFactory()) registerFactory("rigidArea", new RigidAreaFactory()) } def registerTableLayout() { registerFactory("tableLayout", new TableLayoutFactory()) registerFactory("tr", new TRFactory()) registerFactory("td", new TDFactory()) } def registerBorders() { registerFactory("lineBorder", new LineBorderFactory()) registerFactory("loweredBevelBorder", new BevelBorderFactory(BevelBorder.LOWERED)) registerFactory("raisedBevelBorder", new BevelBorderFactory(BevelBorder.RAISED)) registerFactory("etchedBorder", new EtchedBorderFactory(EtchedBorder.LOWERED)) registerFactory("loweredEtchedBorder", new EtchedBorderFactory(EtchedBorder.LOWERED)) registerFactory("raisedEtchedBorder", new EtchedBorderFactory(EtchedBorder.RAISED)) registerFactory("titledBorder", new TitledBorderFactory()) registerFactory("emptyBorder", new EmptyBorderFactory()) registerFactory("compoundBorder", new CompoundBorderFactory()) registerFactory("matteBorder", new MatteBorderFactory()) } def registerRenderers() { RendererFactory renderFactory = new RendererFactory() registerFactory("tableCellRenderer", renderFactory) registerFactory("listCellRenderer", renderFactory) registerFactory("onRender", new RendererUpdateFactory()) registerFactory("cellRenderer", renderFactory) registerFactory("headerRenderer", renderFactory) } def registerEditors() { registerFactory("cellEditor", new CellEditorFactory()) registerFactory("editorValue", new CellEditorGetValueFactory()) registerFactory("prepareEditor", new CellEditorPrepareFactory()) } def registerThreading() { registerExplicitMethod "edt", this.&edt registerExplicitMethod "doOutside", this.&doOutside registerExplicitMethod "doLater", this.&doLater } /** * Do some overrides for standard component handlers, else use super */ public void registerBeanFactory(String nodeName, String groupName, Class klass) { // poke at the type to see if we need special handling if (LayoutManager.isAssignableFrom(klass)) { registerFactory(nodeName, groupName, new LayoutFactory(klass)) } else if (JScrollPane.isAssignableFrom(klass)) { registerFactory(nodeName, groupName, new ScrollPaneFactory(klass)) } else if (JTable.isAssignableFrom(klass)) { registerFactory(nodeName, groupName, new TableFactory(klass)) } else if (JComponent.isAssignableFrom(klass) || JApplet.isAssignableFrom(klass) || JDialog.isAssignableFrom(klass) || JFrame.isAssignableFrom(klass) || JWindow.isAssignableFrom(klass) ) { registerFactory(nodeName, groupName, new ComponentFactory(klass)) } else { super.registerBeanFactory(nodeName, groupName, klass) } } /** * Utility method to run a closure in EDT, * using SwingUtilities.invokeAndWait. * * @param c this closure is run in the EDT */ public SwingBuilder edt(Closure c) { c.setDelegate(this) if (headless || SwingUtilities.isEventDispatchThread()) { c.call(this) } else { Map continuationData = getContinuationData(); try { if (!(c instanceof MethodClosure)) { c = c.curry([this]) } SwingUtilities.invokeAndWait { restoreFromContinuationData(continuationData) c() continuationData = getContinuationData() } } catch (InterruptedException e) { throw new GroovyRuntimeException("interrupted swing interaction", e) } catch (InvocationTargetException e) { throw new GroovyRuntimeException("exception in event dispatch thread", e.getTargetException()) } finally { restoreFromContinuationData(continuationData); } } return this } /** * Utility method to run a closure in EDT, * using SwingUtilities.invokeLater. * * @param c this closure is run in the EDT */ public SwingBuilder doLater(Closure c) { c.setDelegate(this) if (headless) { c.call() } else { if (!(c instanceof MethodClosure)) { c = c.curry([this]) } SwingUtilities.invokeLater(c) } return this } /** * Utility method to run a closure outside of the EDT. *

    * The closure is wrapped in a thread, and the thread is started * immediately, only if the current thread is the EDT, otherwise the * closure will be called immediately. * * @param c this closure is started outside of the EDT */ public SwingBuilder doOutside(Closure c) { c.setDelegate(this) if (!(c instanceof MethodClosure)) { c = c.curry([this]) } if( SwingUtilities.isEventDispatchThread() ) DEFAULT_EXECUTOR_SERVICE.submit(c) else c.call() return this } /** * Factory method to create a SwingBuilder, and run the * the closure in it on the EDT * * @param c run this closure in the new builder using the edt method */ public static SwingBuilder edtBuilder(Closure c) { SwingBuilder builder = new SwingBuilder() return builder.edt(c) } /** * Old factory method static SwingBuilder.build(Closure). * @param c run this closure in the builder using the edt method */ @Deprecated public static SwingBuilder '$static_methodMissing'(String method, Object args) { if (method == 'build' && args.length == 1 && args[0] instanceof Closure) { return edtBuilder(args[0]) } else { throw new MissingMethodException(method, SwingBuilder, args, true) } } /** * Compatibility API. * * @param c run this closure in the builder */ public Object build(Closure c) { c.setDelegate(this) return c.call() } public KeyStroke shortcut(key, modifier = 0) { return KeyStroke.getKeyStroke(key, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | modifier) } public KeyStroke shortcut(String key, modifier = 0) { KeyStroke ks = KeyStroke.getKeyStroke(key) if (ks == null) { return null } else { return KeyStroke.getKeyStroke(ks.getKeyCode(), ks.getModifiers() | modifier | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) } } public static LookAndFeel lookAndFeel(Object laf, Closure initCode) { lookAndFeel([:], laf, initCode) } public static LookAndFeel lookAndFeel(Map attributes = [:], Object laf = null, Closure initCode = null) { // if we get rid of this warning, we can make it static. //if (context) { // LOG.warning "For best result do not call lookAndFeel when it is a child of a SwingBuilder node, initialization of the Look and Feel may be inconsistent." //} LookAndFeelHelper.instance.lookAndFeel(laf, attributes, initCode) } public static LookAndFeel lookAndFeel(Object... lafs) { if (lafs.length == 1) { lookAndFeel([:], lafs[0], null as Closure); } for (Object laf in lafs) { try { // (ab)use multi-methods if (laf instanceof ArrayList) { // multi-method bug return _laf(*laf) } else { return _laf(laf) } } catch (Throwable t) { LOG.fine "Could not instantiate Look and Feel $laf because of ${t}. Attempting next option." } } LOG.warning "All Look and Feel options failed: $lafs" return null } private static LookAndFeel _laf(java.util.List s) { _laf(*s) } private static LookAndFeel _laf(String s, Map m) { lookAndFeel(m, s, null as Closure) } private static LookAndFeel _laf(LookAndFeel laf, Map m) { lookAndFeel(m, laf, null as Closure) } private static LookAndFeel _laf(String s) { lookAndFeel([:], s, null as Closure) } private static LookAndFeel _laf(LookAndFeel laf) { lookAndFeel([:], laf, null as Closure) } public static objectIDAttributeDelegate(def builder, def node, def attributes) { def idAttr = builder.getAt(DELEGATE_PROPERTY_OBJECT_ID) ?: DEFAULT_DELEGATE_PROPERTY_OBJECT_ID def theID = attributes.remove(idAttr) if (theID) { builder.setVariable(theID, node) if(node) { try { if (!node.name) node.name = theID } catch (MissingPropertyException mpe) { // ignore } } } } public static clientPropertyAttributeDelegate(def builder, def node, def attributes) { def clientPropertyMap = attributes.remove("clientProperties") clientPropertyMap.each { key, value -> node.putClientProperty key, value } attributes.findAll { it.key =~ /clientProperty(\w)/ }.each { key, value -> attributes.remove(key) node.putClientProperty(key - "clientProperty", value) } } public void createKeyStrokeAction( Map attributes, JComponent component = null ) { component = findTargetComponent(attributes, component) if( !attributes.containsKey("keyStroke") ) { throw new RuntimeException("You must define a value for keyStroke:") } if( !attributes.containsKey("action") ) { throw new RuntimeException("You must define a value for action:") } def condition = attributes.remove("condition") ?: JComponent.WHEN_FOCUSED if (condition instanceof GString) condition = condition as String if( condition instanceof String ) { condition = condition.toUpperCase().replaceAll(" ","_") if( !condition.startsWith("WHEN_") ) condition = "WHEN_"+condition } switch(condition) { case JComponent.WHEN_FOCUSED: case JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT: case JComponent.WHEN_IN_FOCUSED_WINDOW: // everything is fine, no further processing break case "WHEN_FOCUSED": condition = JComponent.WHEN_FOCUSED break case "WHEN_ANCESTOR_OF_FOCUSED_COMPONENT": condition = JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT break case "WHEN_IN_FOCUSED_WINDOW": condition = JComponent.WHEN_IN_FOCUSED_WINDOW break default: // let's be lenient and assign WHEN_FOCUSED by default condition = JComponent.WHEN_FOCUSED } def actionKey = attributes.remove("actionKey") if( !actionKey ) actionKey = "Action"+Math.abs(random.nextLong()) def keyStroke = attributes.remove("keyStroke") // accept String, Number, KeyStroke, List, List, List def action = attributes.remove("action") if( keyStroke instanceof GString ) keyStroke = keyStroke as String if( keyStroke instanceof String || keyStroke instanceof Number ) keyStroke = [keyStroke] keyStroke.each { ks -> switch(ks) { case KeyStroke: component.getInputMap(condition).put(ks, actionKey) break case String: component.getInputMap(condition).put(KeyStroke.getKeyStroke(ks), actionKey) break case Number: component.getInputMap(condition).put(KeyStroke.getKeyStroke(ks.intValue()), actionKey) break default: throw new RuntimeException("Cannot apply ${ks} as a KeyStroke value.") } } component.actionMap.put(actionKey, action) } private findTargetComponent( Map attributes, JComponent component ) { if( component ) return component if( attributes.containsKey("component") ) { def c = attributes.remove("component") if( !(c instanceof JComponent) ) { throw new RuntimeException("The property component: is not of type JComponent.") } return c } def c = getCurrent() if( c instanceof JComponent ) { return c } throw new RuntimeException("You must define one of the following: a value of type JComponent, a component: attribute or nest this node inside another one that produces a JComponent.") } } groovy-1.8.6/src/main/groovy/swing/binding/0000755001501200150120000000000011707612044020174 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/swing/binding/JComboBoxMetaMethods.groovy0000644001501200150120000000276311627206700025427 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding import javax.swing.ComboBoxModel import javax.swing.JComboBox /** * @author Danno Ferrin */ class JComboBoxMetaMethods { public static void enhanceMetaClass(JComboBox comboBox) { AbstractSyntheticMetaMethods.enhance(comboBox, [ getElements:{-> ComboBoxModel model = delegate.model; def results = [] int size = model.size for (int i = 0; i < size; i++) { results += model.getElementAt(i) } return results }, getSelectedElement:{-> return delegate.selectedItem }, setSelectedElement:{def item-> return delegate.selectedItem = item }, ]); } } groovy-1.8.6/src/main/groovy/swing/binding/JComponentProperties.java0000644001501200150120000001433011627206700025170 0ustar miguelmiguel/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JComponent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Andres Almiray * @since Groovy 1.6 */ public class JComponentProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JComponent.class.getName() + "#size", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "size") { public void componentResized(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#width", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "width") { public void componentResized(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#height", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "height") { public void componentResized(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#bounds", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "bounds") { public void componentResized(ComponentEvent event) { update(); } public void componentMoved(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#x", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "x") { public void componentMoved(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#y", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "y") { public void componentMoved(ComponentEvent event) { update(); } }; } }); result.put(JComponent.class.getName() + "#visible", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractJComponentBinding((PropertyBinding) source, target, "visible") { public void componentHidden(ComponentEvent event) { update(); } public void componentShown(ComponentEvent event) { update(); } }; } }); return result; } } abstract class AbstractJComponentBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ComponentListener { JComponent boundComponent; String propertyName; public AbstractJComponentBinding(PropertyBinding source, TargetBinding target, String propertyName) { super(source, target, JComponent.class, propertyName); source.setNonChangeCheck(true); } public synchronized void syntheticBind() { boundComponent = (JComponent) ((PropertyBinding)sourceBinding).getBean(); boundComponent.addPropertyChangeListener(propertyName, this); boundComponent.addComponentListener(this); } public synchronized void syntheticUnbind() { boundComponent.removePropertyChangeListener(propertyName, this); boundComponent.removeComponentListener(this); boundComponent = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((JComponent)event.getOldValue()).removeComponentListener(this); ((JComponent)event.getNewValue()).addComponentListener(this); } public void componentHidden(ComponentEvent event) {} public void componentShown(ComponentEvent event) {} public void componentMoved(ComponentEvent event) {} public void componentResized(ComponentEvent event) {} } groovy-1.8.6/src/main/groovy/swing/binding/JScrollBarProperties.java0000644001501200150120000000546111627206700025116 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Danno Ferrin * @version $Revision: 7953 $ * @since Groovy 1.1 */ public class JScrollBarProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JScrollBar.class.getName() + "#value", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JScrollBarValueBinding((PropertyBinding) source, target); } }); return result; } } class JScrollBarValueBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ChangeListener { JScrollBar boundScrollBar; public JScrollBarValueBinding(PropertyBinding source, TargetBinding target) { super(source, target, JScrollBar.class, "value"); } public synchronized void syntheticBind() { boundScrollBar = (JScrollBar) ((PropertyBinding)sourceBinding).getBean(); boundScrollBar.addPropertyChangeListener("model", this); boundScrollBar.getModel().addChangeListener(this); } public synchronized void syntheticUnbind() { boundScrollBar.removePropertyChangeListener("model", this); boundScrollBar.getModel().removeChangeListener(this); boundScrollBar = null; } public void setTargetBinding(TargetBinding target) { super.setTargetBinding(target); } public void propertyChange(PropertyChangeEvent event) { update(); ((BoundedRangeModel) event.getOldValue()).removeChangeListener(this); ((BoundedRangeModel) event.getNewValue()).addChangeListener(this); } public void stateChanged(ChangeEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/JSliderProperties.java0000644001501200150120000000522111627206700024447 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.1 */ public class JSliderProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JSlider.class.getName() + "#value", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JSliderValueBinding((PropertyBinding) source, target); } }); return result; } } class JSliderValueBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ChangeListener { JSlider boundSlider; public JSliderValueBinding(PropertyBinding source, TargetBinding target) { super(source, target, JSlider.class, "value"); } public synchronized void syntheticBind() { boundSlider = (JSlider) ((PropertyBinding)sourceBinding).getBean(); boundSlider.addPropertyChangeListener("model", this); boundSlider.getModel().addChangeListener(this); } public synchronized void syntheticUnbind() { boundSlider.removePropertyChangeListener("model", this); boundSlider.getModel().removeChangeListener(this); boundSlider = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((BoundedRangeModel) event.getOldValue()).removeChangeListener(this); ((BoundedRangeModel) event.getNewValue()).addChangeListener(this); } public void stateChanged(ChangeEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/JListMetaMethods.groovy0000644001501200150120000000326711627206700024632 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding import javax.swing.ListModel import javax.swing.JList /** * @author Danno Ferrin * @author Andres Almiray * @since 1.7.5 */ class JListMetaMethods { public static void enhanceMetaClass(JList list) { AbstractSyntheticMetaMethods.enhance(list, [ getElements:{-> ListModel model = delegate.model; def results = [] int size = model.size for (int i = 0; i < size; i++) { results += model.getElementAt(i) } return results }, getSelectedElement:{-> return delegate.selectedValue }, getSelectedElements:{-> return delegate.selectedValues }, setSelectedElement:{def item-> return delegate.setSelectedValue(item, true) }, setSelectedValue:{def item-> return delegate.setSelectedValue(item, true) }, ]); } } groovy-1.8.6/src/main/groovy/swing/binding/package.html0000644001501200150120000000023711627206700022456 0ustar miguelmiguel package groovy.swing.binding.*

    Binding classes for SwingBuilder

    groovy-1.8.6/src/main/groovy/swing/binding/JSpinnerProperties.java0000644001501200150120000000521711627206700024650 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.6.4 */ public class JSpinnerProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JSpinner.class.getName() + "#value", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JSpinnerValueBinding((PropertyBinding) source, target); } }); return result; } } class JSpinnerValueBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ChangeListener { JSpinner boundSlider; public JSpinnerValueBinding(PropertyBinding source, TargetBinding target) { super(source, target, JSpinner.class, "value"); } public synchronized void syntheticBind() { boundSlider = (JSpinner) ((PropertyBinding)sourceBinding).getBean(); boundSlider.addPropertyChangeListener("model", this); boundSlider.getModel().addChangeListener(this); } public synchronized void syntheticUnbind() { boundSlider.removePropertyChangeListener("model", this); boundSlider.getModel().removeChangeListener(this); boundSlider = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((SpinnerModel) event.getOldValue()).removeChangeListener(this); ((SpinnerModel) event.getNewValue()).addChangeListener(this); } public void stateChanged(ChangeEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/JTableMetaMethods.groovy0000644001501200150120000000556111707612044024746 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding import javax.swing.JTable import javax.swing.table.TableColumn import javax.swing.table.TableColumnModel import javax.swing.table.TableModel import org.codehaus.groovy.runtime.InvokerHelper /** * Created by IntelliJ IDEA. * User: Danno.Ferrin * Date: Jun 19, 2008 * Time: 12:46:29 PM * To change this template use File | Settings | File Templates. */ class JTableMetaMethods { public static void enhanceMetaClass(table) { AbstractSyntheticMetaMethods.enhance(table, [ getElements:{-> def model = delegate.model; if (model instanceof javax.swing.table.DefaultTableModel) { return Collections.unmodifiableList(model.getDataVector()) } else if (model instanceof groovy.model.DefaultTableModel) { return Collections.unmodifiableList(model.rows) } }, getSelectedElement:{-> return getElement(delegate, delegate.selectedRow) }, getSelectedElements:{-> def myTable = delegate return myTable.getSelectedRows().collect() { getElement(myTable, it) } } ]); } public static Object getElement(JTable table, int row) { if (row == -1) { return null; } TableModel model = table.model if (model instanceof javax.swing.table.DefaultTableModel) { // could be groovier, but it works and is a well understood idiom Map value = [:] TableColumnModel cmodel = table.columnModel for (int i = 0; i < cmodel.getColumnCount(); i++) { TableColumn c = cmodel.getColumn(i); value.put(c.getIdentifier(), // will fall through to headerValue table.getValueAt(row, c.getModelIndex())) } return value; } else if (model instanceof groovy.model.DefaultTableModel) { Object rowValue = model.getRowsModel().value if (rowValue == null) { return null; } else { return InvokerHelper.asList(rowValue)[row] } } } } groovy-1.8.6/src/main/groovy/swing/binding/AbstractButtonProperties.java0000644001501200150120000000530311627206700026053 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.1 */ public class AbstractButtonProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(AbstractButton.class.getName() + "#selected", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new AbstractButtonSelectedBinding((PropertyBinding) source, target); } }); return result; } } class AbstractButtonSelectedBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ItemListener { AbstractButton boundButton; public AbstractButtonSelectedBinding(PropertyBinding source, TargetBinding target) { super(source, target, AbstractButton.class, "selected"); } public synchronized void syntheticBind() { boundButton = (AbstractButton) ((PropertyBinding) sourceBinding).getBean(); boundButton.addPropertyChangeListener("model", this); boundButton.getModel().addItemListener(this); } public synchronized void syntheticUnbind() { boundButton.removePropertyChangeListener("model", this); boundButton.getModel().removeItemListener(this); boundButton = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((ButtonModel)event.getOldValue()).removeItemListener(this); ((ButtonModel)event.getNewValue()).addItemListener(this); } public void itemStateChanged(ItemEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/JComboBoxProperties.java0000644001501200150120000001362211627206700024741 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; /** * @author Danno Ferrin * @version $Revision: 7953 $ * @since Groovy 1.1 */ public class JComboBoxProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); // to match property name result.put(JComboBox.class.getName() + "#selectedItem", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JComboBoxSelectedElementBinding((PropertyBinding) source, target, "selectedItem"); } }); // to match JSR-295 result.put(JComboBox.class.getName() + "#selectedElement", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JComboBoxSelectedElementBinding((PropertyBinding) source, target, "selectedElement"); } }); result.put(JComboBox.class.getName() + "#selectedIndex", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JComboBoxSelectedIndexBinding((PropertyBinding) source, target); } }); // to match JSR-295 result.put(JComboBox.class.getName() + "#elements", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JComboBoxElementsBinding((PropertyBinding) source, target); } }); return result; } } class JComboBoxSelectedElementBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ItemListener { JComboBox boundComboBox; public JComboBoxSelectedElementBinding(PropertyBinding source, TargetBinding target, String propertyName) { super(source, target, JComboBox.class, propertyName); } public synchronized void syntheticBind() { boundComboBox = (JComboBox) ((PropertyBinding)sourceBinding).getBean(); boundComboBox.addPropertyChangeListener("model", this); boundComboBox.addItemListener(this); } public synchronized void syntheticUnbind() { boundComboBox.removePropertyChangeListener("model", this); boundComboBox.removeItemListener(this); boundComboBox = null; } public void setTargetBinding(TargetBinding target) { super.setTargetBinding(target); } public void propertyChange(PropertyChangeEvent event) { update(); } public void itemStateChanged(ItemEvent e) { update(); } } class JComboBoxSelectedIndexBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ItemListener { JComboBox boundComboBox; public JComboBoxSelectedIndexBinding(PropertyBinding source, TargetBinding target) { super(source, target, JComboBox.class, "selectedIndex"); } public synchronized void syntheticBind() { boundComboBox = (JComboBox) ((PropertyBinding)sourceBinding).getBean(); boundComboBox.addPropertyChangeListener("model", this); boundComboBox.addItemListener(this); } public synchronized void syntheticUnbind() { boundComboBox.removePropertyChangeListener("model", this); boundComboBox.removeItemListener(this); boundComboBox = null; } public void setTargetBinding(TargetBinding target) { super.setTargetBinding(target); } public void propertyChange(PropertyChangeEvent event) { update(); } public void itemStateChanged(ItemEvent e) { update(); } } class JComboBoxElementsBinding extends AbstractSyntheticBinding implements ListDataListener, PropertyChangeListener { JComboBox boundComboBox; public JComboBoxElementsBinding(PropertyBinding propertyBinding, TargetBinding target) { super(propertyBinding, target, JComboBox.class, "elements"); } protected void syntheticBind() { boundComboBox = (JComboBox) ((PropertyBinding)sourceBinding).getBean(); boundComboBox.addPropertyChangeListener("model", this); boundComboBox.getModel().addListDataListener(this); } protected void syntheticUnbind() { boundComboBox.removePropertyChangeListener("model", this); boundComboBox.getModel().removeListDataListener(this); } public void propertyChange(PropertyChangeEvent event) { update(); ((ComboBoxModel) event.getOldValue()).removeListDataListener(this); ((ComboBoxModel) event.getNewValue()).addListDataListener(this); } public void intervalAdded(ListDataEvent e) { update(); } public void intervalRemoved(ListDataEvent e) { update(); } public void contentsChanged(ListDataEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/AbstractSyntheticMetaMethods.groovy0000644001501200150120000000304111627206700027231 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding /** * Created by IntelliJ IDEA. * User: Danno.Ferrin * Date: Jun 19, 2008 * Time: 12:52:31 PM * To change this template use File | Settings | File Templates. */ class AbstractSyntheticMetaMethods { static void enhance(Object o, Map enhancedMethods) { Class klass = o.getClass() MetaClassRegistry mcr = GroovySystem.metaClassRegistry MetaClass mc = mcr.getMetaClass(klass) boolean init = false mcr.removeMetaClass klass //?? //if (!(mc instanceof ExpandoMetaClass)) { mc = new ExpandoMetaClass(klass) init = true //} enhancedMethods.each {k, v -> if (mc.getMetaMethod(k) == null) { mc.registerInstanceMethod(k, v) } } if (init) { mc.initialize() mcr.setMetaClass(klass, mc) } } } groovy-1.8.6/src/main/groovy/swing/binding/JListProperties.groovy0000644001501200150120000001301511627206700024544 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Andres Almiray * @since Groovy 1.7.5 */ public class JListProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); // to match property name result.put(JList.class.getName() + "#selectedValue", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedValue"); } }); // to match JSR-295 result.put(JList.class.getName() + "#selectedElement", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedElement"); } }); // to match property name result.put(JList.class.getName() + "#selectedValues", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedValues"); } }); // to match JSR-295 result.put(JList.class.getName() + "#selectedElements", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedElements"); } }); result.put(JList.class.getName() + "#selectedIndex", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedIndex"); } }); result.put(JList.class.getName() + "#selectedIndices", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListSelectedElementBinding((PropertyBinding) source, target, "selectedIndices"); } }); // to match JSR-295 result.put(JList.class.getName() + "#elements", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JListElementsBinding((PropertyBinding) source, target); } }); return result; } } class JListElementsBinding extends AbstractSyntheticBinding implements ListDataListener, PropertyChangeListener { JList boundList; public JListElementsBinding(PropertyBinding propertyBinding, TargetBinding target) { super(propertyBinding, target, JList.class, "elements"); } protected void syntheticBind() { boundList = (JList) ((PropertyBinding)sourceBinding).getBean(); boundList.addPropertyChangeListener("model", this); boundList.getModel().addListDataListener(this); } protected void syntheticUnbind() { boundList.removePropertyChangeListener("model", this); boundList.getModel().removeListDataListener(this); } public void propertyChange(PropertyChangeEvent event) { update(); ((ListModel) event.getOldValue()).removeListDataListener(this); ((ListModel) event.getNewValue()).addListDataListener(this); } public void intervalAdded(ListDataEvent e) { update(); } public void intervalRemoved(ListDataEvent e) { update(); } public void contentsChanged(ListDataEvent e) { update(); } } class JListSelectedElementBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ListSelectionListener { JList boundList; protected JListSelectedElementBinding(PropertyBinding source, TargetBinding target, String propertyName) { super(source, target, JList.class, propertyName); } public synchronized void syntheticBind() { boundList = (JList) ((PropertyBinding)sourceBinding).getBean(); boundList.addPropertyChangeListener("selectionModel", this); boundList.addListSelectionListener(this); } public synchronized void syntheticUnbind() { boundList.removePropertyChangeListener("selectionModel", this); boundList.removeListSelectionListener(this); boundList = null; } public void setTargetBinding(TargetBinding target) { super.setTargetBinding(target); } public void propertyChange(PropertyChangeEvent event) { update(); } public void valueChanged(ListSelectionEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/JTableProperties.java0000644001501200150120000001120111627206700024247 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: Danno.Ferrin * Date: Jun 18, 2008 * Time: 12:14:16 PM */ public class JTableProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JTable.class.getName() + "#elements", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JTableElementsBinding((PropertyBinding) source, target); } }); result.put(JTable.class.getName() + "#selectedElement", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JTableSelectedElementBinding((PropertyBinding) source, target, "selectedElement"); } }); result.put(JTable.class.getName() + "#selectedElements", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JTableSelectedElementBinding((PropertyBinding) source, target, "selectedElements"); } }); return result; } } class JTableElementsBinding extends AbstractSyntheticBinding implements TableModelListener, PropertyChangeListener { JTable boundTable; public JTableElementsBinding(PropertyBinding propertyBinding, TargetBinding target) { super(propertyBinding, target, JTable.class, "elements"); } protected void syntheticBind() { boundTable = (JTable) ((PropertyBinding)sourceBinding).getBean(); boundTable.addPropertyChangeListener("model", this); boundTable.getModel().addTableModelListener(this); } protected void syntheticUnbind() { boundTable.removePropertyChangeListener("model", this); boundTable.getModel().removeTableModelListener(this); } public void tableChanged(TableModelEvent e) { update(); } public void propertyChange(PropertyChangeEvent event) { update(); ((TableModel) event.getOldValue()).removeTableModelListener(this); ((TableModel) event.getNewValue()).addTableModelListener(this); } } class JTableSelectedElementBinding extends AbstractSyntheticBinding implements PropertyChangeListener, ListSelectionListener { JTable boundTable; protected JTableSelectedElementBinding(PropertyBinding source, TargetBinding target, String propertyName) { super(source, target, JTable.class, propertyName); } public synchronized void syntheticBind() { boundTable = (JTable) ((PropertyBinding)sourceBinding).getBean(); boundTable.addPropertyChangeListener("selectionModel", this); boundTable.getSelectionModel().addListSelectionListener(this); } public synchronized void syntheticUnbind() { boundTable.removePropertyChangeListener("selectionModel", this); boundTable.getSelectionModel().removeListSelectionListener(this); boundTable = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((ListSelectionModel) event.getOldValue()).removeListSelectionListener(this); ((ListSelectionModel) event.getNewValue()).addListSelectionListener(this); } public void valueChanged(ListSelectionEvent e) { update(); } } groovy-1.8.6/src/main/groovy/swing/binding/AbstractSyntheticBinding.java0000644001501200150120000000574511627206700026002 0ustar miguelmiguel/* * Copyright 2007-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.AbstractFullBinding; import org.codehaus.groovy.binding.PropertyBinding; import org.codehaus.groovy.binding.SourceBinding; import org.codehaus.groovy.binding.TargetBinding; /** * Created by IntelliJ IDEA. * User: Danno.Ferrin * Date: Jun 18, 2008 * Time: 1:41:14 PM */ public abstract class AbstractSyntheticBinding extends AbstractFullBinding { boolean bound; String propertyName; Class klass; public AbstractSyntheticBinding(PropertyBinding source, TargetBinding target, Class klass, String propertyName) { this.propertyName = propertyName; this.klass = klass; bound = false; setSourceBinding(source); setTargetBinding(target); } public void bind() { if (!bound) { try { syntheticBind(); bound = true; } catch (RuntimeException re) { try { syntheticUnbind(); } catch (Exception e) { // ignore as we are re-throwing the original cause } throw re; } } } public void unbind() { if (bound) { // fail dirty, no checks bound = false; syntheticUnbind(); } } protected abstract void syntheticBind(); protected abstract void syntheticUnbind(); public void rebind() { if (bound) { unbind(); bind(); } } public void setSourceBinding(SourceBinding source) { if (!(source instanceof PropertyBinding)) { throw new IllegalArgumentException("Only PropertySourceBindings are accepted"); } if (!propertyName.equals(((PropertyBinding) source).getPropertyName())) { throw new IllegalArgumentException("PropertyName must be '" + propertyName + "'"); } Object bean = ((PropertyBinding) source).getBean(); if ((bean == null) || !klass.isAssignableFrom(bean.getClass())) { throw new IllegalArgumentException("SourceBean must be a " + klass.getName()); } super.setSourceBinding(source); } public void setTargetBinding(TargetBinding target) { super.setTargetBinding(target); } } groovy-1.8.6/src/main/groovy/swing/binding/JTextComponentProperties.java0000644001501200150120000000576211627206700026046 0ustar miguelmiguel/* * Copyright 2007-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.swing.binding; import org.codehaus.groovy.binding.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * @author Danno Ferrin * @version $Revision$ * @since Groovy 1.1 */ public class JTextComponentProperties { public static Map getSyntheticProperties() { Map result = new HashMap(); result.put(JTextComponent.class.getName() + "#text", new TriggerBinding() { public FullBinding createBinding(SourceBinding source, TargetBinding target) { return new JTextComponentTextBinding((PropertyBinding) source, target); } }); return result; } } class JTextComponentTextBinding extends AbstractSyntheticBinding implements PropertyChangeListener, DocumentListener { JTextComponent boundTextComponent; public JTextComponentTextBinding(PropertyBinding source, TargetBinding target) { super(source, target, JTextComponent.class, "text"); source.setNonChangeCheck(true); } public synchronized void syntheticBind() { boundTextComponent = (JTextComponent) ((PropertyBinding)sourceBinding).getBean(); boundTextComponent.addPropertyChangeListener("document", this); boundTextComponent.getDocument().addDocumentListener(this); } public synchronized void syntheticUnbind() { boundTextComponent.removePropertyChangeListener("document", this); boundTextComponent.getDocument().removeDocumentListener(this); boundTextComponent = null; } public void propertyChange(PropertyChangeEvent event) { update(); ((Document)event.getOldValue()).removeDocumentListener(this); ((Document)event.getNewValue()).addDocumentListener(this); } public void changedUpdate(DocumentEvent event) { update(); } public void insertUpdate(DocumentEvent event) { update(); } public void removeUpdate(DocumentEvent event) { update(); } } groovy-1.8.6/src/main/groovy/sql/0000755001501200150120000000000011713766062016241 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/sql/ResultSetOutParameter.java0000644001501200150120000000137611627206700023366 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; /** * A ResultSet out parameter. * @author rfuller * */ public interface ResultSetOutParameter extends OutParameter{ } groovy-1.8.6/src/main/groovy/sql/BatchingPreparedStatementWrapper.java0000644001501200150120000000433211707612044025527 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.Tuple; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; /** * Class which delegates to a PreparedStatement but keeps track of * a batch count size. If the batch count reaches the predefined number, * this Statement does an executeBatch() automatically. If batchSize is * zero, then no batching is performed. * * @author Daniel Henrique Alves Lima * @author Paul King */ public class BatchingPreparedStatementWrapper extends BatchingStatementWrapper { private PreparedStatement delegate; private List indexPropList; private Sql sql; public BatchingPreparedStatementWrapper(PreparedStatement delegate, List indexPropList, int batchSize, Logger log, Sql sql) { super(delegate, batchSize, log); this.delegate = delegate; this.indexPropList = indexPropList; this.sql = sql; } public void addBatch(Object[] parameters) throws SQLException { addBatch(Arrays.asList(parameters)); } public void addBatch(List parameters) throws SQLException { if (indexPropList != null) { sql.setParameters(sql.getUpdatedParams(parameters, indexPropList), delegate); } else { sql.setParameters(parameters, delegate); } delegate.addBatch(); batchCount++; if (batchCount == batchSize /* never true for batchSize of 0 */) { int[] result = delegate.executeBatch(); processResult(result); batchCount = 0; } } } groovy-1.8.6/src/main/groovy/sql/ResultSetMetaDataWrapper.java0000644001501200150120000000554411627206700024000 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import java.sql.ResultSetMetaData; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingPropertyException; import groovy.lang.ReadOnlyPropertyException; import org.codehaus.groovy.runtime.InvokerHelper; /** *

    This class defines a wrapper for accessing a specific column in ResultSetMetaData. * This allows iteration over columns using idiomatic Groovy, e.g. *

     * meta.each {col ->
     *   println col.columnName
     * }
     * 
    * All ResultSetMetaData column methods taking a column index * are available on a column either as a no-arg getter or via a property. *

    *

    This wrapper is created by an iterator invoked for ResultSetMetaData. * * @author John Hurst * @see org.codehaus.groovy.runtime.SqlGroovyMethods */ public class ResultSetMetaDataWrapper extends GroovyObjectSupport { private ResultSetMetaData target; private int index; public ResultSetMetaDataWrapper(ResultSetMetaData target, int index) { this.target = target; this.index = index; } private Object[] getIndexedArgs(Object[] originalArgs) { Object[] result = new Object[originalArgs.length + 1]; result[0] = index; for (int i = 0, originalArgsLength = originalArgs.length; i < originalArgsLength; i++) { result[i + 1] = originalArgs[i]; } return result; } @Override public Object invokeMethod(String name, Object args) { Object[] indexedArgs = getIndexedArgs((Object[]) args); return InvokerHelper.invokeMethod(target, name, indexedArgs); } private String getPropertyGetterName(String prop) { if (prop == null || prop.length() < 1) { throw new MissingPropertyException(prop, target.getClass()); } return "get" + prop.substring(0, 1).toUpperCase() + prop.substring(1); } @Override public Object getProperty(String property) { return invokeMethod(getPropertyGetterName(property), new Object[0]); } @Override public void setProperty(String property, Object newValue) { throw new ReadOnlyPropertyException(property, target.getClass()); } } groovy-1.8.6/src/main/groovy/sql/Sql.java0000644001501200150120000046406611713765676017675 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.Closure; import groovy.lang.GString; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import groovy.lang.Tuple; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.SqlGroovyMethods; /** * A facade over Java's normal JDBC APIs providing greatly simplified * resource management and result set handling. Under the covers the * facade hides away details associated with getting connections, * constructing and configuring statements, interacting with the * connection, closing resources and logging errors. Special * features of the facade include using closures to iterate * through result sets, a special GString syntax for representing * prepared statements and treating result sets like collections * of maps with the normal Groovy collection methods available. * *

    Typical usage

    * * First you need to set up your sql instance. There are several constructors * and a few newInstance factory methods available to do this. * In simple cases, you can just provide * the necessary details to set up a connection (e.g. for hsqldb): *
     * def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbcDriver']
     * def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
     * 
    * or if you have an existing connection (perhaps from a connection pool) or a * datasource use one of the constructors: *
     * def sql = new Sql(datasource)
     * 
    * Now you can invoke sql, e.g. to create a table: *
     * sql.execute '''
     *     create table PROJECT (
     *         id integer not null,
     *         name varchar(50),
     *         url varchar(100),
     *     )
     * '''
     * 
    * Or insert a row using JDBC PreparedStatement inspired syntax: *
     * def params = [10, 'Groovy', 'http://groovy.codehaus.org']
     * sql.execute 'insert into PROJECT (id, name, url) values (?, ?, ?)', params
     * 
    * Or insert a row using GString syntax: *
     * def map = [id:20, name:'Grails', url:'http://grails.codehaus.org']
     * sql.execute "insert into PROJECT (id, name, url) values ($map.id, $map.name, $map.url)"
     * 
    * Or a row update: *
     * def newUrl = 'http://grails.org'
     * def project = 'Grails'
     * sql.executeUpdate "update PROJECT set url=$newUrl where name=$project"
     * 
    * Now try a query using eachRow: *
     * println 'Some GR8 projects:'
     * sql.eachRow('select * from PROJECT') { row ->
     *     println "${row.name.padRight(10)} ($row.url)"
     * }
     * 
    * Which will produce something like this: *
     * Some GR8 projects:
     * Groovy     (http://groovy.codehaus.org)
     * Grails     (http://grails.org)
     * Griffon    (http://griffon.codehaus.org)
     * Gradle     (http://gradle.org)
     * 
    * Now try a query using rows: *
     * def rows = sql.rows("select * from PROJECT where name like 'Gra%'")
     * assert rows.size() == 2
     * println rows.join('\n')
     * 
    * with output like this: *
     * [ID:20, NAME:Grails, URL:http://grails.org]
     * [ID:40, NAME:Gradle, URL:http://gradle.org]
     * 
    * Also, eachRow and rows support paging. Here's an example: *
     * sql.eachRow('select * from PROJECT', 2, 2) { row ->
     *     println "${row.name.padRight(10)} ($row.url)"
     * }
     * 
    * Which will start at the second row and return a maximum of 2 rows. Here's an example result: *
     * Grails     (http://grails.org)
     * Griffon    (http://griffon.codehaus.org)
     * 
    * * Finally, we should clean up: *
     * sql.close()
     * 
    * If we are using a DataSource and we haven't enabled statement caching, then * strictly speaking the final close() method isn't required - as all connection * handling is performed transparently on our behalf; however, it doesn't hurt to * have it there as it will return silently in that case. *

    * *

    Named and named ordinal parameters

    * * Several of the methods in this class which have a String-based sql query and * params in a List or Object[] support named or named ordinal parameters. * These methods are useful for queries with large numbers of parameters - though the GString * variations are often preferred in such cases too. *

    * Named parameter queries use placeholder values in the query String. Two forms are supported * ':propname1' and '?.propname2'. For these variations, a single model object is * supplied in the parameter list. The propname refers to a property of that model object. * The model object could be a map, Expando or domain class instance. Here are some examples: *

     * println sql.rows('select * from PROJECT where name=:foo', [foo:'Gradle'])
     * println sql.rows('select * from PROJECT where name=:foo and id=?.bar', [foo:'Gradle', bar:40])
     * class MyDomainClass { def baz = 'Griffon' }
     * println sql.rows('select * from PROJECT where name=?.baz', new MyDomainClass())
     * 
    * Named ordinal parameter queries have multiple model objects with the index number (starting * at 1) also supplied in the placeholder. Only the question mark variation of placeholder is supported. * Here is an example: *
     * println sql.rows("select * from PROJECT where name=?1.baz and id=?2.num", new MyDomainClass(), [num:30])
     * 
    * *

    More details

    * * See the method and constructor JavaDoc for more details. *

    * For advanced usage, the class provides numerous extension points for overriding the * facade behavior associated with the various aspects of managing * the interaction with the underlying database. * * @author Chris Stevenson * @author James Strachan * @author Paul King * @author Marc DeXeT * @author John Bito * @author John Hurst * @author David Durham * @author Daniel Henrique Alves Lima */ public class Sql { /** * Hook to allow derived classes to access the log */ protected static final Logger LOG = Logger.getLogger(Sql.class.getName()); private static final List EMPTY_LIST = Collections.emptyList(); private static final Pattern NAMED_QUERY_PATTERN = Pattern.compile("(?::|\\?(\\d?)\\.?)(\\w*)"); private DataSource dataSource; private Connection useConnection; private int resultSetType = ResultSet.TYPE_FORWARD_ONLY; private int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; private int resultSetHoldability = -1; // store last row update count for executeUpdate, executeInsert and execute private int updateCount = 0; // allows a closure to be used to configure Statement objects before its use private Closure configureStatement; private boolean cacheConnection; private boolean cacheStatements; private boolean cacheNamedQueries = true; private boolean enableNamedQueries = true; private boolean withinBatch; private final Map statementCache = new HashMap(); private final Map namedParamSqlCache = new HashMap(); private final Map> namedParamIndexPropCache = new HashMap>(); /** * Creates a new Sql instance given a JDBC connection URL. * * @param url a database url of the form * jdbc:subprotocol:subname * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs */ public static Sql newInstance(String url) throws SQLException { Connection connection = DriverManager.getConnection(url); return new Sql(connection); } /** * Creates a new Sql instance given a JDBC connection URL * and some properties. * * @param url a database url of the form * jdbc:subprotocol:subname * @param properties a list of arbitrary string tag/value pairs * as connection arguments; normally at least a "user" and * "password" property should be included * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs */ public static Sql newInstance(String url, Properties properties) throws SQLException { Connection connection = DriverManager.getConnection(url, properties); return new Sql(connection); } /** * Creates a new Sql instance given a JDBC connection URL, * some properties and a driver class name. * * @param url a database url of the form * jdbc:subprotocol:subname * @param properties a list of arbitrary string tag/value pairs * as connection arguments; normally at least a "user" and * "password" property should be included * @param driverClassName the fully qualified class name of the driver class * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs * @throws ClassNotFoundException if the class cannot be found or loaded */ public static Sql newInstance(String url, Properties properties, String driverClassName) throws SQLException, ClassNotFoundException { loadDriver(driverClassName); return newInstance(url, properties); } /** * Creates a new Sql instance given a JDBC connection URL, * a username and a password. * * @param url a database url of the form * jdbc:subprotocol:subname * @param user the database user on whose behalf the connection * is being made * @param password the user's password * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs */ public static Sql newInstance(String url, String user, String password) throws SQLException { Connection connection = DriverManager.getConnection(url, user, password); return new Sql(connection); } /** * Creates a new Sql instance given a JDBC connection URL, * a username, a password and a driver class name. * * @param url a database url of the form * jdbc:subprotocol:subname * @param user the database user on whose behalf the connection * is being made * @param password the user's password * @param driverClassName the fully qualified class name of the driver class * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs * @throws ClassNotFoundException if the class cannot be found or loaded */ public static Sql newInstance(String url, String user, String password, String driverClassName) throws SQLException, ClassNotFoundException { loadDriver(driverClassName); return newInstance(url, user, password); } /** * Creates a new Sql instance given a JDBC connection URL * and a driver class name. * * @param url a database url of the form * jdbc:subprotocol:subname * @param driverClassName the fully qualified class name of the driver class * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs * @throws ClassNotFoundException if the class cannot be found or loaded */ public static Sql newInstance(String url, String driverClassName) throws SQLException, ClassNotFoundException { loadDriver(driverClassName); return newInstance(url); } /** * Creates a new Sql instance given parameters in a Map. * Recognized keys for the Map include: *
         * driverClassName the fully qualified class name of the driver class
         * driver          a synonym for driverClassName
         * url             a database url of the form: jdbc:subprotocol:subname
         * user            the database user on whose behalf the connection is being made
         * password        the user's password
         * properties      a list of arbitrary string tag/value pairs as connection arguments;
         *                 normally at least a "user" and "password" property should be included
         * other           any of the public setter methods of this class may be used with property notation
         *                 e.g. cacheStatements: true, resultSetConcurrency: ResultSet.CONCUR_READ_ONLY
         * 
    * Of these, 'url' is required. Others may be needed depending on your database.
    * If 'properties' is supplied, neither 'user' nor 'password' should be supplied.
    * If one of 'user' or 'password' is supplied, both should be supplied. *

    * Example usage: *

         * import groovy.sql.Sql
         * import static java.sql.ResultSet.*
         *
         * def sql = Sql.newInstance(
         *     url:'jdbc:hsqldb:mem:testDB',
         *     user:'sa',
         *     password:'',
         *     driver:'org.hsqldb.jdbcDriver',
         *     cacheStatements: true,
         *     resultSetConcurrency: CONCUR_READ_ONLY
         * )
         * 
    * * @param args a Map contain further arguments * @return a new Sql instance with a connection * @throws SQLException if a database access error occurs * @throws ClassNotFoundException if the class cannot be found or loaded */ public static Sql newInstance(Map args) throws SQLException, ClassNotFoundException { if (!args.containsKey("url")) throw new IllegalArgumentException("Argument 'url' is required"); if (args.get("url") == null) throw new IllegalArgumentException("Argument 'url' must not be null"); if (args.containsKey("driverClassName") && args.containsKey("driver")) throw new IllegalArgumentException("Only one of 'driverClassName' and 'driver' should be provided"); // Make a copy so destructive operations will not affect the caller Map sqlArgs = new HashMap(args); Object driverClassName = sqlArgs.remove("driverClassName"); if (driverClassName == null) driverClassName = sqlArgs.remove("driver"); if (driverClassName != null) loadDriver(driverClassName.toString()); Properties props = (Properties) sqlArgs.remove("properties"); if (props != null && sqlArgs.containsKey("user")) throw new IllegalArgumentException("Only one of 'properties' and 'user' should be supplied"); if (props != null && sqlArgs.containsKey("password")) throw new IllegalArgumentException("Only one of 'properties' and 'password' should be supplied"); if (sqlArgs.containsKey("user") ^ sqlArgs.containsKey("password")) throw new IllegalArgumentException("Found one but not both of 'user' and 'password'"); Object url = sqlArgs.remove("url"); Connection connection; if (props != null) connection = DriverManager.getConnection(url.toString(), new Properties(props)); else if (sqlArgs.containsKey("user")) { Object user = sqlArgs.remove("user"); Object password = sqlArgs.remove("password"); connection = DriverManager.getConnection(url.toString(), (user == null ? null : user.toString()), (password == null ? null : password.toString())); } else connection = DriverManager.getConnection(url.toString()); Sql result = (Sql) InvokerHelper.invokeConstructorOf(Sql.class, sqlArgs); result.setConnection(connection); return result; } /** * Gets the resultSetType for statements created using the connection. * * @return the current resultSetType value * @since 1.5.2 */ public int getResultSetType() { return resultSetType; } /** * Sets the resultSetType for statements created using the connection. * May cause SQLFeatureNotSupportedException exceptions to occur if the * underlying database doesn't support the requested type value. * * @param resultSetType one of the following ResultSet * constants: * ResultSet.TYPE_FORWARD_ONLY, * ResultSet.TYPE_SCROLL_INSENSITIVE, or * ResultSet.TYPE_SCROLL_SENSITIVE * @since 1.5.2 */ public void setResultSetType(int resultSetType) { this.resultSetType = resultSetType; } /** * Gets the resultSetConcurrency for statements created using the connection. * * @return the current resultSetConcurrency value * @since 1.5.2 */ public int getResultSetConcurrency() { return resultSetConcurrency; } /** * Sets the resultSetConcurrency for statements created using the connection. * May cause SQLFeatureNotSupportedException exceptions to occur if the * underlying database doesn't support the requested concurrency value. * * @param resultSetConcurrency one of the following ResultSet * constants: * ResultSet.CONCUR_READ_ONLY or * ResultSet.CONCUR_UPDATABLE * @since 1.5.2 */ public void setResultSetConcurrency(int resultSetConcurrency) { this.resultSetConcurrency = resultSetConcurrency; } /** * Gets the resultSetHoldability for statements created using the connection. * * @return the current resultSetHoldability value or -1 if not set * @since 1.5.2 */ public int getResultSetHoldability() { return resultSetHoldability; } /** * Sets the resultSetHoldability for statements created using the connection. * May cause SQLFeatureNotSupportedException exceptions to occur if the * underlying database doesn't support the requested holdability value. * * @param resultSetHoldability one of the following ResultSet * constants: * ResultSet.HOLD_CURSORS_OVER_COMMIT or * ResultSet.CLOSE_CURSORS_AT_COMMIT * @since 1.5.2 */ public void setResultSetHoldability(int resultSetHoldability) { this.resultSetHoldability = resultSetHoldability; } /** * Attempts to load the JDBC driver on the thread, current or system class * loaders * * @param driverClassName the fully qualified class name of the driver class * @throws ClassNotFoundException if the class cannot be found or loaded */ public static void loadDriver(String driverClassName) throws ClassNotFoundException { // let's try the thread context class loader first // let's try to use the system class loader try { Class.forName(driverClassName); } catch (ClassNotFoundException e) { try { Thread.currentThread().getContextClassLoader().loadClass(driverClassName); } catch (ClassNotFoundException e2) { // now let's try the classloader which loaded us try { Sql.class.getClassLoader().loadClass(driverClassName); } catch (ClassNotFoundException e3) { throw e; } } } } public static final OutParameter ARRAY = new OutParameter(){ public int getType() { return Types.ARRAY; }}; public static final OutParameter BIGINT = new OutParameter(){ public int getType() { return Types.BIGINT; }}; public static final OutParameter BINARY = new OutParameter(){ public int getType() { return Types.BINARY; }}; public static final OutParameter BIT = new OutParameter(){ public int getType() { return Types.BIT; }}; public static final OutParameter BLOB = new OutParameter(){ public int getType() { return Types.BLOB; }}; public static final OutParameter BOOLEAN = new OutParameter(){ public int getType() { return Types.BOOLEAN; }}; public static final OutParameter CHAR = new OutParameter(){ public int getType() { return Types.CHAR; }}; public static final OutParameter CLOB = new OutParameter(){ public int getType() { return Types.CLOB; }}; public static final OutParameter DATALINK = new OutParameter(){ public int getType() { return Types.DATALINK; }}; public static final OutParameter DATE = new OutParameter(){ public int getType() { return Types.DATE; }}; public static final OutParameter DECIMAL = new OutParameter(){ public int getType() { return Types.DECIMAL; }}; public static final OutParameter DISTINCT = new OutParameter(){ public int getType() { return Types.DISTINCT; }}; public static final OutParameter DOUBLE = new OutParameter(){ public int getType() { return Types.DOUBLE; }}; public static final OutParameter FLOAT = new OutParameter(){ public int getType() { return Types.FLOAT; }}; public static final OutParameter INTEGER = new OutParameter(){ public int getType() { return Types.INTEGER; }}; public static final OutParameter JAVA_OBJECT = new OutParameter(){ public int getType() { return Types.JAVA_OBJECT; }}; public static final OutParameter LONGVARBINARY = new OutParameter(){ public int getType() { return Types.LONGVARBINARY; }}; public static final OutParameter LONGVARCHAR = new OutParameter(){ public int getType() { return Types.LONGVARCHAR; }}; public static final OutParameter NULL = new OutParameter(){ public int getType() { return Types.NULL; }}; public static final OutParameter NUMERIC = new OutParameter(){ public int getType() { return Types.NUMERIC; }}; public static final OutParameter OTHER = new OutParameter(){ public int getType() { return Types.OTHER; }}; public static final OutParameter REAL = new OutParameter(){ public int getType() { return Types.REAL; }}; public static final OutParameter REF = new OutParameter(){ public int getType() { return Types.REF; }}; public static final OutParameter SMALLINT = new OutParameter(){ public int getType() { return Types.SMALLINT; }}; public static final OutParameter STRUCT = new OutParameter(){ public int getType() { return Types.STRUCT; }}; public static final OutParameter TIME = new OutParameter(){ public int getType() { return Types.TIME; }}; public static final OutParameter TIMESTAMP = new OutParameter(){ public int getType() { return Types.TIMESTAMP; }}; public static final OutParameter TINYINT = new OutParameter(){ public int getType() { return Types.TINYINT; }}; public static final OutParameter VARBINARY = new OutParameter(){ public int getType() { return Types.VARBINARY; }}; public static final OutParameter VARCHAR = new OutParameter(){ public int getType() { return Types.VARCHAR; }}; public static InParameter ARRAY(Object value) { return in(Types.ARRAY, value); } public static InParameter BIGINT(Object value) { return in(Types.BIGINT, value); } public static InParameter BINARY(Object value) { return in(Types.BINARY, value); } public static InParameter BIT(Object value) { return in(Types.BIT, value); } public static InParameter BLOB(Object value) { return in(Types.BLOB, value); } public static InParameter BOOLEAN(Object value) { return in(Types.BOOLEAN, value); } public static InParameter CHAR(Object value) { return in(Types.CHAR, value); } public static InParameter CLOB(Object value) { return in(Types.CLOB, value); } public static InParameter DATALINK(Object value) { return in(Types.DATALINK, value); } public static InParameter DATE(Object value) { return in(Types.DATE, value); } public static InParameter DECIMAL(Object value) { return in(Types.DECIMAL, value); } public static InParameter DISTINCT(Object value) { return in(Types.DISTINCT, value); } public static InParameter DOUBLE(Object value) { return in(Types.DOUBLE, value); } public static InParameter FLOAT(Object value) { return in(Types.FLOAT, value); } public static InParameter INTEGER(Object value) { return in(Types.INTEGER, value); } public static InParameter JAVA_OBJECT(Object value) { return in(Types.JAVA_OBJECT, value); } public static InParameter LONGVARBINARY(Object value) { return in(Types.LONGVARBINARY, value); } public static InParameter LONGVARCHAR(Object value) { return in(Types.LONGVARCHAR, value); } public static InParameter NULL(Object value) { return in(Types.NULL, value); } public static InParameter NUMERIC(Object value) { return in(Types.NUMERIC, value); } public static InParameter OTHER(Object value) { return in(Types.OTHER, value); } public static InParameter REAL(Object value) { return in(Types.REAL, value); } public static InParameter REF(Object value) { return in(Types.REF, value); } public static InParameter SMALLINT(Object value) { return in(Types.SMALLINT, value); } public static InParameter STRUCT(Object value) { return in(Types.STRUCT, value); } public static InParameter TIME(Object value) { return in(Types.TIME, value); } public static InParameter TIMESTAMP(Object value) { return in(Types.TIMESTAMP, value); } public static InParameter TINYINT(Object value) { return in(Types.TINYINT, value); } public static InParameter VARBINARY(Object value) { return in(Types.VARBINARY, value); } public static InParameter VARCHAR(Object value) { return in(Types.VARCHAR, value); } /** * Create a new InParameter * * @param type the JDBC data type * @param value the object value * @return an InParameter */ public static InParameter in(final int type, final Object value) { return new InParameter() { public int getType() { return type; } public Object getValue() { return value; } }; } /** * Create a new OutParameter * * @param type the JDBC data type. * @return an OutParameter */ public static OutParameter out(final int type) { return new OutParameter() { public int getType() { return type; } }; } /** * Create an inout parameter using this in parameter. * * @param in the InParameter of interest * @return the resulting InOutParameter */ public static InOutParameter inout(final InParameter in) { return new InOutParameter() { public int getType() { return in.getType(); } public Object getValue() { return in.getValue(); } }; } /** * Create a new ResultSetOutParameter * * @param type the JDBC data type. * @return a ResultSetOutParameter */ public static ResultSetOutParameter resultSet(final int type) { return new ResultSetOutParameter() { public int getType() { return type; } }; } /** * When using GString SQL queries, allows a variable to be expanded * in the Sql string rather than representing an sql parameter. *

    * Example usage: *

         * def fieldName = 'firstname'
         * def fieldOp = Sql.expand('like')
         * def fieldVal = '%a%'
         * sql.query "select * from PERSON where ${Sql.expand(fieldName)} $fieldOp ${fieldVal}", { ResultSet rs ->
         *     while (rs.next()) println rs.getString('firstname')
         * }
         * // query will be 'select * from PERSON where firstname like ?'
         * // params will be [fieldVal]
         * 
    * * @param object the object of interest * @return the expanded variable * @see #expand(Object) */ public static ExpandedVariable expand(final Object object) { return new ExpandedVariable() { public Object getObject() { return object; } }; } /** * Constructs an SQL instance using the given DataSource. Each operation * will use a Connection from the DataSource pool and close it when the * operation is completed putting it back into the pool. * * @param dataSource the DataSource to use */ public Sql(DataSource dataSource) { this.dataSource = dataSource; } /** * Constructs an SQL instance using the given Connection. It is the caller's * responsibility to close the Connection after the Sql instance has been * used. Depending on which features you are using, you may be able to do * this on the connection object directly but the preferred approach is to * call the {@link #close()} method which will close the connection but also * free any caches resources. * * @param connection the Connection to use */ public Sql(Connection connection) { if (connection == null) { throw new NullPointerException("Must specify a non-null Connection"); } this.useConnection = connection; } public Sql(Sql parent) { this.dataSource = parent.dataSource; this.useConnection = parent.useConnection; } private Sql() { // supports Map style newInstance method } public DataSet dataSet(String table) { return new DataSet(this, table); } public DataSet dataSet(Class type) { return new DataSet(this, type); } /** * Performs the given SQL query, which should return a single * ResultSet object. The given closure is called * with the ResultSet as its argument. *

    * Example usages: *

         * sql.query("select * from PERSON where firstname like 'S%'") { ResultSet rs ->
         *     while (rs.next()) println rs.getString('firstname') + ' ' + rs.getString(3)
         * }
         *
         * sql.query("call get_people_places()") { ResultSet rs ->
         *     while (rs.next()) println rs.toRowResult().firstname
         * }
         * 
    * * All resources including the ResultSet are closed automatically * after the closure is called. * * @param sql the sql statement * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void query(String sql, Closure closure) throws SQLException { Connection connection = createConnection(); Statement statement = getStatement(connection, sql); ResultSet results = null; try { results = statement.executeQuery(sql); closure.call(results); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement, results); } } /** * Performs the given SQL query, which should return a single * ResultSet object. The given closure is called * with the ResultSet as its argument. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usage: *

         * sql.query('select * from PERSON where lastname like ?', ['%a%']) { ResultSet rs ->
         *     while (rs.next()) println rs.getString('lastname')
         * }
         * 
    * * This method supports named and named ordinal parameters. * See the class Javadoc for more details. *

    * All resources including the ResultSet are closed automatically * after the closure is called. * * @param sql the sql statement * @param params a list of parameters * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void query(String sql, List params, Closure closure) throws SQLException { Connection connection = createConnection(); PreparedStatement statement = null; ResultSet results = null; try { statement = getPreparedStatement(connection, sql, params); results = statement.executeQuery(); closure.call(results); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement, results); } } /** * Performs the given SQL query, which should return a single * ResultSet object. The given closure is called * with the ResultSet as its argument. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * sql.query "select * from PERSON where location_id < $location", { ResultSet rs ->
         *     while (rs.next()) println rs.getString('firstname')
         * }
         * 
    * * All resources including the ResultSet are closed automatically * after the closure is called. * * @param gstring a GString containing the SQL query with embedded params * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs * @see #expand(Object) */ public void query(GString gstring, Closure closure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); query(sql, params, closure); } /** * Performs the given SQL query calling the given Closure with each row of the result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. *

    * Example usages: *

         * sql.eachRow("select * from PERSON where firstname like 'S%'") { row ->
         *    println "$row.firstname ${row[2]}}"
         * }
         *
         * sql.eachRow "call my_stored_proc_returning_resultset()", {
         *     println it.firstname
         * }
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, Closure closure) throws SQLException { eachRow(sql, (Closure) null, closure); } /** * Performs the given SQL query calling the given closure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. * *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * *

    * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, int offset, int maxRows, Closure closure) throws SQLException { eachRow(sql, (Closure) null, offset, maxRows, closure); } /** * Performs the given SQL query calling the given rowClosure with each row of the * result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. *

    * Example usage: *

         * def printColNames = { meta ->
         *     (1..meta.columnCount).each {
         *         print meta.getColumnLabel(it).padRight(20)
         *     }
         *     println()
         * }
         * def printRow = { row ->
         *     row.toRowResult().values().each{ print it.toString().padRight(20) }
         *     println()
         * }
         * sql.eachRow("select * from PERSON", printColNames, printRow)
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param metaClosure called for meta data (only once after sql execution) * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, Closure metaClosure, Closure rowClosure) throws SQLException { eachRow(sql, metaClosure, 0, 0, rowClosure); } /** * Performs the given SQL query calling the given rowClosure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. *

    * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. * *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * *

    * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param metaClosure called for meta data (only once after sql execution) * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException { Connection connection = createConnection(); Statement statement = getStatement(connection, sql); ResultSet results = null; try { results = statement.executeQuery(sql); if (metaClosure != null) metaClosure.call(results.getMetaData()); boolean cursorAtRow = moveCursor(results, offset); if (!cursorAtRow) return; GroovyResultSet groovyRS = new GroovyResultSetProxy(results).getImpl(); int i = 0; while (groovyRS.next() && (maxRows <= 0 || i++ < maxRows)) { rowClosure.call(groovyRS); } } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement, results); } } private boolean moveCursor(ResultSet results, int offset) throws SQLException { boolean cursorAtRow = true; if (results.getType() == ResultSet.TYPE_FORWARD_ONLY) { int i = 1; while (i++ < offset && cursorAtRow) { cursorAtRow = results.next(); } } else if (offset > 1) { cursorAtRow = results.absolute(offset - 1); } return cursorAtRow; } /** * Performs the given SQL query calling the given rowClosure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. *

    * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain placeholder question marks which match the given list of parameters. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * * @param sql the sql statement * @param params a list of parameters * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param metaClosure called for meta data (only once after sql execution) * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, List params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException { Connection connection = createConnection(); PreparedStatement statement = null; ResultSet results = null; try { statement = getPreparedStatement(connection, sql, params); results = statement.executeQuery(); if (metaClosure != null) metaClosure.call(results.getMetaData()); boolean cursorAtRow = moveCursor(results, offset); if (!cursorAtRow) return; GroovyResultSet groovyRS = new GroovyResultSetProxy(results).getImpl(); int i = 0; while (groovyRS.next() && (maxRows <= 0 || i++ < maxRows)) { rowClosure.call(groovyRS); } } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement, results); } } /** * Performs the given SQL query calling the given Closure with each row of the result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usage: *

         * def printColNames = { meta ->
         *     (1..meta.columnCount).each {
         *         print meta.getColumnLabel(it).padRight(20)
         *     }
         *     println()
         * }
         * def printRow = { row ->
         *     row.toRowResult().values().each{ print it.toString().padRight(20) }
         *     println()
         * }
         * sql.eachRow("select * from PERSON where lastname like ?", ['%a%'], printColNames, printRow)
         * 
    * * This method supports named and named ordinal parameters. * See the class Javadoc for more details. *

    * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param params a list of parameters * @param metaClosure called for meta data (only once after sql execution) * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, List params, Closure metaClosure, Closure rowClosure) throws SQLException { eachRow(sql, params, metaClosure, 0, 0, rowClosure); } /** * Performs the given SQL query calling the given Closure with each row of the result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usage: *

         * sql.eachRow("select * from PERSON where lastname like ?", ['%a%']) { row ->
         *     println "${row[1]} $row.lastname"
         * }
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param params a list of parameters * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, List params, Closure closure) throws SQLException { eachRow(sql, params, null, closure); } /** * Performs the given SQL query calling the given closure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * The query may contain placeholder question marks which match the given list of parameters. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * * @param sql the sql statement * @param params a list of parameters * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(String sql, List params, int offset, int maxRows, Closure closure) throws SQLException { eachRow(sql, params, null, offset, maxRows, closure); } /** * Performs the given SQL query calling the given Closure with each row of the result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. *

    * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * def printColNames = { meta ->
         *     (1..meta.columnCount).each {
         *         print meta.getColumnLabel(it).padRight(20)
         *     }
         *     println()
         * }
         * def printRow = { row ->
         *     row.toRowResult().values().each{ print it.toString().padRight(20) }
         *     println()
         * }
         * sql.eachRow("select * from PERSON where location_id < $location", printColNames, printRow)
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @param metaClosure called for meta data (only once after sql execution) * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs * @see #expand(Object) */ public void eachRow(GString gstring, Closure metaClosure, Closure rowClosure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); eachRow(sql, params, metaClosure, rowClosure); } /** * Performs the given SQL query calling the given closure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain GString expressions. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * * @param gstring a GString containing the SQL query with embedded params * @param metaClosure called for meta data (only once after sql execution) * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param rowClosure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(GString gstring, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); eachRow(sql, params, metaClosure, offset, maxRows, rowClosure); } /** * Performs the given SQL query calling the given closure with each row of the result set starting at * the provided offset, and including up to maxRows number of rows. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * The query may contain GString expressions. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. * * @param gstring a GString containing the SQL query with embedded params * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void eachRow(GString gstring, int offset, int maxRows, Closure closure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); eachRow(sql, params, offset, maxRows, closure); } /** * Performs the given SQL query calling the given Closure with each row of the result set. * The row will be a GroovyResultSet which is a ResultSet * that supports accessing the fields using property style notation and ordinal index values. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * sql.eachRow("select * from PERSON where location_id < $location") { row ->
         *     println row.firstname
         * }
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs * @see #expand(Object) */ public void eachRow(GString gstring, Closure closure) throws SQLException { eachRow(gstring, null, closure); } /** * Performs the given SQL query and return the rows of the result set. *

    * Example usage: *

         * def ans = sql.rows("select * from PERSON where firstname like 'S%'")
         * println "Found ${ans.size()} rows"
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql) throws SQLException { return rows(sql, 0, 0, null); } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, int offset, int maxRows) throws SQLException { return rows(sql, offset, maxRows, null); } /** * Performs the given SQL query and return the rows of the result set. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. *

    * Example usage: *

         * def printNumCols = { meta -> println "Found $meta.columnCount columns" }
         * def ans = sql.rows("select * from PERSON", printNumCols)
         * println "Found ${ans.size()} rows"
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param metaClosure called with meta data of the ResultSet * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, Closure metaClosure) throws SQLException { return rows(sql, 0, 0, metaClosure); } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param metaClosure called for meta data (only once after sql execution) * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, int offset, int maxRows, Closure metaClosure) throws SQLException { AbstractQueryCommand command = createQueryCommand(sql); ResultSet rs = null; try { rs = command.execute(); List result = asList(sql, rs, offset, maxRows, metaClosure); rs = null; return result; } finally { command.closeResources(rs); } } /** * Performs the given SQL query and return the rows of the result set. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usage: *

         * def ans = sql.rows("select * from PERSON where lastname like ?", ['%a%'])
         * println "Found ${ans.size()} rows"
         * 
    *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, List params) throws SQLException { return rows(sql, params, null); } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. * The query may contain placeholder question marks which match the given list of parameters. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params an array of parameters * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, List params, int offset, int maxRows) throws SQLException { return rows(sql, params, offset, maxRows, null); } /** * Performs the given SQL query and return the rows of the result set. * * An Object array variant of {@link #rows(String, List)}. * * @param sql the SQL statement * @param params an array of parameters * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, Object[] params) throws SQLException { return rows(sql, params, 0, 0); } /** * Performs the given SQL query and return the rows of the result set. * * An Object array variant of {@link #rows(String, List, int, int)}. * * @param sql the SQL statement * @param params an array of parameters * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, Object[] params, int offset, int maxRows) throws SQLException { return rows(sql, Arrays.asList(params), offset, maxRows, null); } /** * Performs the given SQL query and return the rows of the result set. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usage: *

         * def printNumCols = { meta -> println "Found $meta.columnCount columns" }
         * def ans = sql.rows("select * from PERSON where lastname like ?", ['%a%'], printNumCols)
         * println "Found ${ans.size()} rows"
         * 
    * * This method supports named and named ordinal parameters by supplying such * parameters in the params list. Here is an example: *
         * def printNumCols = { meta -> println "Found $meta.columnCount columns" }
         *
         * def mapParam = [foo: 'Smith']
         * def domainParam = new MyDomainClass(bar: 'John')
         * def qry = 'select * from PERSON where lastname=?1.foo and firstname=?2.bar'
         * def ans = sql.rows(qry, [mapParam, domainParam], printNumCols)
         * println "Found ${ans.size()} rows"
         *
         * def qry2 = 'select * from PERSON where firstname=:first and lastname=:last'
         * def ans2 = sql.rows(qry2, [[last:'Smith', first:'John']], printNumCols)
         * println "Found ${ans2.size()} rows"
         * 
    * See the class Javadoc for more details. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @param metaClosure called for meta data (only once after sql execution) * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, List params, Closure metaClosure) throws SQLException { return rows(sql, params, 0, 0, metaClosure); } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain placeholder question marks which match the given list of parameters. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param metaClosure called for meta data (only once after sql execution) * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(String sql, List params, int offset, int maxRows, Closure metaClosure) throws SQLException { AbstractQueryCommand command = createPreparedQueryCommand(sql, params); try { return asList(sql, command.execute(), offset, maxRows, metaClosure); } finally { command.closeResources(); } } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. * The query may contain GString expressions. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(GString sql, int offset, int maxRows) throws SQLException { return rows(sql, offset, maxRows, null); } /** * Performs the given SQL query and return the rows of the result set. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * def ans = sql.rows("select * from PERSON where location_id < $location")
         * println "Found ${ans.size()} rows"
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs * @see #expand(Object) */ public List rows(GString gstring) throws SQLException { return rows(gstring, null); } /** * Performs the given SQL query and return the rows of the result set. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * def printNumCols = { meta -> println "Found $meta.columnCount columns" }
         * def ans = sql.rows("select * from PERSON where location_id < $location", printNumCols)
         * println "Found ${ans.size()} rows"
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @param metaClosure called with meta data of the ResultSet * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs * @see #expand(Object) */ public List rows(GString gstring, Closure metaClosure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return rows(sql, params, metaClosure); } /** * Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at * a 1-based offset, and containing a maximum number of rows. * In addition, the metaClosure will be called once passing in the * ResultSetMetaData as argument. * The query may contain GString expressions. *

    * Note that the underlying implementation is based on either invoking ResultSet.absolute(), * or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method * is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect * on the initial positioning within the result set. *

    * Note that different database and JDBC driver implementations may work differently with respect to this method. * Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a * "scrollable" type. *

    * Resource handling is performed automatically where appropriate. * * @param gstring the SQL statement * @param offset the 1-based offset for the first row to be processed * @param maxRows the maximum number of rows to be processed * @param metaClosure called for meta data (only once after sql execution) * @return a list of GroovyRowResult objects * @throws SQLException if a database access error occurs */ public List rows(GString gstring, int offset, int maxRows, Closure metaClosure) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return rows(sql, params, offset, maxRows, metaClosure); } /** * Performs the given SQL query and return the first row of the result set. *

    * Example usage: *

         * def ans = sql.firstRow("select * from PERSON where firstname like 'S%'")
         * println ans.firstname
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @return a GroovyRowResult object or null if no row is found * @throws SQLException if a database access error occurs */ public GroovyRowResult firstRow(String sql) throws SQLException { List rows = rows(sql); if (rows.isEmpty()) return null; return (rows.get(0)); } /** * Performs the given SQL query and return * the first row of the result set. * The query may contain GString expressions. *

    * Example usage: *

         * def location = 25
         * def ans = sql.firstRow("select * from PERSON where location_id < $location")
         * println ans.firstname
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return a GroovyRowResult object or null if no row is found * @throws SQLException if a database access error occurs * @see #expand(Object) */ public GroovyRowResult firstRow(GString gstring) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return firstRow(sql, params); } /** * Performs the given SQL query and return the first row of the result set. * The query may contain placeholder question marks which match the given list of parameters. *

    * Example usages: *

         * def ans = sql.firstRow("select * from PERSON where lastname like ?", ['%a%'])
         * println ans.firstname
         * 
    * If your database returns scalar functions as ResultSets, you can also use firstRow * to gain access to stored procedure results, e.g. using hsqldb 1.9 RC4: *
         * sql.execute """
         *     create function FullName(p_firstname VARCHAR(40)) returns VARCHAR(80)
         *     BEGIN atomic
         *     DECLARE ans VARCHAR(80);
         *     SET ans = (SELECT firstname || ' ' || lastname FROM PERSON WHERE firstname = p_firstname);
         *     RETURN ans;
         *     END
         * """
         *
         * assert sql.firstRow("{call FullName(?)}", ['Sam'])[0] == 'Sam Pullara'
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @return a GroovyRowResult object or null if no row is found * @throws SQLException if a database access error occurs */ public GroovyRowResult firstRow(String sql, List params) throws SQLException { List rows = rows(sql, params); if (rows.isEmpty()) return null; return rows.get(0); } /** * Performs the given SQL query and return the first row of the result set. * * An Object array variant of {@link #firstRow(String, List)}. * * @param sql the SQL statement * @param params an array of parameters * @return a GroovyRowResult object or null if no row is found * @throws SQLException if a database access error occurs */ public GroovyRowResult firstRow(String sql, Object[] params) throws SQLException { return firstRow(sql, Arrays.asList(params)); } /** * Executes the given piece of SQL. * Also saves the updateCount, if any, for subsequent examination. *

    * Example usages: *

         * sql.execute "drop table if exists PERSON"
         *
         * sql.execute """
         *     create table PERSON (
         *         id integer not null,
         *         firstname varchar(100),
         *         lastname varchar(100),
         *         location_id integer
         *     )
         * """
         *
         * sql.execute """
         *     insert into PERSON (id, firstname, lastname, location_id) values (4, 'Paul', 'King', 40)
         * """
         * assert sql.updateCount == 1
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL to execute * @return true if the first result is a ResultSet * object; false if it is an update count or there are * no results * @throws SQLException if a database access error occurs */ public boolean execute(String sql) throws SQLException { Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); // TODO handle multiple results boolean isResultSet = statement.execute(sql); this.updateCount = statement.getUpdateCount(); return isResultSet; } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given piece of SQL with parameters. * Also saves the updateCount, if any, for subsequent examination. *

    * Example usage: *

         * sql.execute """
         *     insert into PERSON (id, firstname, lastname, location_id) values (?, ?, ?, ?)
         * """, [1, "Guillaume", "Laforge", 10]
         * assert sql.updateCount == 1
         * 
    * * This method supports named and named ordinal parameters. * See the class Javadoc for more details. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @return true if the first result is a ResultSet * object; false if it is an update count or there are * no results * @throws SQLException if a database access error occurs */ public boolean execute(String sql, List params) throws SQLException { Connection connection = createConnection(); PreparedStatement statement = null; try { statement = getPreparedStatement(connection, sql, params); // TODO handle multiple results boolean isResultSet = statement.execute(); this.updateCount = statement.getUpdateCount(); return isResultSet; } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given piece of SQL with parameters. * * An Object array variant of {@link #execute(String, List)}. * * @param sql the SQL statement * @param params an array of parameters * @return true if the first result is a ResultSet * object; false if it is an update count or there are * no results * @throws SQLException if a database access error occurs */ public boolean execute(String sql, Object[] params) throws SQLException { return execute(sql, Arrays.asList(params)); } /** * Executes the given SQL with embedded expressions inside. * Also saves the updateCount, if any, for subsequent examination. *

    * Example usage: *

         * def scott = [firstname: "Scott", lastname: "Davis", id: 5, location_id: 50]
         * sql.execute """
         *     insert into PERSON (id, firstname, lastname, location_id) values ($scott.id, $scott.firstname, $scott.lastname, $scott.location_id)
         * """
         * assert sql.updateCount == 1
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return true if the first result is a ResultSet * object; false if it is an update count or there are * no results * @throws SQLException if a database access error occurs * @see #expand(Object) */ public boolean execute(GString gstring) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return execute(sql, params); } /** * Executes the given SQL statement (typically an INSERT statement). * Use this variant when you want to receive the values of any * auto-generated columns, such as an autoincrement ID field. * See {@link #executeInsert(GString)} for more details. * * Resource handling is performed automatically where appropriate. * * @param sql The SQL statement to execute * @return A list of the auto-generated column values for each * inserted row (typically auto-generated keys) * @throws SQLException if a database access error occurs */ public List> executeInsert(String sql) throws SQLException { Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); this.updateCount = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet keys = statement.getGeneratedKeys(); return calculateKeys(keys); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given SQL statement (typically an INSERT statement). * Use this variant when you want to receive the values of any * auto-generated columns, such as an autoincrement ID field. * The query may contain placeholder question marks which match the given list of parameters. * See {@link #executeInsert(GString)} for more details. * * This method supports named and named ordinal parameters. * See the class Javadoc for more details. *

    * Resource handling is performed automatically where appropriate. * * @param sql The SQL statement to execute * @param params The parameter values that will be substituted * into the SQL statement's parameter slots * @return A list of the auto-generated column values for each * inserted row (typically auto-generated keys) * @throws SQLException if a database access error occurs */ public List> executeInsert(String sql, List params) throws SQLException { Connection connection = createConnection(); PreparedStatement statement = null; try { statement = getPreparedStatement(connection, sql, params, Statement.RETURN_GENERATED_KEYS); this.updateCount = statement.executeUpdate(); ResultSet keys = statement.getGeneratedKeys(); return calculateKeys(keys); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given SQL statement (typically an INSERT statement). * * An Object array variant of {@link #executeInsert(String, List)}. * * @param sql The SQL statement to execute * @param params The parameter values that will be substituted * into the SQL statement's parameter slots * @return A list of the auto-generated column values for each * inserted row (typically auto-generated keys) * @throws SQLException if a database access error occurs */ public List> executeInsert(String sql, Object[] params) throws SQLException { return executeInsert(sql, Arrays.asList(params)); } /** *

    Executes the given SQL statement (typically an INSERT statement). * Use this variant when you want to receive the values of any * auto-generated columns, such as an autoincrement ID field. * The query may contain GString expressions.

    * *

    Generated key values can be accessed using * array notation. For example, to return the second auto-generated * column value of the third row, use keys[3][1]. The * method is designed to be used with SQL INSERT statements, but is * not limited to them.

    * *

    The standard use for this method is when a table has an * autoincrement ID column and you want to know what the ID is for * a newly inserted row. In this example, we insert a single row * into a table in which the first column contains the autoincrement * ID:

    *
         *     def sql = Sql.newInstance("jdbc:mysql://localhost:3306/groovy",
         *                               "user",
         *                               "password",
         *                               "com.mysql.jdbc.Driver")
         * 

    * def keys = sql.executeInsert("insert into test_table (INT_DATA, STRING_DATA) " * + "VALUES (1, 'Key Largo')") *

    * def id = keys[0][0] *

    * // 'id' now contains the value of the new row's ID column. * // It can be used to update an object representation's * // id attribute for example. * ... *

    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return A list of the auto-generated column values for each * inserted row (typically auto-generated keys) * @throws SQLException if a database access error occurs * @see #expand(Object) */ public List> executeInsert(GString gstring) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return executeInsert(sql, params); } /** * Executes the given SQL update. * * Resource handling is performed automatically where appropriate. * * @param sql the SQL to execute * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs */ public int executeUpdate(String sql) throws SQLException { Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); this.updateCount = statement.executeUpdate(sql); return this.updateCount; } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given SQL update with parameters. * * This method supports named and named ordinal parameters. * See the class Javadoc for more details. *

    * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs */ public int executeUpdate(String sql, List params) throws SQLException { Connection connection = createConnection(); PreparedStatement statement = null; try { statement = getPreparedStatement(connection, sql, params); this.updateCount = statement.executeUpdate(); return this.updateCount; } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Executes the given SQL update with parameters. * * An Object array variant of {@link #executeUpdate(String, List)}. * * @param sql the SQL statement * @param params an array of parameters * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs */ public int executeUpdate(String sql, Object[] params) throws SQLException { return executeUpdate(sql, Arrays.asList(params)); } /** * Executes the given SQL update with embedded expressions inside. * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs * @see #expand(Object) */ public int executeUpdate(GString gstring) throws SQLException { List params = getParameters(gstring); String sql = asSql(gstring, params); return executeUpdate(sql, params); } /** * Performs a stored procedure call. *

    * Example usage (tested with MySQL) - suppose we have the following stored procedure: *

         * sql.execute """
         *     CREATE PROCEDURE HouseSwap(_first1 VARCHAR(50), _first2 VARCHAR(50))
         *     BEGIN
         *         DECLARE _loc1 INT;
         *         DECLARE _loc2 INT;
         *         SELECT location_id into _loc1 FROM PERSON where firstname = _first1;
         *         SELECT location_id into _loc2 FROM PERSON where firstname = _first2;
         *         UPDATE PERSON
         *         set location_id = case firstname
         *             when _first1 then _loc2
         *             when _first2 then _loc1
         *         end
         *         where (firstname = _first1 OR firstname = _first2);
         *     END
         * """
         * 
    * then you can invoke the procedure as follows: *
         * def rowsChanged = sql.call("{call HouseSwap('Guillaume', 'Paul')}")
         * assert rowsChanged == 2
         * 
    * * @param sql the SQL statement * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs */ public int call(String sql) throws Exception { return call(sql, EMPTY_LIST); } /** * Performs a stored procedure call with the given embedded parameters. *

    * Example usage - see {@link #call(String)} for more details about * creating a HouseSwap(IN name1, IN name2) stored procedure. * Once created, it can be called like this: *

         * def p1 = 'Paul'
         * def p2 = 'Guillaume'
         * def rowsChanged = sql.call("{call HouseSwap($p1, $p2)}")
         * assert rowsChanged == 2
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs * @see #expand(Object) * @see #call(String) */ public int call(GString gstring) throws Exception { List params = getParameters(gstring); String sql = asSql(gstring, params); return call(sql, params); } /** * Performs a stored procedure call with the given parameters. *

    * Example usage - see {@link #call(String)} for more details about * creating a HouseSwap(IN name1, IN name2) stored procedure. * Once created, it can be called like this: *

         * def rowsChanged = sql.call("{call HouseSwap(?, ?)}", ['Guillaume', 'Paul'])
         * assert rowsChanged == 2
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the SQL statement * @param params a list of parameters * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs * @see #call(String) */ public int call(String sql, List params) throws Exception { Connection connection = createConnection(); CallableStatement statement = connection.prepareCall(sql); try { LOG.fine(sql + " | " + params); setParameters(params, statement); configure(statement); return statement.executeUpdate(); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } } /** * Performs a stored procedure call with the given parameters. *

    * An Object array variant of {@link #call(String, List)}. * * @param sql the SQL statement * @param params an array of parameters * @return the number of rows updated or 0 for SQL statements that return nothing * @throws SQLException if a database access error occurs * @see #call(String) */ public int call(String sql, Object[] params) throws Exception { return call(sql, Arrays.asList(params)); } /** * Performs a stored procedure call with the given parameters. The closure * is called once with all the out parameters. *

    * Example usage - suppose we create a stored procedure (ignore its simplistic implementation): *

         * // Tested with MySql 5.0.75
         * sql.execute """
         *     CREATE PROCEDURE Hemisphere(
         *         IN p_firstname VARCHAR(50),
         *         IN p_lastname VARCHAR(50),
         *         OUT ans VARCHAR(50))
         *     BEGIN
         *     DECLARE loc INT;
         *     SELECT location_id into loc FROM PERSON where firstname = p_firstname and lastname = p_lastname;
         *     CASE loc
         *         WHEN 40 THEN
         *             SET ans = 'Southern Hemisphere';
         *         ELSE
         *             SET ans = 'Northern Hemisphere';
         *     END CASE;
         *     END;
         * """
         * 
    * we can now call the stored procedure as follows: *
         * sql.call '{call Hemisphere(?, ?, ?)}', ['Guillaume', 'Laforge', Sql.VARCHAR], { dwells ->
         *     println dwells
         * }
         * 
    * which will output 'Northern Hemisphere'. *

    * We can also access stored functions with scalar return values where the return value * will be treated as an OUT parameter. Here are examples for various databases for * creating such a procedure: *

         * // Tested with MySql 5.0.75
         * sql.execute """
         *     create function FullName(p_firstname VARCHAR(40)) returns VARCHAR(80)
         *     begin
         *         declare ans VARCHAR(80);
         *         SELECT CONCAT(firstname, ' ', lastname) INTO ans FROM PERSON WHERE firstname = p_firstname;
         *         return ans;
         *     end
         * """
         *
         * // Tested with MS SQLServer Express 2008
         * sql.execute """
         *     {@code create function FullName(@firstname VARCHAR(40)) returns VARCHAR(80)}
         *     begin
         *         declare {@code @ans} VARCHAR(80)
         *         {@code SET @ans = (SELECT firstname + ' ' + lastname FROM PERSON WHERE firstname = @firstname)}
         *         return {@code @ans}
         *     end
         * """
         *
         * // Tested with Oracle XE 10g
         * sql.execute """
         *     create function FullName(p_firstname VARCHAR) return VARCHAR is
         *     ans VARCHAR(80);
         *     begin
         *         SELECT CONCAT(CONCAT(firstname, ' '), lastname) INTO ans FROM PERSON WHERE firstname = p_firstname;
         *         return ans;
         *     end;
         * """
         * 
    * and here is how you access the stored function for all databases: *
         * sql.call("{? = call FullName(?)}", [Sql.VARCHAR, 'Sam']) { name ->
         *     assert name == 'Sam Pullara'
         * }
         * 
    * * Resource handling is performed automatically where appropriate. * * @param sql the sql statement * @param params a list of parameters * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs */ public void call(String sql, List params, Closure closure) throws Exception { Connection connection = createConnection(); CallableStatement statement = connection.prepareCall(sql); List resultSetResources = new ArrayList(); try { LOG.fine(sql + " | " + params); setParameters(params, statement); // TODO handle multiple results and mechanism for retrieving ResultSet if any (GROOVY-3048) statement.execute(); List results = new ArrayList(); int indx = 0; int inouts = 0; for (Object value : params) { if (value instanceof OutParameter) { if (value instanceof ResultSetOutParameter) { GroovyResultSet resultSet = CallResultSet.getImpl(statement, indx); resultSetResources.add(resultSet); results.add(resultSet); } else { Object o = statement.getObject(indx + 1); if (o instanceof ResultSet) { GroovyResultSet resultSet = new GroovyResultSetProxy((ResultSet) o).getImpl(); results.add(resultSet); resultSetResources.add(resultSet); } else { results.add(o); } } inouts++; } indx++; } closure.call(results.toArray(new Object[inouts])); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); for (GroovyResultSet rs : resultSetResources) { closeResources(null, null, rs); } } } /** * Performs a stored procedure call with the given parameters, * calling the closure once with all result objects. *

    * See {@link #call(String, List, Closure)} for more details about * creating a Hemisphere(IN first, IN last, OUT dwells) stored procedure. * Once created, it can be called like this: *

         * def first = 'Scott'
         * def last = 'Davis'
         * sql.call "{call Hemisphere($first, $last, ${Sql.VARCHAR})}", { dwells ->
         *     println dwells
         * }
         * 
    *

    * As another example, see {@link #call(String, List, Closure)} for more details about * creating a FullName(IN first) stored function. * Once created, it can be called like this: *

         * def first = 'Sam'
         * sql.call("{$Sql.VARCHAR = call FullName($first)}") { name ->
         *     assert name == 'Sam Pullara'
         * }
         * 
    * * Resource handling is performed automatically where appropriate. * * @param gstring a GString containing the SQL query with embedded params * @param closure called for each row with a GroovyResultSet * @throws SQLException if a database access error occurs * @see #call(String, List, Closure) * @see #expand(Object) */ public void call(GString gstring, Closure closure) throws Exception { List params = getParameters(gstring); String sql = asSql(gstring, params); call(sql, params, closure); } /** * If this SQL object was created with a Connection then this method closes * the connection. If this SQL object was created from a DataSource then * this method only frees any cached objects (statements in particular). */ public void close() { namedParamSqlCache.clear(); namedParamIndexPropCache.clear(); clearStatementCache(); if (useConnection != null) { try { useConnection.close(); } catch (SQLException e) { LOG.finest("Caught exception closing connection: " + e.getMessage()); } } } public DataSource getDataSource() { return dataSource; } /** * If this SQL object was created with a Connection then this method commits * the connection. If this SQL object was created from a DataSource then * this method does nothing. * * @throws SQLException if a database access error occurs */ public void commit() throws SQLException { if (useConnection == null) { LOG.info("Commit operation not supported when using datasets unless using withTransaction or cacheConnection - attempt to commit ignored"); return; } try { useConnection.commit(); } catch (SQLException e) { LOG.warning("Caught exception committing connection: " + e.getMessage()); throw e; } } /** * If this SQL object was created with a Connection then this method rolls back * the connection. If this SQL object was created from a DataSource then * this method does nothing. * * @throws SQLException if a database access error occurs */ public void rollback() throws SQLException { if (useConnection == null) { LOG.info("Rollback operation not supported when using datasets unless using withTransaction or cacheConnection - attempt to rollback ignored"); return; } try { useConnection.rollback(); } catch (SQLException e) { LOG.warning("Caught exception rolling back connection: " + e.getMessage()); throw e; } } /** * @return Returns the updateCount. */ public int getUpdateCount() { return updateCount; } /** * If this instance was created with a single Connection then the connection * is returned. Otherwise if this instance was created with a DataSource * then this method returns null * * @return the connection wired into this object, or null if this object * uses a DataSource */ public Connection getConnection() { return useConnection; } private void setConnection(Connection connection) { useConnection = connection; } /** * Allows a closure to be passed in to configure the JDBC statements before they are executed. * It can be used to do things like set the query size etc. When this method is invoked, the supplied * closure is saved. Statements subsequently created from other methods will then be * configured using this closure. The statement being configured is passed into the closure * as its single argument, e.g.: *
         * sql.withStatement{ stmt -> stmt.maxRows = 10 }
         * def firstTenRows = sql.rows("select * from table")
         * 
    * * @param configureStatement the closure */ public void withStatement(Closure configureStatement) { this.configureStatement = configureStatement; } /** * Enables statement caching.
    * if cacheStatements is true, cache is created and all created prepared statements will be cached.
    * if cacheStatements is false, all cached statements will be properly closed. * * @param cacheStatements the new value */ public synchronized void setCacheStatements(boolean cacheStatements) { this.cacheStatements = cacheStatements; if (!cacheStatements) { clearStatementCache(); } } /** * @return boolean true if cache is enabled (default is false) */ public boolean isCacheStatements() { return cacheStatements; } /** * Caches the connection used while the closure is active. * If the closure takes a single argument, it will be called * with the connection, otherwise it will be called with no arguments. * * @param closure the given closure * @throws SQLException if a database error occurs */ public synchronized void cacheConnection(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; try { connection = createConnection(); callClosurePossiblyWithConnection(closure, connection); } finally { cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } } /** * Performs the closure within a transaction using a cached connection. * If the closure takes a single argument, it will be called * with the connection, otherwise it will be called with no arguments. * * @param closure the given closure * @throws SQLException if a database error occurs */ public synchronized void withTransaction(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; boolean savedAutoCommit = true; try { connection = createConnection(); savedAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); callClosurePossiblyWithConnection(closure, connection); connection.commit(); } catch (SQLException e) { handleError(connection, e); throw e; } catch (RuntimeException e) { handleError(connection, e); throw e; } catch (Error e) { handleError(connection, e); throw e; } finally { if (connection != null) connection.setAutoCommit(savedAutoCommit); cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } } /** * Returns true if the current Sql object is currently executing a withBatch * method call. * * @return true if a withBatch call is currently being executed. */ public boolean isWithinBatch() { return withinBatch; } /** * Performs the closure (containing batch operations) within a batch. * Uses a batch size of zero, i.e. no automatic partitioning of batches. * * This means that executeBatch() will be called automatically after the withBatch * closure has finished but may be called explicitly if desired as well for more fine-grained * partitioning of the batch. * * The closure will be called with a single argument; the database * statement (actually a BatchingStatementWrapper helper object) * associated with this batch. * * Use it like this: *
         * def updateCounts = sql.withBatch { stmt ->
         *     stmt.addBatch("insert into TABLENAME ...")
         *     stmt.addBatch("insert into TABLENAME ...")
         *     stmt.addBatch("insert into TABLENAME ...")
         *     ...
         * }
         * 
    * For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction: *
         * sql.withTransaction {
         *     def result1 = sql.withBatch { ... }
         *     ...
         * }
         * 
    * * @param closure the closure containing batch and optionally other statements * @return an array of update counts containing one element for each * command in the batch. The elements of the array are ordered according * to the order in which commands were added to the batch. * @throws SQLException if a database access error occurs, * or this method is called on a closed Statement, or the * driver does not support batch statements. Throws {@link java.sql.BatchUpdateException} * (a subclass of SQLException) if one of the commands sent to the * database fails to execute properly or attempts to return a result set. * @see #withBatch(int, Closure) */ public int[] withBatch(Closure closure) throws SQLException { return withBatch(0, closure); } /** * Performs the closure (containing batch operations) within a batch using a given batch size. * * After every batchSize addBatch(sqlBatchOperation) * operations, automatically calls an executeBatch() operation to "chunk" up the database operations * into partitions. Though not normally needed, you can also explicitly call executeBatch() which * after executing the current batch, resets the batch count back to zero. * * The closure will be called with a single argument; the database statement * (actually a BatchingStatementWrapper helper object) * associated with this batch. * * Use it like this for batchSize of 20: *
         * def updateCounts = sql.withBatch(20) { stmt ->
         *     stmt.addBatch("insert into TABLENAME ...")
         *     stmt.addBatch("insert into TABLENAME ...")
         *     stmt.addBatch("insert into TABLENAME ...")
         *     ...
         * }
         * 
    * For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction: *
         * sql.withTransaction {
         *     def result1 = sql.withBatch { ... }
         *     ...
         * }
         * 
    * * @param batchSize partition the batch into batchSize pieces, i.e. after batchSize * addBatch() invocations, call executeBatch() automatically; * 0 means manual calls to executeBatch are required * @param closure the closure containing batch and optionally other statements * @return an array of update counts containing one element for each * command in the batch. The elements of the array are ordered according * to the order in which commands were added to the batch. * @throws SQLException if a database access error occurs, * or this method is called on a closed Statement, or the * driver does not support batch statements. Throws {@link java.sql.BatchUpdateException} * (a subclass of SQLException) if one of the commands sent to the * database fails to execute properly or attempts to return a result set. * @see #withBatch(Closure) * @see BatchingStatementWrapper * @see Statement */ public int[] withBatch(int batchSize, Closure closure) throws SQLException { Connection connection = createConnection(); BatchingStatementWrapper statement = null; boolean savedWithinBatch = withinBatch; try { withinBatch = true; statement = new BatchingStatementWrapper(createStatement(connection), batchSize, LOG); closure.call(statement); return statement.executeBatch(); } catch (SQLException e) { LOG.warning("Error during batch execution: " + e.getMessage()); throw e; } finally { closeResources(statement); closeResources(connection); withinBatch = savedWithinBatch; } } /** * Performs the closure (containing batch operations specific to an associated prepared statement) * within a batch. Uses a batch size of zero, i.e. no automatic partitioning of batches. * * This means that executeBatch() will be called automatically after the withBatch * closure has finished but may be called explicitly if desired as well for more fine-grained * partitioning of the batch. * * The closure will be called with a single argument; the prepared * statement (actually a BatchingPreparedStatementWrapper helper object) * associated with this batch. * * An example: *
         * def updateCounts = sql.withBatch('insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps ->
         *     ps.addBatch([10, 12, 5])
         *     ps.addBatch([7, 3, 98])
         *     ps.addBatch(22, 67, 11)
         *     def partialUpdateCounts = ps.executeBatch() // optional interim batching
         *     ps.addBatch(30, 40, 50)
         *     ...
         * }
         * 
    * For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction: *
         * sql.withTransaction {
         *     def result1 = sql.withBatch { ... }
         *     ...
         * }
         * 
    * * @param sql batch update statement * @param closure the closure containing batch statements (to bind parameters) and optionally other statements * @return an array of update counts containing one element for each * binding in the batch. The elements of the array are ordered according * to the order in which commands were executed. * @throws SQLException if a database access error occurs, * or this method is called on a closed Statement, or the * driver does not support batch statements. Throws {@link java.sql.BatchUpdateException} * (a subclass of SQLException) if one of the commands sent to the * database fails to execute properly or attempts to return a result set. * @see #withBatch(int, String, Closure) * @see BatchingPreparedStatementWrapper * @see PreparedStatement */ public int[] withBatch(String sql, Closure closure) throws SQLException { return withBatch(0, sql, closure); } /** * Performs the closure (containing batch operations specific to an associated prepared statement) * within a batch using a given batch size. * * After every batchSize addBatch(params) * operations, automatically calls an executeBatch() operation to "chunk" up the database operations * into partitions. Though not normally needed, you can also explicitly call executeBatch() which * after executing the current batch, resets the batch count back to zero. * * The closure will be called with a single argument; the prepared * statement (actually a BatchingPreparedStatementWrapper helper object) * associated with this batch. * * Below is an example using a batchSize of 20: *
         * def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps ->
         *     ps.addBatch(10, 12, 5)      // varargs style
         *     ps.addBatch([7, 3, 98])     // list
         *     ps.addBatch([22, 67, 11])
         *     ...
         * }
         * 
    * Named parameters (into maps or domain objects) are also supported: *
         * def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (:foo, :bar, :baz)') { ps ->
         *     ps.addBatch([foo:10, bar:12, baz:5])  // map
         *     ps.addBatch(foo:7, bar:3, baz:98)     // Groovy named args allow outer brackets to be dropped
         *     ...
         * }
         * 
    * Named ordinal parameters (into maps or domain objects) are also supported: *
         * def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (?1.foo, ?2.bar, ?2.baz)') { ps ->
         *     ps.addBatch([[foo:22], [bar:67, baz:11]])  // list of maps or domain objects
         *     ps.addBatch([foo:10], [bar:12, baz:5])     // varargs allows outer brackets to be dropped
         *     ps.addBatch([foo:7], [bar:3, baz:98])
         *     ...
         * }
         * // swap to batch size of 5 and illustrate simple and domain object cases ...
         * class Person { String first, last }
         * def updateCounts2 = sql.withBatch(5, 'insert into PERSON(id, first, last) values (?1, ?2.first, ?2.last)') { ps ->
         *     ps.addBatch(1, new Person(first:'Peter', last:'Pan'))
         *     ps.addBatch(2, new Person(first:'Snow', last:'White'))
         *     ...
         * }
         * 
    * For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction: *
         * sql.withTransaction {
         *     def result1 = sql.withBatch { ... }
         *     ...
         * }
         * 
    * * @param batchSize partition the batch into batchSize pieces, i.e. after batchSize * addBatch() invocations, call executeBatch() automatically; * 0 means manual calls to executeBatch are required if additional partitioning of the batch is required * @param sql batch update statement * @param closure the closure containing batch statements (to bind parameters) and optionally other statements * @return an array of update counts containing one element for each * binding in the batch. The elements of the array are ordered according * to the order in which commands were executed. * @throws SQLException if a database access error occurs, * or this method is called on a closed Statement, or the * driver does not support batch statements. Throws {@link java.sql.BatchUpdateException} * (a subclass of SQLException) if one of the commands sent to the * database fails to execute properly or attempts to return a result set. * @see BatchingPreparedStatementWrapper * @see PreparedStatement */ public int[] withBatch(int batchSize, String sql, Closure closure) throws SQLException { Connection connection = createConnection(); List indexPropList = null; SqlWithParams preCheck = preCheckForNamedParams(sql); boolean savedWithinBatch = withinBatch; BatchingPreparedStatementWrapper psWrapper = null; if (preCheck != null) { indexPropList = new ArrayList(); for (Object next : preCheck.getParams()) { indexPropList.add((Tuple) next); } sql = preCheck.getSql(); } try { withinBatch = true; PreparedStatement statement = (PreparedStatement) getAbstractStatement(new CreatePreparedStatementCommand(0), connection, sql); configure(statement); psWrapper = new BatchingPreparedStatementWrapper(statement, indexPropList, batchSize, LOG, this); closure.call(psWrapper); return psWrapper.executeBatch(); } catch (SQLException e) { LOG.warning("Error during batch execution of '" + sql + "' with message: " + e.getMessage()); throw e; } finally { closeResources(psWrapper); closeResources(connection); withinBatch = savedWithinBatch; } } /** * Caches every created preparedStatement in Closure closure
    * Every cached preparedStatement is closed after closure has been called. * If the closure takes a single argument, it will be called * with the connection, otherwise it will be called with no arguments. * * @param closure the given closure * @throws SQLException if a database error occurs * @see #setCacheStatements(boolean) */ public synchronized void cacheStatements(Closure closure) throws SQLException { boolean savedCacheStatements = cacheStatements; cacheStatements = true; Connection connection = null; try { connection = createConnection(); callClosurePossiblyWithConnection(closure, connection); } finally { cacheStatements = false; closeResources(connection, null); cacheStatements = savedCacheStatements; } } // protected implementation methods - extension points for subclasses //------------------------------------------------------------------------- /** * Hook to allow derived classes to access ResultSet returned from query. * * @param sql query to execute * @return the resulting ResultSet * @throws SQLException if a database error occurs */ protected final ResultSet executeQuery(String sql) throws SQLException { AbstractQueryCommand command = createQueryCommand(sql); ResultSet rs = null; try { rs = command.execute(); } finally { command.closeResources(); } return rs; } /** * Hook to allow derived classes to access ResultSet returned from query. * * @param sql query to execute * @param params parameters matching question mark placeholders in the query * @return the resulting ResultSet * @throws SQLException if a database error occurs */ protected final ResultSet executePreparedQuery(String sql, List params) throws SQLException { AbstractQueryCommand command = createPreparedQueryCommand(sql, params); ResultSet rs = null; try { rs = command.execute(); } finally { command.closeResources(); } return rs; } /** * Hook to allow derived classes to override list of result collection behavior. * The default behavior is to return a list of GroovyRowResult objects corresponding * to each row in the ResultSet. * * @param sql query to execute * @param rs the ResultSet to process * @return the resulting list of rows * @throws SQLException if a database error occurs */ protected List asList(String sql, ResultSet rs) throws SQLException { return asList(sql, rs, null); } /** * Hook to allow derived classes to override list of result collection behavior. * The default behavior is to return a list of GroovyRowResult objects corresponding * to each row in the ResultSet. * * @param sql query to execute * @param rs the ResultSet to process * @param metaClosure called for meta data (only once after sql execution) * @return the resulting list of rows * @throws SQLException if a database error occurs */ protected List asList(String sql, ResultSet rs, Closure metaClosure) throws SQLException { return asList(sql, rs, 0, 0, metaClosure); } protected List asList(String sql, ResultSet rs, int offset, int maxRows, Closure metaClosure) throws SQLException { List results = new ArrayList(); try { if (metaClosure != null) { metaClosure.call(rs.getMetaData()); } boolean cursorAtRow = moveCursor(rs, offset); if (!cursorAtRow) return null; int i = 0; while (rs.next() && (maxRows <= 0 || i++ < maxRows)) { results.add(SqlGroovyMethods.toRowResult(rs)); } return (results); } catch (SQLException e) { LOG.warning("Failed to retrieve row from ResultSet for: " + sql + " because: " + e.getMessage()); throw e; } finally { rs.close(); } } /** * Hook to allow derived classes to override sql generation from GStrings. * * @param gstring a GString containing the SQL query with embedded params * @param values the values to embed * @return the SQL version of the given query using ? instead of any parameter * @see #expand(Object) */ protected String asSql(GString gstring, List values) { String[] strings = gstring.getStrings(); if (strings.length <= 0) { throw new IllegalArgumentException("No SQL specified in GString: " + gstring); } boolean nulls = false; StringBuilder buffer = new StringBuilder(); boolean warned = false; Iterator iter = values.iterator(); for (int i = 0; i < strings.length; i++) { String text = strings[i]; if (text != null) { buffer.append(text); } if (iter.hasNext()) { Object value = iter.next(); if (value != null) { if (value instanceof ExpandedVariable) { buffer.append(((ExpandedVariable) value).getObject()); iter.remove(); } else { boolean validBinding = true; if (i < strings.length - 1) { String nextText = strings[i + 1]; if ((text.endsWith("\"") || text.endsWith("'")) && (nextText.startsWith("'") || nextText.startsWith("\""))) { if (!warned) { LOG.warning("In Groovy SQL please do not use quotes around dynamic expressions " + "(which start with $) as this means we cannot use a JDBC PreparedStatement " + "and so is a security hole. Groovy has worked around your mistake but the security hole is still there. " + "The expression so far is: " + buffer.toString() + "?" + nextText); warned = true; } buffer.append(value); iter.remove(); validBinding = false; } } if (validBinding) { buffer.append("?"); } } } else { nulls = true; iter.remove(); buffer.append("?'\"?"); // will replace these with nullish values } } } String sql = buffer.toString(); if (nulls) { sql = nullify(sql); } return sql; } /** * Hook to allow derived classes to override null handling. * Default behavior is to replace ?'"? references with NULLish * * @param sql the SQL statement * @return the modified SQL String */ protected String nullify(String sql) { /* * Some drivers (Oracle classes12.zip) have difficulty resolving data * type if setObject(null). We will modify the query to pass 'null', 'is * null', and 'is not null' */ //could be more efficient by compiling expressions in advance. int firstWhere = findWhereKeyword(sql); if (firstWhere >= 0) { Pattern[] patterns = {Pattern.compile("(?is)^(.{" + firstWhere + "}.*?)!=\\s{0,1}(\\s*)\\?'\"\\?(.*)"), Pattern.compile("(?is)^(.{" + firstWhere + "}.*?)<>\\s{0,1}(\\s*)\\?'\"\\?(.*)"), Pattern.compile("(?is)^(.{" + firstWhere + "}.*?[^<>])=\\s{0,1}(\\s*)\\?'\"\\?(.*)"),}; String[] replacements = {"$1 is not $2null$3", "$1 is not $2null$3", "$1 is $2null$3",}; for (int i = 0; i < patterns.length; i++) { Matcher matcher = patterns[i].matcher(sql); while (matcher.matches()) { sql = matcher.replaceAll(replacements[i]); matcher = patterns[i].matcher(sql); } } } return sql.replaceAll("\\?'\"\\?", "null"); } /** * Hook to allow derived classes to override where clause sniffing. * Default behavior is to find the first 'where' keyword in the sql * doing simple avoidance of the word 'where' within quotes. * * @param sql the SQL statement * @return the index of the found keyword or -1 if not found */ protected int findWhereKeyword(String sql) { char[] chars = sql.toLowerCase().toCharArray(); char[] whereChars = "where".toCharArray(); int i = 0; boolean inString = false; //TODO: Cater for comments? int inWhere = 0; while (i < chars.length) { switch (chars[i]) { case '\'': inString = !inString; break; default: if (!inString && chars[i] == whereChars[inWhere]) { inWhere++; if (inWhere == whereChars.length) { return i; } } } i++; } return -1; } /** * Hook to allow derived classes to override behavior associated with * extracting params from a GString. * * @param gstring a GString containing the SQL query with embedded params * @return extracts the parameters from the expression as a List * @see #expand(Object) */ protected List getParameters(GString gstring) { return new ArrayList(Arrays.asList(gstring.getValues())); } /** * Hook to allow derived classes to override behavior associated with * setting params for a prepared statement. Default behavior is to * append the parameters to the given statement using setObject. * * @param params the parameters to append * @param statement the statement * @throws SQLException if a database access error occurs */ protected void setParameters(List params, PreparedStatement statement) throws SQLException { int i = 1; for (Object value : params) { setObject(statement, i++, value); } } /** * Strategy method allowing derived classes to handle types differently * such as for CLOBs etc. * * @param statement the statement of interest * @param i the index of the object of interest * @param value the new object value * @throws SQLException if a database access error occurs */ protected void setObject(PreparedStatement statement, int i, Object value) throws SQLException { if (value instanceof InParameter || value instanceof OutParameter) { if (value instanceof InParameter) { InParameter in = (InParameter) value; Object val = in.getValue(); if (null == val) { statement.setNull(i, in.getType()); } else { statement.setObject(i, val, in.getType()); } } if (value instanceof OutParameter) { try { OutParameter out = (OutParameter) value; ((CallableStatement) statement).registerOutParameter(i, out.getType()); } catch (ClassCastException e) { throw new SQLException("Cannot register out parameter."); } } } else { try { statement.setObject(i, value); } catch (SQLException e) { if (value == null) { SQLException se = new SQLException("Your JDBC driver may not support null arguments for setObject. Consider using Groovy's InParameter feature." + (e.getMessage() == null ? "" : " (CAUSE: " + e.getMessage() + ")")); se.setNextException(e); throw se; } else { throw e; } } } } /** * An extension point allowing derived classes to change the behavior of * connection creation. The default behavior is to either use the * supplied connection or obtain it from the supplied datasource. * * @return the connection associated with this Sql * @throws java.sql.SQLException if a SQL error occurs */ protected Connection createConnection() throws SQLException { if ((cacheStatements || cacheConnection) && useConnection != null) { return useConnection; } if (dataSource != null) { // Use a doPrivileged here as many different properties need to be // read, and the policy shouldn't have to list them all. Connection con; try { con = AccessController.doPrivileged(new PrivilegedExceptionAction() { public Connection run() throws SQLException { return dataSource.getConnection(); } }); } catch (PrivilegedActionException pae) { Exception e = pae.getException(); if (e instanceof SQLException) { throw (SQLException) e; } else { throw (RuntimeException) e; } } if (cacheStatements || cacheConnection) { useConnection = con; } return con; } return useConnection; } /** * An extension point allowing derived classes to change the behavior * of resource closing. * * @param connection the connection to close * @param statement the statement to close * @param results the results to close */ protected void closeResources(Connection connection, Statement statement, ResultSet results) { if (results != null) { try { results.close(); } catch (SQLException e) { LOG.finest("Caught exception closing resultSet: " + e.getMessage() + " - continuing"); } } closeResources(connection, statement); } /** * An extension point allowing the behavior of resource closing to be * overridden in derived classes. * * @param connection the connection to close * @param statement the statement to close */ protected void closeResources(Connection connection, Statement statement) { if (cacheStatements) return; if (statement != null) { try { statement.close(); } catch (SQLException e) { LOG.finest("Caught exception closing statement: " + e.getMessage() + " - continuing"); } } closeResources(connection); } private void closeResources(BatchingStatementWrapper statement) { if (cacheStatements) return; if (statement != null) { try { statement.close(); } catch (SQLException e) { LOG.finest("Caught exception closing statement: " + e.getMessage() + " - continuing"); } } } /** * An extension point allowing the behavior of resource closing to be * overridden in derived classes. * * @param connection the connection to close */ protected void closeResources(Connection connection) { if (cacheConnection) return; if (connection != null && dataSource != null) { try { connection.close(); } catch (SQLException e) { LOG.finest("Caught exception closing connection: " + e.getMessage() + " - continuing"); } } } /** * Provides a hook for derived classes to be able to configure JDBC statements. * Default behavior is to call a previously saved closure, if any, using the * statement as a parameter. * * @param statement the statement to configure */ protected void configure(Statement statement) { // for thread safety, grab local copy Closure configureStatement = this.configureStatement; if (configureStatement != null) { configureStatement.call(statement); } } // private implementation methods //------------------------------------------------------------------------- private List> calculateKeys(ResultSet keys) throws SQLException { // Prepare a list to contain the auto-generated column // values, and then fetch them from the statement. List> autoKeys = new ArrayList>(); int count = keys.getMetaData().getColumnCount(); // Copy the column values into a list of a list. while (keys.next()) { List rowKeys = new ArrayList(count); for (int i = 1; i <= count; i++) { rowKeys.add(keys.getObject(i)); } autoKeys.add(rowKeys); } return autoKeys; } private Statement createStatement(Connection connection) throws SQLException { if (resultSetHoldability == -1) { return connection.createStatement(resultSetType, resultSetConcurrency); } return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } private void handleError(Connection connection, Throwable t) throws SQLException { if (connection != null) { LOG.warning("Rolling back due to: " + t.getMessage()); connection.rollback(); } } private void callClosurePossiblyWithConnection(Closure closure, Connection connection) { if (closure.getMaximumNumberOfParameters() == 1) { closure.call(connection); } else { closure.call(); } } private void clearStatementCache() { Statement statements[]; synchronized (statementCache) { if (statementCache.isEmpty()) return; // Arrange to call close() outside synchronized block, since // the close may involve server requests. statements = new Statement[statementCache.size()]; statementCache.values().toArray(statements); statementCache.clear(); } for (Statement s : statements) { try { s.close(); } catch (Exception e) { // It's normally safe to ignore exceptions during cleanup but here if there is // a closed statement in the cache, the cache is possibly corrupted, hence log // at slightly elevated level than similar cases. LOG.info("Failed to close statement. Already closed? Exception message: " + e.getMessage()); } } } private Statement getAbstractStatement(AbstractStatementCommand cmd, Connection connection, String sql) throws SQLException { Statement stmt; if (cacheStatements) { synchronized (statementCache) { // checking for existence without sync can cause leak if object needs close(). stmt = statementCache.get(sql); if (stmt == null) { stmt = cmd.execute(connection, sql); statementCache.put(sql, stmt); } } } else { stmt = cmd.execute(connection, sql); } return stmt; } private Statement getStatement(Connection connection, String sql) throws SQLException { LOG.fine(sql); Statement stmt = getAbstractStatement(new CreateStatementCommand(), connection, sql); configure(stmt); return stmt; } private PreparedStatement getPreparedStatement(Connection connection, String sql, List params, int returnGeneratedKeys) throws SQLException { SqlWithParams updated = checkForNamedParams(sql, params); LOG.fine(updated.getSql() + " | " + updated.getParams()); PreparedStatement statement = (PreparedStatement) getAbstractStatement(new CreatePreparedStatementCommand(returnGeneratedKeys), connection, updated.getSql()); setParameters(updated.getParams(), statement); configure(statement); return statement; } public SqlWithParams checkForNamedParams(String sql, List params) { SqlWithParams preCheck = preCheckForNamedParams(sql); if (preCheck == null) { return new SqlWithParams(sql, params); } List indexPropList = new ArrayList(); for (Object next : preCheck.getParams()) { indexPropList.add((Tuple) next); } return new SqlWithParams(preCheck.getSql(), getUpdatedParams(params, indexPropList)); } public SqlWithParams preCheckForNamedParams(String sql) { // look for quick exit if (!enableNamedQueries || !NAMED_QUERY_PATTERN.matcher(sql).find()) { return null; } ExtractIndexAndSql extractIndexAndSql = new ExtractIndexAndSql(sql).invoke(); String newSql = extractIndexAndSql.getNewSql(); if (sql.equals(newSql)) { return null; } List indexPropList = new ArrayList(extractIndexAndSql.getIndexPropList()); return new SqlWithParams(newSql, indexPropList); } public List getUpdatedParams(List params, List indexPropList) { List updatedParams = new ArrayList(); for (Tuple tuple : indexPropList) { int index = (Integer) tuple.get(0); String prop = (String) tuple.get(1); if (index < 0 || index >= params.size()) throw new IllegalArgumentException("Invalid index " + index + " should be in range 1.." + params.size()); updatedParams.add(prop.equals("") ? params.get(index) : InvokerHelper.getProperty(params.get(index), prop)); } return updatedParams; } private PreparedStatement getPreparedStatement(Connection connection, String sql, List params) throws SQLException { return getPreparedStatement(connection, sql, params, 0); } /** * @return boolean true if caching is enabled (the default is true) */ public boolean isCacheNamedQueries() { return cacheNamedQueries; } /** * Enables named query caching.
    * if cacheNamedQueries is true, cache is created and processed named queries will be cached.
    * if cacheNamedQueries is false, no caching will occur saving memory at the cost of additional processing time. * * @param cacheNamedQueries the new value */ public void setCacheNamedQueries(boolean cacheNamedQueries) { this.cacheNamedQueries = cacheNamedQueries; } /** * @return boolean true if named query processing is enabled (the default is true) */ public boolean isEnableNamedQueries() { return enableNamedQueries; } /** * Enables named query support.
    * if enableNamedQueries is true, queries with ':propname' and '?1.propname' style placeholders will be processed.
    * if enableNamedQueries is false, this feature will be turned off. * * @param enableNamedQueries the new value */ public void setEnableNamedQueries(boolean enableNamedQueries) { this.enableNamedQueries = enableNamedQueries; } // command pattern implementation classes //------------------------------------------------------------------------- private abstract class AbstractStatementCommand { /** * Execute the command that's defined by the subclass following * the Command pattern. Specialized parameters are held in the command instances. * * @param conn all commands accept a connection * @param sql all commands accept an SQL statement * @return statement that can be cached, etc. * @throws SQLException if a database error occurs */ abstract Statement execute(Connection conn, String sql) throws SQLException; } private class CreatePreparedStatementCommand extends AbstractStatementCommand { private final int returnGeneratedKeys; CreatePreparedStatementCommand(int returnGeneratedKeys) { this.returnGeneratedKeys = returnGeneratedKeys; } PreparedStatement execute(Connection connection, String sql) throws SQLException { if (returnGeneratedKeys != 0) return connection.prepareStatement(sql, returnGeneratedKeys); if (appearsLikeStoredProc(sql)) return connection.prepareCall(sql); return connection.prepareStatement(sql); } boolean appearsLikeStoredProc(String sql) { return sql.matches("\\s*[{]?\\s*[?]?\\s*[=]?\\s*[cC][aA][lL][lL].*"); } } private class CreateStatementCommand extends AbstractStatementCommand { @Override Statement execute(Connection conn, String sql) throws SQLException { return createStatement(conn); } } protected abstract class AbstractQueryCommand { protected final String sql; protected Statement statement; private Connection connection; AbstractQueryCommand(String sql) { // Don't create statement in subclass constructors to avoid throw in constructors this.sql = sql; } /** * Execute the command that's defined by the subclass following * the Command pattern. Specialized parameters are held in the command instances. * * @return ResultSet from executing a query * @throws SQLException if a database error occurs */ final ResultSet execute() throws SQLException { connection = createConnection(); setInternalConnection(connection); statement = null; try { // The variation in the pattern is isolated ResultSet result = runQuery(connection); assert (null != statement); return result; } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); closeResources(); connection = null; statement = null; throw e; } } /** * After performing the execute operation and making use of its return, it's necessary * to free the resources allocated for the statement. */ public final void closeResources(){ Sql.this.closeResources(connection, statement); } /** * After performing the execute operation and making use of its return, it's necessary * to free the resources allocated for the statement. * * @param rs allows the caller to conveniently close its resource as well */ public final void closeResources(ResultSet rs) { Sql.this.closeResources(connection, statement, rs); } /** * Perform the query. Must set statement field so that the main ({@link #execute()}) method can clean up. * This is the method that encloses the variant part of the code. * @param connection the connection to use * @return ResultSet from an executeQuery method. * @throws SQLException if a database error occurs */ protected abstract ResultSet runQuery(Connection connection) throws SQLException; } protected final class PreparedQueryCommand extends AbstractQueryCommand { private List params; PreparedQueryCommand(String sql, List queryParams) { super(sql); params = queryParams; } @Override protected ResultSet runQuery(Connection connection) throws SQLException { PreparedStatement s = getPreparedStatement(connection, sql, params); statement = s; return s.executeQuery(); } } protected final class QueryCommand extends AbstractQueryCommand { QueryCommand(String sql) { super(sql); } @Override protected ResultSet runQuery(Connection connection) throws SQLException { statement = getStatement(connection, sql); return statement.executeQuery(sql); } } /** * Factory for the QueryCommand command pattern object allows subclasses to * supply implementations of the command class. The factory will be used in a pattern * similar to *
         * AbstractQueryCommand q = createQueryCommand("update TABLE set count = 0) where count is null");
         * try {
         *        ResultSet rs = q.execute();
         *     return asList(rs);
         * } finally {
         *     q.closeResources();
         * }
         * 
    * @param sql statement to be executed * @return a command - invoke its execute() and closeResource() methods */ protected AbstractQueryCommand createQueryCommand(String sql) { return new QueryCommand(sql); } /** * Factory for the PreparedQueryCommand command pattern object allows subclass to supply implementations * of the command class. * @see #createQueryCommand(String) * @param sql statement to be executed, including optional parameter placeholders (?) * @param queryParams List of parameter values corresponding to parameter placeholders * @return a command - invoke its execute() and closeResource() methods */ protected AbstractQueryCommand createPreparedQueryCommand(String sql, List queryParams) { return new PreparedQueryCommand(sql, queryParams); } /** * Stub needed for testing. Called when a connection is opened by one of the command-pattern classes * so that a test case can monitor the state of the connection through its subclass. * @param conn the connection that is about to be used by a command */ protected void setInternalConnection(Connection conn) { } private class ExtractIndexAndSql { private String sql; private List indexPropList; private String newSql; public ExtractIndexAndSql(String sql) { this.sql = sql; } public List getIndexPropList() { return indexPropList; } public String getNewSql() { return newSql; } public ExtractIndexAndSql invoke() { if (cacheNamedQueries && namedParamSqlCache.containsKey(sql)) { newSql = namedParamSqlCache.get(sql); indexPropList = namedParamIndexPropCache.get(sql); } else { indexPropList = new ArrayList(); StringBuilder sb = new StringBuilder(); StringBuilder currentChunk = new StringBuilder(); char[] chars = sql.toCharArray(); int i = 0; boolean inString = false; //TODO: Cater for comments? while (i < chars.length) { switch (chars[i]) { case '\'': inString = !inString; if (inString) { sb.append(adaptForNamedParams(currentChunk.toString(), indexPropList)); currentChunk = new StringBuilder(); currentChunk.append(chars[i]); } else { currentChunk.append(chars[i]); sb.append(currentChunk); currentChunk = new StringBuilder(); } break; default: currentChunk.append(chars[i]); } i++; } if (inString) throw new IllegalStateException("Failed to process query. Unterminated ' character?"); sb.append(adaptForNamedParams(currentChunk.toString(), indexPropList)); newSql = sb.toString(); namedParamSqlCache.put(sql, newSql); namedParamIndexPropCache.put(sql, indexPropList); } return this; } private String adaptForNamedParams(String sql, List indexPropList) { StringBuilder newSql = new StringBuilder(); int txtIndex = 0; Matcher matcher = NAMED_QUERY_PATTERN.matcher(sql); while (matcher.find()) { newSql.append(sql.substring(txtIndex, matcher.start())).append('?'); String indexStr = matcher.group(1); int index = (indexStr == null || indexStr.length() == 0) ? 0 : new Integer(indexStr) - 1; String prop = matcher.group(2); indexPropList.add(new Tuple(new Object[]{index, prop.length() == 0 ? "" : prop})); txtIndex = matcher.end(); } newSql.append(sql.substring(txtIndex)); // append ending SQL after last param. return newSql.toString(); } } } groovy-1.8.6/src/main/groovy/sql/GroovyResultSetExtension.java0000644001501200150120000002274111627206700024137 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingPropertyException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.ResultSetMetaData; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.InvokerInvocationException; /** * GroovyResultSetExtension implements additional logic for ResultSet. Due to * the version incompatibility between java6 and java5 this methods are moved * here from the original GroovyResultSet class. The methods in this class are * used by the proxy GroovyResultSetProxy, which will try to invoke methods * on this class before invoking it on ResultSet. *

    *

    This class is not intended to be used directly. Should be used through * GroovyResultSetProxy only!

    * * @author Jochen Theodorou * @see GroovyResultSet * @see GroovyResultSetProxy */ public class GroovyResultSetExtension extends GroovyObjectSupport { private boolean updated; private final ResultSet resultSet; /** * Gets the current result set. * * @return the result set * @throws SQLException if the result set can not be returned */ protected ResultSet getResultSet() throws SQLException { return resultSet; } /** * Creates a GroovyResultSet implementation. * * @param set the result set */ public GroovyResultSetExtension(ResultSet set) { updated = false; resultSet = set; } public String toString() { try { StringBuffer sb = new StringBuffer("["); ResultSetMetaData metaData = resultSet.getMetaData(); int count = metaData.getColumnCount(); for (int i = 1; i <= count; i++) { sb.append(metaData.getColumnName(i)); sb.append(":"); Object object = resultSet.getObject(i); if (object!=null) { sb.append(object.toString()); } else { sb.append("[null]"); } if (i < count) { sb.append(", "); } } sb.append("]"); return sb.toString(); } catch (SQLException e) { // System.err.println("e.getMessage() = " + e.getMessage()); return super.toString(); } } public Object invokeMethod(String name, Object args) { try { return InvokerHelper.invokeMethod(getResultSet(), name, args); } catch (SQLException se) { throw new InvokerInvocationException(se); } } /** * Gets the value of the designated column in the current row * of as an Object. * * @param columnName the SQL name of the column * @return the returned column value * @throws MissingPropertyException if an SQLException happens while getting the object * @see groovy.lang.GroovyObject#getProperty(java.lang.String) * @see ResultSet#getObject(java.lang.String) */ public Object getProperty(String columnName) { try { return getResultSet().getObject(columnName); } catch (SQLException e) { throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e); } } /** * Updates the designated column with an Object value. * * @param columnName the SQL name of the column * @param newValue the updated value * @throws MissingPropertyException if an SQLException happens while setting the new value * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) * @see ResultSet#updateObject(java.lang.String, java.lang.Object) */ public void setProperty(String columnName, Object newValue) { try { getResultSet().updateObject(columnName, newValue); updated = true; } catch (SQLException e) { throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e); } } /** * Supports integer based subscript operators for accessing at numbered columns * starting at zero. Negative indices are supported, they will count from the last column backwards. * * @param index is the number of the column to look at starting at 1 * @return the returned column value * @throws java.sql.SQLException if something goes wrong * @see ResultSet#getObject(int) */ public Object getAt(int index) throws SQLException { index = normalizeIndex(index); return getResultSet().getObject(index); } /** * Supports integer based subscript operators for updating the values of numbered columns * starting at zero. Negative indices are supported, they will count from the last column backwards. * * @param index is the number of the column to look at starting at 1 * @param newValue the updated value * @throws java.sql.SQLException if something goes wrong * @see ResultSet#updateObject(java.lang.String, java.lang.Object) */ public void putAt(int index, Object newValue) throws SQLException { index = normalizeIndex(index); getResultSet().updateObject(index, newValue); } /** * Adds a new row to the result set * * @param values a map containing the mappings for column names and values * @throws java.sql.SQLException if something goes wrong * @see ResultSet#insertRow() * @see ResultSet#updateObject(java.lang.String, java.lang.Object) * @see ResultSet#moveToInsertRow() */ public void add(Map values) throws SQLException { getResultSet().moveToInsertRow(); for (Iterator iter = values.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); getResultSet().updateObject(entry.getKey().toString(), entry.getValue()); } getResultSet().insertRow(); } /** * Takes a zero based index and convert it into an SQL based 1 based index. * A negative index will count backwards from the last column. * * @param index the raw requested index (may be negative) * @return a JDBC index * @throws SQLException if some exception occurs finding out the column count */ protected int normalizeIndex(int index) throws SQLException { if (index < 0) { int columnCount = getResultSet().getMetaData().getColumnCount(); do { index += columnCount; } while (index < 0); } return index + 1; } /** * Call the closure once for each row in the result set. * * @param closure the closure to perform on each row * @throws SQLException if something goes wrong */ public void eachRow(Closure closure) throws SQLException { while (next()) { closure.call(this); } } // Implementation of java.sql.getResultSet() // ------------------------------------------------------------ /** * Moves the cursor down one row from its current position. * A getResultSet() cursor is initially positioned * before the first row; the first call to the method * next makes the first row the current row; the * second call makes the second row the current row, and so on. *

    *

    If an input stream is open for the current row, a call * to the method next will * implicitly close it. A getResultSet() object's * warning chain is cleared when a new row is read. * * @return true if the new current row is valid; * false if there are no more rows * @throws SQLException if a database access error occurs */ public boolean next() throws SQLException { if (updated) { getResultSet().updateRow(); updated = false; } return getResultSet().next(); } /** * Moves the cursor to the previous row in this * getResultSet() object. * * @return true if the cursor is on a valid row; * false if it is off the result set * @throws SQLException if a database access error * occurs or the result set type is TYPE_FORWARD_ONLY * @since 1.2 */ public boolean previous() throws SQLException { if (updated) { getResultSet().updateRow(); updated = false; } return getResultSet().previous(); } } groovy-1.8.6/src/main/groovy/sql/GroovyResultSet.java0000644001501200150120000000621211627206700022235 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.Closure; import groovy.lang.GroovyObject; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; /** * Represents an extent of objects * * @author James Strachan * @author Ivan Ganza * @author Chris Stevenson * @version $Revision$ */ public interface GroovyResultSet extends GroovyObject, ResultSet { /** * Supports integer-based subscript operators for accessing at numbered columns * starting at zero. Negative indices are supported, they will count from the last column backwards. * * @param index is the number of the column to look at starting at 1 * @return the object for this index in the current result set * @throws SQLException if a database error occurs */ Object getAt(int index) throws SQLException; /** * Gets the value of the designated column in the current row * as an Object. * * @param columnName the SQL name of the column * @return the returned column value * @throws groovy.lang.MissingPropertyException * if an SQLException happens while getting the object */ Object getAt(String columnName); /** * Supports integer based subscript operators for updating the values of numbered columns * starting at zero. Negative indices are supported, they will count from the last column backwards. * * @param index is the number of the column to look at starting at 1 * @param newValue the new value for this index * @throws SQLException if a database error occurs */ void putAt(int index, Object newValue) throws SQLException; /** * Updates the designated column with an Object value. * * @param columnName the SQL name of the column * @param newValue the updated value * @throws groovy.lang.MissingPropertyException * if an SQLException happens while setting the new value */ void putAt(String columnName, Object newValue); /** * Adds a new row to this result set * * @param values the new values to add * @throws SQLException if a database error occurs */ void add(Map values) throws SQLException; /** * Call the closure once for each row in the result set. * * @param closure the closure to call for each row * @throws SQLException if a database error occurs */ void eachRow(Closure closure) throws SQLException; } groovy-1.8.6/src/main/groovy/sql/package.html0000644001501200150120000000026611627206700020516 0ustar miguelmiguel package groovy.sql.*

    Groovy helper classes for working with SQL data as Groovy objects

    groovy-1.8.6/src/main/groovy/sql/InOutParameter.java0000644001501200150120000000145611627206700022001 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; /** * @author rfuller * * A typed parameter passed to, and returned from a CallableStatement. */ public interface InOutParameter extends InParameter, OutParameter { } groovy-1.8.6/src/main/groovy/sql/SqlOrderByVisitor.java0000644001501200150120000000243711627206700022510 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.stmt.ReturnStatement; /** * @author Paul King * @version $Revision: 6714 $ */ public class SqlOrderByVisitor extends CodeVisitorSupport { private StringBuffer buffer = new StringBuffer(); public String getOrderBy() { return buffer.toString(); } public void visitReturnStatement(ReturnStatement statement) { statement.getExpression().visit(this); } public void visitPropertyExpression(PropertyExpression expression) { buffer.append(expression.getPropertyAsString()); } } groovy-1.8.6/src/main/groovy/sql/SqlWithParams.java0000644001501200150120000000201011627206700021624 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import java.util.List; public class SqlWithParams { private String sql; private List params; public SqlWithParams(String sql, List params) { this.sql = sql; this.params = params; } public String getSql() { return sql; } public List getParams() { return params; } }groovy-1.8.6/src/main/groovy/sql/SqlWhereVisitor.java0000644001501200150120000000564211627206700022215 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; /** * @author James Strachan * @version $Revision$ */ public class SqlWhereVisitor extends CodeVisitorSupport { private final StringBuffer buffer = new StringBuffer(); private final List parameters = new ArrayList(); public String getWhere() { return buffer.toString(); } public void visitReturnStatement(ReturnStatement statement) { statement.getExpression().visit(this); } public void visitBinaryExpression(BinaryExpression expression) { Expression left = expression.getLeftExpression(); Expression right = expression.getRightExpression(); boolean leaf = (right instanceof ConstantExpression); if (!leaf) buffer.append("("); left.visit(this); buffer.append(" "); Token token = expression.getOperation(); buffer.append(tokenAsSql(token)); buffer.append(" "); right.visit(this); if (!leaf) buffer.append(")"); } public void visitBooleanExpression(BooleanExpression expression) { expression.getExpression().visit(this); } public void visitConstantExpression(ConstantExpression expression) { getParameters().add(expression.getValue()); buffer.append("?"); } public void visitPropertyExpression(PropertyExpression expression) { buffer.append(expression.getPropertyAsString()); } public List getParameters() { return parameters; } protected String tokenAsSql(Token token) { switch (token.getType()) { case Types.COMPARE_EQUAL : return "="; case Types.LOGICAL_AND : return "and"; case Types.LOGICAL_OR : return "or"; default : return token.getText(); } } } groovy-1.8.6/src/main/groovy/sql/ExpandedVariable.java0000644001501200150120000000150511627206700022273 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; /** * Identifies a variable to be expanded into the * sql string rather than representing a placeholder. * * @author rfuller */ public interface ExpandedVariable { Object getObject(); } groovy-1.8.6/src/main/groovy/sql/DataSet.java0000644001501200150120000002370511627206700020430 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.stmt.Statement; import java.sql.Connection; import java.sql.SQLException; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * An enhancement of Groovy's Sql class providing support for accessing * and querying databases using POGO fields and operators rather than * JDBC-level API calls and RDBMS column names. So, instead of a query like: *
     * def db = // an instance of groovy.sql.Sql
     * def sql = '''select * from Person
     *     where (purchaseCount > ? and birthMonth = ?)
     *     and (lastName < ? or lastName > ?)
     *     and age < ? and age > ? and firstName != ?
     *     order by firstName DESC, age'''
     * def params = [10, "January", "Zulu", "Alpha", 99, 5, "Bert"]
     * def sortedPeopleOfInterest = db.rows(sql, params)
     * 
    * You can write code like this: *
     * def person = new DataSet(db, 'Person') // or db.dataSet('Person'), or db.dataSet(Person)
     * def janFrequentBuyers = person.findAll { it.purchaseCount > 10 && it.lastName == "January" }
     * def sortedPeopleOfInterest = janFrequentBuyers.
     *     findAll{ it.lastName < 'Zulu' || it.lastName > 'Alpha' }.
     *     findAll{ it.age < 99 }.
     *     findAll{ it.age > 5 }.
     *     sort{ it.firstName }.reverse().
     *     findAll{ it.firstName != 'Bert' }.
     *     sort{ it.age }
     * 
    * Currently, the Groovy source code for any accessed POGO must be on the * classpath at runtime. * * @author Chris Stevenson * @author Paul King * @author James Strachan * @version $Revision$ */ public class DataSet extends Sql { private Closure where; private Closure sort; private boolean reversed = false; private DataSet parent; private String table; private SqlWhereVisitor visitor; private SqlOrderByVisitor sortVisitor; private String sql; private List params; private Sql delegate; public DataSet(Sql sql, Class type) { super(sql); delegate = sql; String table = type.getName(); int idx = table.lastIndexOf('.'); if (idx > 0) { table = table.substring(idx + 1); } this.table = table.toLowerCase(); } public DataSet(Sql sql, String table) { super(sql); delegate = sql; this.table = table; } private DataSet(DataSet parent, Closure where) { super(parent); this.delegate = parent.delegate; this.table = parent.table; this.parent = parent; this.where = where; } private DataSet(DataSet parent, Closure where, Closure sort) { super(parent); this.delegate = parent.delegate; this.table = parent.table; this.parent = parent; this.where = where; this.sort = sort; } private DataSet(DataSet parent) { super(parent); this.delegate = parent.delegate; this.table = parent.table; this.parent = parent; this.reversed = true; } @Override protected Connection createConnection() throws SQLException { return delegate.createConnection(); } @Override protected void closeResources(Connection connection, java.sql.Statement statement, ResultSet results) { delegate.closeResources(connection, statement, results); } @Override protected void closeResources(Connection connection, java.sql.Statement statement) { delegate.closeResources(connection, statement); } @Override public void cacheConnection(Closure closure) throws SQLException { delegate.cacheConnection(closure); } @Override public void withTransaction(Closure closure) throws SQLException { delegate.withTransaction(closure); } @Override public void commit() throws SQLException { delegate.commit(); } @Override public void rollback() throws SQLException { delegate.rollback(); } public void add(Map map) throws SQLException { StringBuffer buffer = new StringBuffer("insert into "); buffer.append(table); buffer.append(" ("); StringBuffer paramBuffer = new StringBuffer(); boolean first = true; for (String column : map.keySet()) { if (first) { first = false; paramBuffer.append("?"); } else { buffer.append(", "); paramBuffer.append(", ?"); } buffer.append(column); } buffer.append(") values ("); buffer.append(paramBuffer.toString()); buffer.append(")"); int answer = executeUpdate(buffer.toString(), new ArrayList(map.values())); if (answer != 1) { LOG.warning("Should have updated 1 row not " + answer + " when trying to add: " + map); } } public DataSet findAll(Closure where) { return new DataSet(this, where); } public DataSet sort(Closure sort) { return new DataSet(this, null, sort); } public DataSet reverse() { if (sort == null) { throw new GroovyRuntimeException("reverse() only allowed immediately after a sort()"); } return new DataSet(this); } public void each(Closure closure) throws SQLException { eachRow(getSql(), getParameters(), closure); } private String getSqlWhere() { String whereClaus = ""; String parentClaus = ""; if (parent != null) { parentClaus = parent.getSqlWhere(); } if (where != null) { whereClaus += getSqlWhereVisitor().getWhere(); } if (parentClaus.length() == 0) return whereClaus; if (whereClaus.length() == 0) return parentClaus; return parentClaus + " and " + whereClaus; } private String getSqlOrderBy() { String sortByClaus = ""; String parentClaus = ""; if (parent != null) { parentClaus = parent.getSqlOrderBy(); } if (reversed) { if (parentClaus.length() > 0) parentClaus += " DESC"; } if (sort != null) { sortByClaus += getSqlOrderByVisitor().getOrderBy(); } if (parentClaus.length() == 0) return sortByClaus; if (sortByClaus.length() == 0) return parentClaus; return parentClaus + ", " + sortByClaus; } public String getSql() { if (sql == null) { sql = "select * from " + table; String whereClaus = getSqlWhere(); if (whereClaus.length() > 0) { sql += " where " + whereClaus; } String orerByClaus = getSqlOrderBy(); if (orerByClaus.length() > 0) { sql += " order by " + orerByClaus; } } return sql; } public List getParameters() { if (params == null) { params = new ArrayList(); if (parent != null) { params.addAll(parent.getParameters()); } params.addAll(getSqlWhereVisitor().getParameters()); } return params; } protected SqlWhereVisitor getSqlWhereVisitor() { if (visitor == null) { visitor = new SqlWhereVisitor(); visit(where, visitor); } return visitor; } protected SqlOrderByVisitor getSqlOrderByVisitor() { if (sortVisitor == null) { sortVisitor = new SqlOrderByVisitor(); visit(sort, sortVisitor); } return sortVisitor; } private void visit(Closure closure, CodeVisitorSupport visitor) { if (closure != null) { ClassNode classNode = closure.getMetaClass().getClassNode(); if (classNode == null) { throw new GroovyRuntimeException( "Could not find the ClassNode for MetaClass: " + closure.getMetaClass()); } List methods = classNode.getDeclaredMethods("doCall"); if (!methods.isEmpty()) { MethodNode method = (MethodNode) methods.get(0); if (method != null) { Statement statement = method.getCode(); if (statement != null) { statement.visit(visitor); } } } } } /* * create a subset of the original dataset */ public DataSet createView(Closure criteria) { return new DataSet(this, criteria); } /** * Returns a List of all of the rows from the table a DataSet * represents * * @return Returns a list of GroovyRowResult objects from the dataset * @throws SQLException if a database error occurs */ public List rows() throws SQLException { return rows(getSql(), getParameters()); } /** * Returns the first row from a DataSet's underlying table * * @return Returns the first GroovyRowResult object from the dataset * @throws SQLException if a database error occurs */ public Object firstRow() throws SQLException { List rows = rows(); if (rows.isEmpty()) return null; return (rows.get(0)); } } groovy-1.8.6/src/main/groovy/sql/BatchingStatementWrapper.java0000644001501200150120000000707411645141222024046 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.GroovyObjectSupport; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Class which delegates to a Statement but keeps track of a batch count size. * If the batch count reaches the predefined number, this Statement does an executeBatch() * automatically. If batchSize is zero, then no batching is performed. */ public class BatchingStatementWrapper extends GroovyObjectSupport { private Statement delegate; protected int batchSize; protected int batchCount; protected Logger log; protected List results; public BatchingStatementWrapper(Statement delegate, int batchSize, Logger log) { this.delegate = delegate; this.batchSize = batchSize; this.log = log; reset(); } protected void reset() { batchCount = 0; results = new ArrayList(); } @Override public Object invokeMethod(String name, Object args) { return InvokerHelper.invokeMethod(delegate, name, args); } public void addBatch(String sql) throws SQLException { delegate.addBatch(sql); batchCount++; if (batchCount == batchSize /* never true for batchSize of 0 */) { int[] result = delegate.executeBatch(); processResult(result); batchCount = 0; } } public void clearBatch() throws SQLException { if (batchSize != 0) { reset(); } delegate.clearBatch(); } public int[] executeBatch() throws SQLException { int[] lastResult = delegate.executeBatch(); processResult(lastResult); int[] result = new int[results.size()]; for (int i = 0; i < results.size(); i++) { result[i] = results.get(i); } reset(); return result; } protected void processResult(int[] lastResult) { boolean foundError = false; for (int i : lastResult) { if (i == Statement.EXECUTE_FAILED) foundError = true; results.add(i); } // A little bit of paranoid checking here? Most drivers will throw BatchUpdateException perhaps? if (batchCount != lastResult.length) { log.warning("Problem executing batch - expected result length of " + batchCount + " but got " + lastResult.length); } else if (foundError) { log.warning("Problem executing batch - at least one result failed in: " + DefaultGroovyMethods.toList(lastResult)); } else { log.fine("Successfully executed batch with " + lastResult.length + " command(s)"); } } public void close() throws SQLException { delegate.close(); } } groovy-1.8.6/src/main/groovy/sql/GroovyRowResult.java0000644001501200150120000001116211713766062022261 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingPropertyException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Represents an extent of objects. * It's used in the oneRow method to be able to access the result * of a SQL query by the name of the column, or by the column number. * * @version $Revision$ * @author Jean-Louis Berliet */ public class GroovyRowResult extends GroovyObjectSupport implements Map { private final Map result; public GroovyRowResult(Map result) { this.result = result; } /** * Retrieve the value of the property by its name * * @param property is the name of the property to look at * @return the value of the property */ public Object getProperty(String property) { try { Object key = lookupKeyIgnoringCase(property); if (key != null) { return result.get(key); } throw new MissingPropertyException(property, GroovyRowResult.class); } catch (Exception e) { throw new MissingPropertyException(property, GroovyRowResult.class, e); } } private Object lookupKeyIgnoringCase(Object key) { // try some special cases first for efficiency if (result.containsKey(key)) return key; if (!(key instanceof CharSequence)) return null; String keyStr = key.toString(); for (Object next : result.keySet()) { if (!(next instanceof String)) continue; if (keyStr.equalsIgnoreCase((String)next)) return next; } return null; } /** * Retrieve the value of the property by its index. * A negative index will count backwards from the last column. * * @param index is the number of the column to look at * @return the value of the property */ public Object getAt(int index) { try { // a negative index will count backwards from the last column. if (index < 0) index += result.size(); Iterator it = result.values().iterator(); int i = 0; Object obj = null; while ((obj == null) && (it.hasNext())) { if (i == index) obj = it.next(); else it.next(); i++; } return obj; } catch (Exception e) { throw new MissingPropertyException(Integer.toString(index), GroovyRowResult.class, e); } } public String toString() { return result.toString(); } /* * The following methods are needed for implementing the Map interface. * They are mostly delegating the request to the provided Map. */ public void clear() { result.clear(); } public boolean containsKey(Object key) { return lookupKeyIgnoringCase(key) != null; } public boolean containsValue(Object value) { return result.containsValue(value); } public Set entrySet() { return result.entrySet(); } public boolean equals(Object o) { return result.equals(o); } public Object get(Object property) { if (property instanceof String) return getProperty((String)property); return null; } public int hashCode() { return result.hashCode(); } public boolean isEmpty() { return result.isEmpty(); } public Set keySet() { return result.keySet(); } public Object put(Object key, Object value) { return result.put(key, value); } public void putAll(Map t) { result.putAll(t); } public Object remove(Object rawKey) { return result.remove(lookupKeyIgnoringCase(rawKey)); } public int size() { return result.size(); } public Collection values() { return result.values(); } } groovy-1.8.6/src/main/groovy/sql/InParameter.java0000644001501200150120000000165211627206700021307 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; /** * A typed parameter to pass to a query * * @author rfuller */ public interface InParameter { /** * The JDBC data type. * @return the type */ int getType(); /** * The object holding the data value. * @return the value */ Object getValue(); }groovy-1.8.6/src/main/groovy/sql/CallResultSet.java0000644001501200150120000000305711627206700021627 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author rfuller *

    * Represents a ResultSet retrieved as a callable statement out parameter. */ class CallResultSet extends GroovyResultSetExtension { int indx; CallableStatement call; ResultSet resultSet; boolean firstCall = true; CallResultSet(CallableStatement call, int indx) { super(null); this.call = call; this.indx = indx; } protected ResultSet getResultSet() throws SQLException { if (firstCall) { resultSet = (ResultSet) call.getObject(indx + 1); firstCall = false; } return resultSet; } protected static GroovyResultSet getImpl(CallableStatement call, int idx) { GroovyResultSetProxy proxy = new GroovyResultSetProxy(new CallResultSet(call, idx)); return proxy.getImpl(); } } groovy-1.8.6/src/main/groovy/sql/OutParameter.java0000644001501200150120000000154611627206700021512 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; /** * A parameter to be returned from a CallableStatement. * * @author rfuller */ public interface OutParameter { /** * Get the JDBC datatype for this parameter. * @return the type */ int getType(); } groovy-1.8.6/src/main/groovy/sql/GroovyResultSetProxy.java0000644001501200150120000001011111627206700023270 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.sql; import groovy.lang.GroovyObject; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.ResultSet; import org.codehaus.groovy.runtime.InvokerHelper; /** * GroovyResultSetProxy is used to create a proxy for GroovyResultSet. * Due to the version incompatibility between java 6 and older versions * methods with additional logic were moved into an extension class. When * getting properties or calling methods, the runtime will try to first * execute these on the extension and then on the ResultSet itself. * This way it is possible to replace and add methods. To overload methods * from ResultSet all methods have to be implemented on the extension * class. * * @author Jochen Theodorou */ public final class GroovyResultSetProxy implements InvocationHandler { private GroovyResultSetExtension extension; /** * Creates a new proxy instance. * This will create the extension automatically using * GroovyResultSetExtension * * @param set the result set to delegate to * @see GroovyResultSetExtension */ public GroovyResultSetProxy(ResultSet set) { extension = new GroovyResultSetExtension(set); } /** * Creates a new proxy instance with a custom extension. * * @param ext the extension * @see GroovyResultSetExtension */ public GroovyResultSetProxy(GroovyResultSetExtension ext) { extension = ext; } /** * Invokes a method for the GroovyResultSet. * This will try to invoke the given method first on the extension * and then on the result set given as proxy parameter. * * @param proxy the result set * @param method the method name of this method will be used * to make a call on the extension. If this fails the call will be * done on the proxy instead * @param args for the call * @see ResultSet * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if (method.getDeclaringClass() == GroovyObject.class) { if (name.equals("getMetaClass")) { return getMetaClass(); } else if (name.equals("setMetaClass")) { return setMetaClass((MetaClass) args[0]); } } return InvokerHelper.invokeMethod(extension, method.getName(), args); } private MetaClass metaClass; private MetaClass setMetaClass(MetaClass mc) { metaClass = mc; return mc; } private MetaClass getMetaClass() { if (metaClass == null) { metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(GroovyResultSet.class); } return metaClass; } /** * Gets a proxy instance that can be used as GroovyResultSet. * * @return the proxy */ public GroovyResultSet getImpl() { return (GroovyResultSet) Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[]{GroovyResultSet.class}, this ); } }groovy-1.8.6/src/main/groovy/grape/0000755001501200150120000000000011715031256016530 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/grape/GrapeIvy.groovy0000644001501200150120000005703211715031256021534 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.grape import java.util.regex.Pattern import org.apache.ivy.Ivy import org.apache.ivy.core.cache.ResolutionCacheManager import org.apache.ivy.core.event.IvyListener import org.apache.ivy.core.event.download.PrepareDownloadEvent import org.apache.ivy.core.event.resolve.StartResolveEvent import org.apache.ivy.core.module.descriptor.Configuration import org.apache.ivy.core.module.descriptor.DefaultDependencyArtifactDescriptor import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor import org.apache.ivy.core.module.descriptor.DefaultExcludeRule import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor import org.apache.ivy.core.module.id.ArtifactId import org.apache.ivy.core.module.id.ModuleId import org.apache.ivy.core.module.id.ModuleRevisionId import org.apache.ivy.core.report.ArtifactDownloadReport import org.apache.ivy.core.report.ResolveReport import org.apache.ivy.core.resolve.ResolveOptions import org.apache.ivy.core.settings.IvySettings import org.apache.ivy.plugins.matcher.ExactPatternMatcher import org.apache.ivy.plugins.matcher.PatternMatcher import org.apache.ivy.plugins.resolver.ChainResolver import org.apache.ivy.plugins.resolver.IBiblioResolver import org.apache.ivy.util.DefaultMessageLogger import org.apache.ivy.util.Message import org.codehaus.groovy.reflection.ReflectionUtils //import java.util.zip.ZipFile //import java.util.zip.ZipEntry /** * @author Danno Ferrin * @author Paul King * @author Roshan Dawrani (roshandawrani) */ class GrapeIvy implements GrapeEngine { static final int DEFAULT_DEPTH = 3 private final exclusiveGrabArgs = [ ['group', 'groupId', 'organisation', 'organization', 'org'], ['module', 'artifactId', 'artifact'], ['version', 'revision', 'rev'], ['conf', 'scope', 'configuration'], ].inject([:], {m, g -> g.each {a -> m[a] = (g - a) as Set}; m}) boolean enableGrapes Ivy ivyInstance Set resolvedDependencies Set downloadedArtifacts // weak hash map so we don't leak loaders directly Map> loadedDeps = new WeakHashMap>() // set that stores the IvyGrabRecord(s) for all the dependencies in each grab() call Set grabRecordsForCurrDependencies = new LinkedHashSet() // we keep the settings so that addResolver can add to the resolver chain IvySettings settings public GrapeIvy() { // if we are already initialized, quit if (enableGrapes) return // start ivy Message.defaultLogger = new DefaultMessageLogger(System.getProperty("ivy.message.logger.level", "-1") as int) settings = new IvySettings() // configure settings def grapeConfig = getLocalGrapeConfig() if (!grapeConfig.exists()) { grapeConfig = GrapeIvy.class.getResource("defaultGrapeConfig.xml") } try { settings.load(grapeConfig) // exploit multi-methods for convenience } catch (java.text.ParseException ex) { System.err.println "Local Ivy config file '$grapeConfig.canonicalPath' appears corrupt - ignoring it and using default config instead\nError was: " + ex.message grapeConfig = GrapeIvy.class.getResource("defaultGrapeConfig.xml") settings.load(grapeConfig) } // set up the cache dirs settings.defaultCache = getGrapeCacheDir() settings.setVariable("ivy.default.configuration.m2compatible", "true") ivyInstance = Ivy.newInstance(settings) resolvedDependencies = [] downloadedArtifacts = [] //TODO add grab to the DGM?? enableGrapes = true } public File getGroovyRoot() { String root = System.getProperty("groovy.root") def groovyRoot if (root == null) { groovyRoot = new File(System.getProperty("user.home"), ".groovy") } else { groovyRoot = new File(root) } try { groovyRoot = groovyRoot.canonicalFile } catch (IOException e) { // skip canonicalization then, it may not exist yet } return groovyRoot } public File getLocalGrapeConfig() { String grapeConfig = System.getProperty("grape.config") if(grapeConfig) { return new File(grapeConfig) } else { return new File(getGrapeDir(), 'grapeConfig.xml') } } public File getGrapeDir() { String root = System.getProperty("grape.root") if(root == null) { return getGroovyRoot() } else { File grapeRoot = new File(root) try { grapeRoot = grapeRoot.canonicalFile } catch (IOException e) { // skip canonicalization then, it may not exist yet } return grapeRoot } } public File getGrapeCacheDir() { File cache = new File(getGrapeDir(), 'grapes') if (!cache.exists()) { cache.mkdirs() } else if (!cache.isDirectory()) { throw new RuntimeException("The grape cache dir $cache is not a directory") } return cache } public def chooseClassLoader(Map args) { def loader = args.classLoader if (!isValidTargetClassLoader(loader)) { loader = (args.refObject?.class ?:ReflectionUtils.getCallingClass(args.calleeDepth?:1) )?.classLoader while (loader && !isValidTargetClassLoader(loader)) { loader = loader.parent } //if (!isValidTargetClassLoader(loader)) { // loader = Thread.currentThread().contextClassLoader //} //if (!isValidTargetClassLoader(loader)) { // loader = GrapeIvy.class.classLoader //} if (!isValidTargetClassLoader(loader)) { throw new RuntimeException("No suitable ClassLoader found for grab") } } return loader } private boolean isValidTargetClassLoader(loader) { return isValidTargetClassLoaderClass(loader?.class) } private boolean isValidTargetClassLoaderClass(Class loaderClass) { return (loaderClass != null) && ( (loaderClass.name == 'groovy.lang.GroovyClassLoader') || (loaderClass.name == 'org.codehaus.groovy.tools.RootLoader') || isValidTargetClassLoaderClass(loaderClass.superclass) ) } public IvyGrabRecord createGrabRecord(Map deps) { // parse the actual dependency arguments String module = deps.module ?: deps.artifactId ?: deps.artifact if (!module) { throw new RuntimeException('grab requires at least a module: or artifactId: or artifact: argument') } String groupId = deps.group ?: deps.groupId ?: deps.organisation ?: deps.organization ?: deps.org ?: '' String ext = deps.ext ?: deps.type ?: '' String type = deps.type ?: '' //TODO accept ranges and decode them? except '1.0.0'..<'2.0.0' won't work in groovy String version = deps.version ?: deps.revision ?: deps.rev ?: '*' if ('*' == version) version = 'latest.default' ModuleRevisionId mrid = ModuleRevisionId.newInstance(groupId, module, version) boolean force = deps.containsKey('force') ? deps.force : true boolean changing = deps.containsKey('changing') ? deps.changing : false boolean transitive = deps.containsKey('transitive') ? deps.transitive : true def conf = deps.conf ?: deps.scope ?: deps.configuration ?: ['default'] if (conf instanceof String) { if (conf.startsWith("[") && conf.endsWith("]")) conf = conf[1..-2] conf = conf.split(",").toList() } def classifier = deps.classifier ?: null return new IvyGrabRecord(mrid:mrid, conf:conf, changing:changing, transitive:transitive, force:force, classifier:classifier, ext:ext, type:type) } public grab(String endorsedModule) { return grab(group:'groovy.endorsed', module:endorsedModule, version:GroovySystem.version) } public grab(Map args) { args.calleeDepth = args.calleeDepth?:DEFAULT_DEPTH + 1 return grab(args, args) } public grab(Map args, Map... dependencies) { def loader grabRecordsForCurrDependencies.clear() try { // identify the target classloader early, so we fail before checking repositories loader = chooseClassLoader( classLoader:args.remove('classLoader'), refObject:args.remove('refObject'), calleeDepth:args.calleeDepth?:DEFAULT_DEPTH, ) // check for non-fail null. // If we were in fail mode we would have already thrown an exception if (!loader) return for (URI uri in resolve(loader, args, dependencies)) { //TODO check artifact type, jar vs library, etc // processServices(new File(uri)); loader.addURL(uri.toURL()) } } catch (Exception e) { // clean-up the state first Set grabRecordsForCurrLoader = getLoadedDepsForLoader(loader) grabRecordsForCurrLoader.removeAll(grabRecordsForCurrDependencies) grabRecordsForCurrDependencies.clear() if (args.noExceptions) { return e } else { throw e } } return null } // void processServices(File f) { // System.out.println('Processing ' + f.getCanonicalPath()) // ZipFile zf = new ZipFile(f) // ZipEntry dgmMethods = zf.getEntry("META-INF/services/groovy/defaultGroovyMethods") // if (dgmMethods == null) return // InputStream is = zf.getInputStream(dgmMethods) // List classNames = is.text.readLines() // classNames.each { // println it.trim() // } // } public ResolveReport getDependencies(Map args, IvyGrabRecord... grabRecords) { ResolutionCacheManager cacheManager = ivyInstance.resolutionCacheManager def md = new DefaultModuleDescriptor(ModuleRevisionId .newInstance("caller", "all-caller", "working"), "integration", null, true) md.addConfiguration(new Configuration('default')) md.setLastModified(System.currentTimeMillis()) addExcludesIfNeeded(args, md) for (IvyGrabRecord grabRecord : grabRecords) { DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, grabRecord.mrid, grabRecord.force, grabRecord.changing, grabRecord.transitive) def conf = grabRecord.conf ?: ['*'] conf.each {dd.addDependencyConfiguration('default', it)} if (grabRecord.classifier) { def dad = new DefaultDependencyArtifactDescriptor(dd, grabRecord.mrid.name, grabRecord.type ?: 'jar', grabRecord.ext ?: 'jar', null, [classifier:grabRecord.classifier]) conf.each { dad.addConfiguration(it) } dd.addDependencyArtifact('default', dad) } md.addDependency(dd) } // resolve grab and dependencies ResolveOptions resolveOptions = new ResolveOptions()\ .setConfs(['default'] as String[])\ .setOutputReport(false)\ .setValidate(args.containsKey('validate') ? args.validate : false) ivyInstance.settings.defaultResolver = args.autoDownload ? 'downloadGrapes' : 'cachedGrapes' boolean reportDownloads = System.getProperty('groovy.grape.report.downloads', 'false') == 'true' if (reportDownloads) { ivyInstance.eventManager.addIvyListener([progress:{ ivyEvent -> switch(ivyEvent) { case StartResolveEvent: ivyEvent.moduleDescriptor.dependencies.each { it -> def name = it.toString() if (!resolvedDependencies.contains(name)) { resolvedDependencies << name System.err.println "Resolving " + name } } break case PrepareDownloadEvent: ivyEvent.artifacts.each { it -> def name = it.toString() if (!downloadedArtifacts.contains(name)) { downloadedArtifacts << name System.err.println "Preparing to download artifact " + name } } break } } ] as IvyListener) } ResolveReport report = ivyInstance.resolve(md, resolveOptions) if (report.hasError()) { throw new RuntimeException("Error grabbing Grapes -- $report.allProblemMessages") } if (report.downloadSize && reportDownloads) { System.err.println "Downloaded ${report.downloadSize >> 10} Kbytes in ${report.downloadTime}ms:\n ${report.allArtifactsReports*.toString().join('\n ')}" } md = report.moduleDescriptor if (!args.preserveFiles) { cacheManager.getResolvedIvyFileInCache(md.moduleRevisionId).delete() cacheManager.getResolvedIvyPropertiesInCache(md.moduleRevisionId).delete() } return report } public void uninstallArtifact(String group, String module, String rev) { // TODO consider transitive uninstall as an option Pattern ivyFilePattern = ~/ivy-(.*)\.xml/ //TODO get pattern from ivy conf grapeCacheDir.eachDir { File groupDir -> if (groupDir.name == group) groupDir.eachDir { File moduleDir -> if (moduleDir.name == module) moduleDir.eachFileMatch(ivyFilePattern) { File ivyFile -> def m = ivyFilePattern.matcher(ivyFile.name) if (m.matches() && m.group(1) == rev) { def root = new XmlParser(false, false).parse(ivyFile) // TODO handle other types? e.g. 'dlls' def jardir = new File(moduleDir, 'jars') if (!jardir.exists()) return root.publications.artifact.each { def name = it.@name + "-$rev" def classifier = it.'@m:classifier' if (classifier) name += "-$classifier" name += ".${it.@ext}" def jarfile = new File(jardir, name) if (jarfile.exists()) { println "Deleting ${jarfile.name}" jarfile.delete() } } ivyFile.delete() } } } } } private addExcludesIfNeeded(Map args, DefaultModuleDescriptor md) { if (!args.containsKey('excludes')) return args.excludes.each{ map -> def excludeRule = new DefaultExcludeRule(new ArtifactId( new ModuleId(map.group, map.module), PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION), ExactPatternMatcher.INSTANCE, null) excludeRule.addConfiguration('default') md.addExcludeRule(excludeRule) } } public Map>> enumerateGrapes() { Map>> bunches = [:] Pattern ivyFilePattern = ~/ivy-(.*)\.xml/ //TODO get pattern from ivy conf grapeCacheDir.eachDir {File groupDir -> Map> grapes = [:] bunches[groupDir.name] = grapes groupDir.eachDir { File moduleDir -> def versions = [] moduleDir.eachFileMatch(ivyFilePattern) {File ivyFile -> def m = ivyFilePattern.matcher(ivyFile.name) if (m.matches()) versions += m.group(1) } grapes[moduleDir.name] = versions } } return bunches } public URI[] resolve(Map args, Map ... dependencies) { resolve(args, null, dependencies) } public URI[] resolve(Map args, List depsInfo, Map ... dependencies) { // identify the target classloader early, so we fail before checking repositories def loader = chooseClassLoader( classLoader: args.remove('classLoader'), refObject: args.remove('refObject'), calleeDepth: args.calleeDepth ?: DEFAULT_DEPTH, ) // check for non-fail null. // If we were in fail mode we would have already thrown an exception if (!loader) return resolve(loader, args, depsInfo, dependencies) } URI [] resolve(ClassLoader loader, Map args, Map... dependencies) { return resolve(loader, args, null, dependencies) } URI [] resolve(ClassLoader loader, Map args, List depsInfo, Map... dependencies) { // check for mutually exclusive arguments Set keys = args.keySet() keys.each {a -> Set badArgs = exclusiveGrabArgs[a] if (badArgs && !badArgs.disjoint(keys)) { throw new RuntimeException("Mutually exclusive arguments passed into grab: ${keys.intersect(badArgs) + a}") } } // check the kill switch if (!enableGrapes) { return } boolean populateDepsInfo = (depsInfo != null) Set localDeps = getLoadedDepsForLoader(loader) dependencies.each { IvyGrabRecord igr = createGrabRecord(it) grabRecordsForCurrDependencies.add(igr) localDeps.add(igr) } // the call to reverse ensures that the newest additions are in // front causing existing dependencies to come last and thus // claiming higher priority. Thus when module versions clash we // err on the side of using the class already loaded into the // classloader rather than adding another jar of the same module // with a different version ResolveReport report = getDependencies(args, *localDeps.asList().reverse()) List results = [] for (ArtifactDownloadReport adl in report.allArtifactsReports) { //TODO check artifact type, jar vs library, etc if (adl.localFile) { results += adl.localFile.toURI() } } if (populateDepsInfo) { def deps = report.dependencies deps.each { depNode -> def id = depNode.id depsInfo << ['group' : id.organisation, 'module' : id.name, 'revision' : id.revision] } } return results as URI[] } private Set getLoadedDepsForLoader(ClassLoader loader) { Set localDeps = loadedDeps.get(loader) if (localDeps == null) { // use a linked set to preserve initial insertion order localDeps = new LinkedHashSet() loadedDeps.put(loader, localDeps) } return localDeps } public Map[] listDependencies (ClassLoader classLoader) { if (loadedDeps.containsKey(classLoader)) { List results = [] loadedDeps[classLoader].each { IvyGrabRecord grabbed -> def dep = [ group : grabbed.mrid.organisation, module : grabbed.mrid.name, version : grabbed.mrid.revision ] if (grabbed.conf != ['default']) { dep.conf = grabbed.conf } if (grabbed.changing) { dep.changing = grabbed.changing } if (!grabbed.transitive) { dep.transitive = grabbed.transitive } if (!grabbed.force) { dep.force = grabbed.force } if (grabbed.classifier) { dep.classifier = grabbed.classifier } if (grabbed.ext) { dep.ext = grabbed.ext } if (grabbed.type) { dep.type = grabbed.type } results << dep } return results } else { return null } } public void addResolver(Map args) { ChainResolver chainResolver = settings.getResolver("downloadGrapes") IBiblioResolver resolver = new IBiblioResolver(name: args.name, root:args.root, m2compatible:(args.m2Compatible ?: true), settings:settings) chainResolver.add(resolver) ivyInstance = Ivy.newInstance(settings) resolvedDependencies = [] downloadedArtifacts = [] } } class IvyGrabRecord { ModuleRevisionId mrid List conf boolean changing boolean transitive boolean force String classifier String ext String type public int hashCode() { return (mrid.hashCode() ^ conf.hashCode() ^ (changing ? 0xaaaaaaaa : 0x55555555) ^ (transitive ? 0xbbbbbbbb : 0x66666666) ^ (force ? 0xcccccccc: 0x77777777) ^ (classifier ? classifier.hashCode() : 0) ^ (ext ? ext.hashCode() : 0) ^ (type ? type.hashCode() : 0)) } public boolean equals(Object o) { return ((o.class == IvyGrabRecord) && (changing == o.changing) && (transitive == o.transitive) && (force== o.force) && (mrid == o.mrid) && (conf == o.conf) && (classifier == o.classifier) && (ext == o.ext) && (type == o.type)) } } groovy-1.8.6/src/main/groovy/grape/GrabAnnotationTransformation.java0000644001501200150120000006244511715031256025243 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.grape; import groovy.lang.Grab; import groovy.lang.GrabResolver; import groovy.lang.Grapes; import groovy.lang.GrabExclude; import groovy.lang.GrabConfig; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.ASTTransformationVisitor; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Transformation for declarative dependency management. */ @GroovyASTTransformation(phase=CompilePhase.CONVERSION) public class GrabAnnotationTransformation extends ClassCodeVisitorSupport implements ASTTransformation { private static final String GRAB_CLASS_NAME = Grab.class.getName(); private static final String GRAB_DOT_NAME = GRAB_CLASS_NAME.substring(GRAB_CLASS_NAME.lastIndexOf(".")); private static final String GRAB_SHORT_NAME = GRAB_DOT_NAME.substring(1); private static final String GRABEXCLUDE_CLASS_NAME = GrabExclude.class.getName(); private static final String GRABEXCLUDE_DOT_NAME = dotName(GRABEXCLUDE_CLASS_NAME); private static final String GRABEXCLUDE_SHORT_NAME = shortName(GRABEXCLUDE_DOT_NAME); private static final String GRABCONFIG_CLASS_NAME = GrabConfig.class.getName(); private static final String GRABCONFIG_DOT_NAME = dotName(GRABCONFIG_CLASS_NAME); private static final String GRABCONFIG_SHORT_NAME = shortName(GRABCONFIG_DOT_NAME); private static final String GRAPES_CLASS_NAME = Grapes.class.getName(); private static final String GRAPES_DOT_NAME = dotName(GRAPES_CLASS_NAME); private static final String GRAPES_SHORT_NAME = shortName(GRAPES_DOT_NAME); private static final String GRABRESOLVER_CLASS_NAME = GrabResolver.class.getName(); private static final String GRAPERESOLVER_DOT_NAME = dotName(GRABRESOLVER_CLASS_NAME); private static final String GRABRESOLVER_SHORT_NAME = shortName(GRAPERESOLVER_DOT_NAME); private static final ClassNode THREAD_CLASSNODE = ClassHelper.make(Thread.class); private static final List GRABEXCLUDE_REQUIRED = Arrays.asList("group", "module"); private static final List GRAPERESOLVER_REQUIRED = Arrays.asList("name", "root"); private static final List GRAB_REQUIRED = Arrays.asList("group", "module", "version"); private static final List GRAB_OPTIONAL = Arrays.asList("classifier", "transitive", "conf", "ext", "type", "changing", "force", "initClass"); private static final List GRAB_BOOLEAN = Arrays.asList("transitive", "changing", "force", "initClass"); private static final Collection GRAB_ALL = DefaultGroovyMethods.plus(GRAB_REQUIRED, GRAB_OPTIONAL); private static final Pattern IVY_PATTERN = Pattern.compile("([a-zA-Z0-9-/._+=]+)#([a-zA-Z0-9-/._+=]+)(;([a-zA-Z0-9-/.\\(\\)\\[\\]\\{\\}_+=,:@][a-zA-Z0-9-/.\\(\\)\\]\\{\\}_+=,:@]*))?(\\[([a-zA-Z0-9-/._+=,]*)\\])?"); private static final Pattern ATTRIBUTES_PATTERN = Pattern.compile("(.*;|^)([a-zA-Z0-9]+)=([a-zA-Z0-9.*\\[\\]\\-\\(\\),]*)$"); private static String dotName(String className) { return className.substring(className.lastIndexOf(".")); } private static String shortName(String className) { return className.substring(1); } boolean allowShortGrab; Set grabAliases; List grabAnnotations; boolean allowShortGrabExcludes; Set grabExcludeAliases; List grabExcludeAnnotations; boolean allowShortGrabConfig; Set grabConfigAliases; List grabConfigAnnotations; boolean allowShortGrapes; Set grapesAliases; List grapesAnnotations; boolean allowShortGrabResolver; Set grabResolverAliases; List grabResolverAnnotations; SourceUnit sourceUnit; ClassLoader loader; boolean initContextClassLoader; public SourceUnit getSourceUnit() { return sourceUnit; } public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; loader = null; initContextClassLoader = false; ModuleNode mn = (ModuleNode) nodes[0]; allowShortGrab = true; allowShortGrabExcludes = true; allowShortGrabConfig = true; allowShortGrapes = true; allowShortGrabResolver = true; grabAliases = new HashSet(); grabExcludeAliases = new HashSet(); grabConfigAliases = new HashSet(); grapesAliases = new HashSet(); grabResolverAliases = new HashSet(); for (ImportNode im : mn.getImports()) { String alias = im.getAlias(); String className = im.getClassName(); if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAB_CLASS_NAME.equals(alias))) { allowShortGrab = false; } else if (GRAB_CLASS_NAME.equals(className)) { grabAliases.add(im.getAlias()); } if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAPES_CLASS_NAME.equals(alias))) { allowShortGrapes = false; } else if (GRAPES_CLASS_NAME.equals(className)) { grapesAliases.add(im.getAlias()); } if ((className.endsWith(GRAPERESOLVER_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRABRESOLVER_CLASS_NAME.equals(alias))) { allowShortGrabResolver = false; } else if (GRABRESOLVER_CLASS_NAME.equals(className)) { grabResolverAliases.add(im.getAlias()); } } List> grabMaps = new ArrayList>(); List> grabExcludeMaps = new ArrayList>(); for (ClassNode classNode : sourceUnit.getAST().getClasses()) { grabAnnotations = new ArrayList(); grabExcludeAnnotations = new ArrayList(); grabConfigAnnotations = new ArrayList(); grapesAnnotations = new ArrayList(); grabResolverAnnotations = new ArrayList(); visitClass(classNode); ClassNode grapeClassNode = ClassHelper.make(Grape.class); if (!grabResolverAnnotations.isEmpty()) { grabResolverAnnotationLoop: for (AnnotationNode node : grabResolverAnnotations) { Map grapeResolverMap = new HashMap(); Expression value = node.getMember("value"); ConstantExpression ce = null; if (value != null && value instanceof ConstantExpression) { ce = (ConstantExpression) value; } String sval = null; if (ce != null && ce.getValue() instanceof String) { sval = (String) ce.getValue(); } if (sval != null && sval.length() > 0) { for (String s : GRAPERESOLVER_REQUIRED) { Expression member = node.getMember(s); if (member != null) { addError("The attribute \"" + s + "\" conflicts with attribute 'value' in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabResolverAnnotationLoop; } } grapeResolverMap.put("name", sval); grapeResolverMap.put("root", sval); } else { for (String s : GRAPERESOLVER_REQUIRED) { Expression member = node.getMember(s); if (member == null) { addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabResolverAnnotationLoop; } else if (member != null && !(member instanceof ConstantExpression)) { addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabResolverAnnotationLoop; } grapeResolverMap.put(s, ((ConstantExpression) member).getValue()); } } Grape.addResolver(grapeResolverMap); } } if (!grapesAnnotations.isEmpty()) { for (AnnotationNode node : grapesAnnotations) { Expression init = node.getMember("initClass"); Expression value = node.getMember("value"); if (value instanceof ListExpression) { for (Object o : ((ListExpression)value).getExpressions()) { if (o instanceof ConstantExpression) { extractGrab(init, (ConstantExpression) o); } } } else if (value instanceof ConstantExpression) { extractGrab(init, (ConstantExpression) value); } // don't worry if it's not a ListExpression, or AnnotationConstant, etc. // the rest of GroovyC will flag it as a syntax error later, so we don't // need to raise the error ourselves } } if (!grabConfigAnnotations.isEmpty()) { for (AnnotationNode node : grabConfigAnnotations) { checkForClassLoader(node); checkForInitContextClassLoader(node); } addInitContextClassLoaderIfNeeded(classNode); } if (!grabExcludeAnnotations.isEmpty()) { grabExcludeAnnotationLoop: for (AnnotationNode node : grabExcludeAnnotations) { Map grabExcludeMap = new HashMap(); checkForConvenienceForm(node, true); for (String s : GRABEXCLUDE_REQUIRED) { Expression member = node.getMember(s); if (member == null) { addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabExcludeAnnotationLoop; } else if (member != null && !(member instanceof ConstantExpression)) { addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabExcludeAnnotationLoop; } grabExcludeMap.put(s, ((ConstantExpression)member).getValue()); } grabExcludeMaps.add(grabExcludeMap); } } if (!grabAnnotations.isEmpty()) { grabAnnotationLoop: for (AnnotationNode node : grabAnnotations) { Map grabMap = new HashMap(); checkForConvenienceForm(node, false); for (String s : GRAB_ALL) { Expression member = node.getMember(s); if (member == null && !GRAB_OPTIONAL.contains(s)) { addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabAnnotationLoop; } else if (member != null && !(member instanceof ConstantExpression)) { addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabAnnotationLoop; } if (node.getMember(s) != null) grabMap.put(s, ((ConstantExpression)member).getValue()); } grabMaps.add(grabMap); callGrabAsStaticInitIfNeeded(classNode, grapeClassNode, node, grabExcludeMaps); } } } if (!grabMaps.isEmpty()) { Map basicArgs = new HashMap(); basicArgs.put("classLoader", loader != null ? loader : sourceUnit.getClassLoader()); if (!grabExcludeMaps.isEmpty()) basicArgs.put("excludes", grabExcludeMaps); try { Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()])); // grab may have added more transformations through new URLs added to classpath, so do one more scan ASTTransformationVisitor.addGlobalTransformsAfterGrab(); } catch (RuntimeException re) { // Decided against syntax exception since this is not a syntax error. // The down side is we lose line number information for the offending // @Grab annotation. source.addException(re); } } } private void callGrabAsStaticInitIfNeeded(ClassNode classNode, ClassNode grapeClassNode, AnnotationNode node, List> grabExcludeMaps) { if ((node.getMember("initClass") == null) || (node.getMember("initClass") == ConstantExpression.TRUE)) { List grabInitializers = new ArrayList(); // add Grape.grab(excludeArgs, [group:group, module:module, version:version, classifier:classifier]) // or Grape.grab([group:group, module:module, version:version, classifier:classifier]) MapExpression me = new MapExpression(); for (String s : GRAB_REQUIRED) { me.addMapEntryExpression(new ConstantExpression(s),node.getMember(s)); } for (String s : GRAB_OPTIONAL) { if (node.getMember(s) != null) me.addMapEntryExpression(new ConstantExpression(s),node.getMember(s)); } ArgumentListExpression grabArgs; if (grabExcludeMaps.isEmpty()) { grabArgs = new ArgumentListExpression(me); } else { MapExpression args = new MapExpression(); ListExpression list = new ListExpression(); for (Map map : grabExcludeMaps) { Set> entries = map.entrySet(); MapExpression inner = new MapExpression(); for (Map.Entry entry : entries) { inner.addMapEntryExpression(new ConstantExpression(entry.getKey()), new ConstantExpression(entry.getValue())); } list.addExpression(inner); } args.addMapEntryExpression(new ConstantExpression("excludes"), list); grabArgs = new ArgumentListExpression(args, me); } grabInitializers.add(new ExpressionStatement( new StaticMethodCallExpression(grapeClassNode, "grab", grabArgs))); // insert at beginning so we have the classloader set up before the class is called classNode.addStaticInitializerStatements(grabInitializers, true); } } private void addInitContextClassLoaderIfNeeded(ClassNode classNode) { if (initContextClassLoader) { Statement initStatement = new ExpressionStatement( new MethodCallExpression( new StaticMethodCallExpression(THREAD_CLASSNODE, "currentThread", ArgumentListExpression.EMPTY_ARGUMENTS), "setContextClassLoader", new MethodCallExpression( new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "getClass", MethodCallExpression.NO_ARGUMENTS), "getClassLoader", ArgumentListExpression.EMPTY_ARGUMENTS ) ) ); classNode.addObjectInitializerStatements(initStatement); } } private void checkForClassLoader(AnnotationNode node) { Object val = node.getMember("systemClassLoader"); if (val == null || !(val instanceof ConstantExpression)) return; Object systemClassLoaderObject = ((ConstantExpression)val).getValue(); if (!(systemClassLoaderObject instanceof Boolean)) return; Boolean systemClassLoader = (Boolean) systemClassLoaderObject; if (systemClassLoader) loader = ClassLoader.getSystemClassLoader(); } private void checkForInitContextClassLoader(AnnotationNode node) { Object val = node.getMember("initContextClassLoader"); if (val == null || !(val instanceof ConstantExpression)) return; Object initContextClassLoaderObject = ((ConstantExpression)val).getValue(); if (!(initContextClassLoaderObject instanceof Boolean)) return; initContextClassLoader = (Boolean) initContextClassLoaderObject; } private void checkForConvenienceForm(AnnotationNode node, boolean exclude) { Object val = node.getMember("value"); if (val == null || !(val instanceof ConstantExpression)) return; Object allParts = ((ConstantExpression)val).getValue(); if (!(allParts instanceof String)) return; String allstr = (String) allParts; // strip off trailing attributes boolean done = false; while (!done) { Matcher attrs = ATTRIBUTES_PATTERN.matcher(allstr); if (attrs.find()) { String attrName = attrs.group(2); String attrValue = attrs.group(3); if (attrName == null || attrValue == null) continue; boolean isBool = GRAB_BOOLEAN.contains(attrName); ConstantExpression value = new ConstantExpression(isBool ? Boolean.valueOf(attrValue) : attrValue); value.setSourcePosition(node); node.addMember(attrName, value); int lastSemi = allstr.lastIndexOf(';'); if (lastSemi == -1) { allstr = ""; break; } allstr = allstr.substring(0, lastSemi); } else { done = true; } } if (allstr.contains("#")) { // see: http://ant.apache.org/ivy/history/latest-milestone/textual.html Matcher m = IVY_PATTERN.matcher(allstr); if (!m.find()) return; if (m.group(1) == null || m.group(2) == null) return; node.addMember("module", new ConstantExpression(m.group(2))); node.addMember("group", new ConstantExpression(m.group(1))); if (m.group(6) != null) node.addMember("conf", new ConstantExpression(m.group(6))); if (m.group(4) != null) node.addMember("version", new ConstantExpression(m.group(4))); else if (!exclude && node.getMember("version") == null) node.addMember("version", new ConstantExpression("*")); node.getMembers().remove("value"); } else if (allstr.contains(":")) { // assume gradle syntax // see: http://www.gradle.org/latest/docs/userguide/dependency_management.html#sec:how_to_declare_your_dependencies String ext = ""; String[] parts; if (allstr.contains("@")) { parts = allstr.split("@"); if (parts.length > 2) return; allstr = parts[0]; ext = parts[1]; } parts = allstr.split(":"); if (parts.length > 4) return; if (parts.length > 3) node.addMember("classifier", new ConstantExpression(parts[3])); if (parts.length > 2) node.addMember("version", new ConstantExpression(parts[2])); else if (!exclude && node.getMember("version") == null) node.addMember("version", new ConstantExpression("*")); if (ext.length() > 0) node.addMember("ext", new ConstantExpression(ext)); node.addMember("module", new ConstantExpression(parts[1])); node.addMember("group", new ConstantExpression(parts[0])); node.getMembers().remove("value"); } } private void extractGrab(Expression init, ConstantExpression ce) { if (ce.getValue() instanceof AnnotationNode) { AnnotationNode annotation = (AnnotationNode) ce.getValue(); if ((init != null) && (annotation.getMember("initClass") != null)) { annotation.setMember("initClass", init); } String name = annotation.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(annotation); } if ((GRABEXCLUDE_CLASS_NAME.equals(name)) || (allowShortGrabExcludes && GRABEXCLUDE_SHORT_NAME.equals(name)) || (grabExcludeAliases.contains(name))) { grabExcludeAnnotations.add(annotation); } if ((GRABCONFIG_CLASS_NAME.equals(name)) || (allowShortGrabConfig && GRABCONFIG_SHORT_NAME.equals(name)) || (grabConfigAliases.contains(name))) { grabConfigAnnotations.add(annotation); } if ((GRABRESOLVER_CLASS_NAME.equals(name)) || (allowShortGrabResolver && GRABRESOLVER_SHORT_NAME.equals(name)) || (grabResolverAliases.contains(name))) { grabResolverAnnotations.add(annotation); } } } /** * Adds the annotation to the internal target list if a match is found. * * @param node the AST node we are processing */ public void visitAnnotations(AnnotatedNode node) { super.visitAnnotations(node); for (AnnotationNode an : node.getAnnotations()) { String name = an.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(an); } if ((GRABEXCLUDE_CLASS_NAME.equals(name)) || (allowShortGrabExcludes && GRABEXCLUDE_SHORT_NAME.equals(name)) || (grabExcludeAliases.contains(name))) { grabExcludeAnnotations.add(an); } if ((GRABCONFIG_CLASS_NAME.equals(name)) || (allowShortGrabConfig && GRABCONFIG_SHORT_NAME.equals(name)) || (grabConfigAliases.contains(name))) { grabConfigAnnotations.add(an); } if ((GRAPES_CLASS_NAME.equals(name)) || (allowShortGrapes && GRAPES_SHORT_NAME.equals(name)) || (grapesAliases.contains(name))) { grapesAnnotations.add(an); } if ((GRABRESOLVER_CLASS_NAME.equals(name)) || (allowShortGrabResolver && GRABRESOLVER_SHORT_NAME.equals(name)) || (grabResolverAliases.contains(name))) { grabResolverAnnotations.add(an); } } } } groovy-1.8.6/src/main/groovy/grape/defaultGrapeConfig.xml0000644001501200150120000000306411707612044023007 0ustar miguelmiguel groovy-1.8.6/src/main/groovy/grape/Grape.java0000644001501200150120000001610111707612044020431 0ustar miguelmiguel/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.grape; import java.util.Collections; import java.util.List; import java.util.Map; import java.net.URI; /** * Facade to GrapeEngine. */ public class Grape { private static boolean enableGrapes = Boolean.valueOf(System.getProperty("groovy.grape.enable", "true")); private static boolean enableAutoDownload = Boolean.valueOf(System.getProperty("groovy.grape.autoDownload", "true")); protected static GrapeEngine instance; /** * This is a static access kill-switch. All of the static shortcut * methods in this class will not work if this property is set to false. *
    * By default it is set to true. */ public static boolean getEnableGrapes() { return enableGrapes; } /** * This is a static access kill-switch. All of the static shortcut * methods in this class will not work if this property is set to false. *
    * By default it is set to true. */ public static void setEnableGrapes(boolean enableGrapes) { Grape.enableGrapes = enableGrapes; } /** * This is a static access auto download enabler. It will set the * 'autoDownload' value to the passed in arguments map if not already * set. If 'autoDownload' is set the value will not be adjusted.

    * * This applies to the grab and resolve calls.

    * * If it is set to false, only previously downloaded grapes * will be used. This may cause failure in the grape call * if the library has not yet been downloaded * * If it is set to true, then any jars not already downloaded will * automatically be downloaded. Also, any versions expressed as a range * will be checked for new versions and downloaded (with dependencies) * if found.

    * * By default it is set to false. */ public static boolean getEnableAutoDownload() { return enableAutoDownload; } /** * This is a static access auto download enabler. It will set the * 'autoDownload' value to the passed in arguments map if not already * set. If 'autoDownload' is set the value will not be adjusted.

    * * This applies to the grab and resolve calls.

    * * If it is set to false, only previously downloaded grapes * will be used. This may cause failure in the grape call * if the library has not yet been downloaded

    * * If it is set to true, then any jars not already downloaded will * automatically be downloaded. Also, any versions expressed as a range * will be checked for new versions and downloaded (with dependencies) * if found.

    * * By default it is set to false. */ public static void setEnableAutoDownload(boolean enableAutoDownload) { Grape.enableAutoDownload = enableAutoDownload; } public static synchronized GrapeEngine getInstance() { if (instance == null) { try { // by default use GrapeIvy //TODO META-INF/services resolver? instance = (GrapeEngine) Class.forName("groovy.grape.GrapeIvy").newInstance(); } catch (InstantiationException e) { //LOGME } catch (IllegalAccessException e) { //LOGME } catch (ClassNotFoundException e) { //LOGME } } return instance; } public static void grab(String endorsed) { if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { instance.grab(endorsed); } } } public static void grab(Map dependency) { if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { if (!dependency.containsKey("autoDownload")) { dependency.put("autoDownload" , enableAutoDownload); } instance.grab(dependency); } } } public static void grab(Map args, Map... dependencies) { if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { if (!args.containsKey("autoDownload")) { args.put("autoDownload" , enableAutoDownload); } instance.grab(args, dependencies); } } } public static Map>> enumerateGrapes() { Map>> grapes = null; if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { grapes = instance.enumerateGrapes(); } } if (grapes == null) { return Collections.emptyMap(); } else { return grapes; } } public static URI[] resolve(Map args, Map... dependencies) { return resolve(args, null, dependencies); } public static URI[] resolve(Map args, List depsInfo, Map... dependencies) { URI[] uris = null; if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { if (!args.containsKey("autoDownload")) { args.put("autoDownload" , enableAutoDownload); } uris = instance.resolve(args, depsInfo, dependencies); } } if (uris == null) { return new URI[0]; } else { return uris; } } public static Map[] listDependencies(ClassLoader cl) { Map[] maps = null; if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { maps = instance.listDependencies(cl); } } if (maps == null) { return new Map[0]; } else { return maps; } } public static void addResolver(Map args) { if (enableGrapes) { GrapeEngine instance = getInstance(); if (instance != null) { instance.addResolver(args); } } } } groovy-1.8.6/src/main/groovy/grape/GrapeEngine.java0000644001501200150120000000230411713766062021566 0ustar miguelmiguel/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.grape; import java.util.List; import java.util.Map; import java.net.URI; /** * @author Danno Ferrin */ public interface GrapeEngine { Object grab(String endorsedModule); Object grab(Map args); Object grab(Map args, Map... dependencies); Map>> enumerateGrapes(); URI[] resolve(Map args, Map... dependencies); URI[] resolve(Map args, List depsInfo, Map... dependencies); Map[] listDependencies(ClassLoader classLoader); void addResolver(Map args); } groovy-1.8.6/src/main/groovy/json/0000755001501200150120000000000011715031256016403 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/json/StringEscapeUtils.java0000644001501200150120000003662111707612044022667 0ustar miguelmiguel/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Locale; /** *

    Escapes and unescapes Strings for * Java, Java Script, HTML, XML, and SQL.

    * *

    #ThreadSafe#

    * * Note that this version is a stripped down version from Commons Lang 2.6 with only necessary methods for * JSON builder * @author Apache Software Foundation * @author Apache Jakarta Turbine * @author Purple Technology * @author Alexander Day Chaffee * @author Antony Riley * @author Helge Tesgaard * @author Sean Brown * @author Gary Gregory * @author Phil Steitz * @author Pete Gieser * @since 2.0 * @version $Id: StringEscapeUtils.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class StringEscapeUtils { /** *

    StringEscapeUtils instances should NOT be constructed in * standard programming.

    * *

    Instead, the class should be used as: *

    StringEscapeUtils.escapeJava("foo");

    * *

    This constructor is public to permit tools that require a JavaBean * instance to operate.

    */ public StringEscapeUtils() { super(); } // Java and JavaScript //-------------------------------------------------------------------------- /** *

    Escapes the characters in a String using Java String rules.

    * *

    Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

    * *

    So a tab becomes the characters '\\' and * 't'.

    * *

    The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

    * *

    Example: *

         * input string: He didn't say, "Stop!"
         * output string: He didn't say, \"Stop!\"
         * 
    *

    * * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJava(String str) { return escapeJavaStyleString(str, false, false); } /** *

    Escapes the characters in a String using Java String rules to * a Writer.

    * *

    A null string input has no effect.

    * * @see #escapeJava(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void escapeJava(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, false, false); } /** *

    Escapes the characters in a String using JavaScript String rules.

    *

    Escapes any values it finds into their JavaScript String form. * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

    * *

    So a tab becomes the characters '\\' and * 't'.

    * *

    The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

    * *

    Example: *

         * input string: He didn't say, "Stop!"
         * output string: He didn\'t say, \"Stop!\"
         * 
    *

    * * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJavaScript(String str) { return escapeJavaStyleString(str, true, true); } /** *

    Escapes the characters in a String using JavaScript String rules * to a Writer.

    * *

    A null string input has no effect.

    * * @see #escapeJavaScript(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer **/ public static void escapeJavaScript(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, true, true); } /** *

    Worker method for the {@link #escapeJavaScript(String)} method.

    * * @param str String to escape values in, may be null * @param escapeSingleQuotes escapes single quotes if true * @param escapeForwardSlash TODO * @return the escaped string */ private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length() * 2); escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new RuntimeException(ioe); } } /** *

    Worker method for the {@link #escapeJavaScript(String)} method.

    * * @param out write to receieve the escaped string * @param str String to escape values in, may be null * @param escapeSingleQuote escapes single quotes if true * @param escapeForwardSlash TODO * @throws IOException if an IOException occurs */ private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote, boolean escapeForwardSlash) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b' : out.write('\\'); out.write('b'); break; case '\n' : out.write('\\'); out.write('n'); break; case '\t' : out.write('\\'); out.write('t'); break; case '\f' : out.write('\\'); out.write('f'); break; case '\r' : out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'' : if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"' : out.write('\\'); out.write('"'); break; case '\\' : out.write('\\'); out.write('\\'); break; case '/' : if (escapeForwardSlash) { out.write('\\'); } out.write('/'); break; default : out.write(ch); break; } } } } /** *

    Returns an upper case hexadecimal String for the given * character.

    * * @param ch The character to convert. * @return An upper case hexadecimal String */ private static String hex(char ch) { return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH); } /** *

    Unescapes any Java literals found in the String. * For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

    * * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input */ public static String unescapeJava(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length()); unescapeJava(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new RuntimeException(ioe); } } /** *

    Unescapes any Java literals found in the String to a * Writer.

    * *

    For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

    * *

    A null string input has no effect.

    * * @param out the Writer used to output unescaped characters * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void unescapeJava(Writer out, String str) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz = str.length(); StringBuilder unicode = new StringBuilder(4); boolean hadSlash = false; boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == 4) { // unicode now contains the four hex digits // which represents our unicode character try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; } catch (NumberFormatException nfe) { throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe); } } continue; } if (hadSlash) { // handle an escaped value hadSlash = false; switch (ch) { case '\\': out.write('\\'); break; case '\'': out.write('\''); break; case '\"': out.write('"'); break; case 'r': out.write('\r'); break; case 'f': out.write('\f'); break; case 't': out.write('\t'); break; case 'n': out.write('\n'); break; case 'b': out.write('\b'); break; case 'u': { // uh-oh, we're in unicode country.... inUnicode = true; break; } default : out.write(ch); break; } continue; } else if (ch == '\\') { hadSlash = true; continue; } out.write(ch); } if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.write('\\'); } } /** *

    Unescapes any JavaScript literals found in the String.

    * *

    For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

    * * @see #unescapeJava(String) * @param str the String to unescape, may be null * @return A new unescaped String, null if null string input */ public static String unescapeJavaScript(String str) { return unescapeJava(str); } /** *

    Unescapes any JavaScript literals found in the String to a * Writer.

    * *

    For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

    * *

    A null string input has no effect.

    * * @see #unescapeJava(Writer,String) * @param out the Writer used to output unescaped characters * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void unescapeJavaScript(Writer out, String str) throws IOException { unescapeJava(out, str); } }groovy-1.8.6/src/main/groovy/json/JsonToken.java0000644001501200150120000001104011707612044021155 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; import java.math.BigDecimal; import java.math.BigInteger; import static groovy.json.JsonTokenType.*; /** * A JSON token, with a type, line / column information, and the text of that token. * * @author Guillaume Laforge * @since 1.8.0 */ public class JsonToken { private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger MAX_INTEGER = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger MIN_INTEGER = BigInteger.valueOf(Integer.MIN_VALUE); private static final BigDecimal MAX_DOUBLE = new BigDecimal(String.valueOf(Double.MAX_VALUE)); private static final BigDecimal MIN_DOUBLE = MAX_DOUBLE.negate(); private static final BigDecimal MAX_FLOAT = new BigDecimal(String.valueOf(Float.MAX_VALUE)); private static final BigDecimal MIN_FLOAT = MAX_FLOAT.negate(); /** Start line position */ private long startLine; /** End line position */ private long endLine; /** Start column position */ private long startColumn; /** End column position */ private long endColumn; /** The type of the token */ private JsonTokenType type; /** The text of that token */ private String text; /** * Return the value represented by this token (ie. a number, a string, a boolean or null). * For numbers, the most appropriate type is returned (Float, Double, BigDecimal for decimal numbers, * and Integer, Long and BigInteger for integral numbers). * * @return the represented value */ public Object getValue() { if (type == STRING) { if (text.length() == 2) { return ""; } else { return text.substring(1, text.length() - 1); } } else if (type == NUMBER) { if (text.contains(".") || text.contains("e") || text.contains("E")) { // a decimal number return new BigDecimal(text); } else { // an integer number BigInteger v = new BigInteger(text); if(v.compareTo(MAX_INTEGER) <= 0 && v.compareTo(MIN_INTEGER) >= 0 ) { return v.intValue(); } else if (v.compareTo(MAX_LONG) <= 0 && v.compareTo(MIN_LONG) >= 0 ) { return v.longValue(); } else { return v; } } } else if (type == TRUE) { return true; } else if (type == FALSE) { return false; } else if (type == NULL) { return null; } else { throw new JsonException( "No appropriate value represented by '" + text + "' on line: " + startLine + ", column: " + startColumn ); } } public String toString() { return text + " (" + type + ") [" + startLine + ":" + startColumn + "-" + endLine + ":" + endColumn + "]"; } public long getStartLine() { return startLine; } public void setStartLine(long startLine) { this.startLine = startLine; } public long getEndLine() { return endLine; } public void setEndLine(long endLine) { this.endLine = endLine; } public long getStartColumn() { return startColumn; } public void setStartColumn(long startColumn) { this.startColumn = startColumn; } public long getEndColumn() { return endColumn; } public void setEndColumn(long endColumn) { this.endColumn = endColumn; } public JsonTokenType getType() { return this.type; } public void setType(JsonTokenType type) { this.type = type; } public void setText(String text) { this.text = text; } public String getText() { return this.text; } } groovy-1.8.6/src/main/groovy/json/JsonException.java0000644001501200150120000000227711707612044022047 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; /** * JsonException is the exception thrown by the JSON builder and slurper classes, * whenever a problem occurs when creating or parsing JSON data structures. * * @author Guillaume Laforge * @since 1.8.0 */ public class JsonException extends RuntimeException { public JsonException() { super(); } public JsonException(String s) { super(s); } public JsonException(String s, Throwable throwable) { super(s, throwable); } public JsonException(Throwable throwable) { super(throwable); } } groovy-1.8.6/src/main/groovy/json/JsonLexer.java0000644001501200150120000002174411715031256021167 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; import static groovy.json.JsonTokenType.*; import groovy.io.LineColumnReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The lexer reads JSON tokens in a streaming fashion from the underlying reader. * * @author Guillaume Laforge * @since 1.8.0 */ public class JsonLexer implements Iterator { private static final char SPACE = ' '; private static final char DOT = '.'; private static final char MINUS = '-'; private static final char PLUS = '+'; private static final char LOWER_E = 'e'; private static final char UPPER_E = 'E'; private static final char ZERO = '0'; private static final char NINE = '9'; private static final Pattern p = Pattern.compile("\\\\u(\\p{XDigit}{4})"); private LineColumnReader reader; /** * Underlying reader from which to read the JSON tokens. * This reader is an instance of LineColumnReader, * to keep track of line and column positions. */ public LineColumnReader getReader() { return reader; } private JsonToken currentToken = null; /** * Instanciates a lexer with a reader from which to read JSON tokens. * Under the hood, the reader is wrapped in a LineColumnReader, * for line and column information, unless it's already an instance of that class. * * @param reader underlying reader */ public JsonLexer(Reader reader) { this.reader = reader instanceof LineColumnReader ? (LineColumnReader)reader : new LineColumnReader(reader); } /** * @return the next token from the stream */ public JsonToken nextToken() { try { int firstIntRead = skipWhitespace(); if (firstIntRead == -1) return null; char firstChar = (char) firstIntRead; JsonTokenType possibleTokenType = startingWith((char) firstIntRead); if (possibleTokenType == null) { throw new JsonException( "Lexing failed on line: " + reader.getLine() + ", column: " + reader.getColumn() + ", while reading '" + firstChar + "', " + "no possible valid JSON value or punctuation could be recognized." ); } reader.reset(); long startLine = reader.getLine(); long startColumn = reader.getColumn(); JsonToken token = new JsonToken(); token.setStartLine(startLine); token.setStartColumn(startColumn); token.setEndLine(startLine); token.setEndColumn(startColumn + 1); token.setType(possibleTokenType); token.setText("" + firstChar); if (possibleTokenType.ordinal() >= OPEN_CURLY.ordinal() && possibleTokenType.ordinal() <= FALSE.ordinal()) { return readingConstant(possibleTokenType, token); } else if (possibleTokenType == STRING) { StringBuilder currentContent = new StringBuilder("\""); // consume the first double quote starting the string reader.read(); boolean isEscaped = false; for (;;) { int read = reader.read(); if (read == -1) return null; isEscaped = (!isEscaped && currentContent.charAt(currentContent.length() - 1) == '\\'); char charRead = (char) read; currentContent.append(charRead); if (charRead == '"' && !isEscaped && possibleTokenType.matching(currentContent.toString())) { token.setEndLine(reader.getLine()); token.setEndColumn(reader.getColumn()); token.setText(unescape(currentContent.toString())); return token; } } } else if (possibleTokenType == NUMBER) { StringBuilder currentContent = new StringBuilder(); for (;;) { reader.mark(1); int read = reader.read(); if (read == -1) return null; char lastCharRead = (char) read; if (lastCharRead >= ZERO && lastCharRead <= NINE || lastCharRead == DOT || lastCharRead == MINUS || lastCharRead == PLUS || lastCharRead == LOWER_E || lastCharRead == UPPER_E) { currentContent.append(lastCharRead); } else { reader.reset(); break; } } String content = currentContent.toString(); if (possibleTokenType.matching(content)) { token.setEndLine(reader.getLine()); token.setEndColumn(reader.getColumn()); token.setText(currentContent.toString()); return token; } else { throwJsonException(currentContent.toString(), possibleTokenType); } } return null; } catch (IOException ioe) { throw new JsonException("An IO exception occurred while reading the JSON payload", ioe); } } private void throwJsonException(String content, JsonTokenType type) { throw new JsonException( "Lexing failed on line: " + reader.getLine() + ", column: " + reader.getColumn() + ", while reading '" + content + "', " + "was trying to match " + type.getLabel() ); } /** * Replace unicode escape and other control characters with real characters * * @param input text * @return input text without the escaping */ public static String unescape(String input) { return StringEscapeUtils.unescapeJavaScript(input); } /** * When a constant token type is expected, check that the expected constant is read, * and update the content of the token accordingly. * * @param type the token type * @param token the token * @return the token updated with end column and text updated */ private JsonToken readingConstant(JsonTokenType type, JsonToken token) { try { int numCharsToRead = ((String)type.getValidator()).length(); char[] chars = new char[numCharsToRead]; reader.read(chars); String stringRead = new String(chars); if (stringRead.equals(type.getValidator())) { token.setEndColumn(token.getStartColumn() + numCharsToRead); token.setText(stringRead); return token; } else { throwJsonException(stringRead, type); } } catch (IOException ioe) { throw new JsonException("An IO exception occurred while reading the JSON payload", ioe); } return null; } /** * Skips all the whitespace characters and moves the cursor to the next non-space character. */ public int skipWhitespace() { try { int readChar = 20; char c = SPACE; while(Character.isWhitespace(c)) { reader.mark(1); readChar = reader.read(); c = (char)readChar; } reader.reset(); return readChar; } catch (IOException ioe) { throw new JsonException("An IO exception occurred while reading the JSON payload", ioe); } } /** * Iterator method to know if another token follows, * or if we've reached the end of the stream. * * @return true if there are more tokens */ public boolean hasNext() { currentToken = nextToken(); return currentToken != null; } /** * Iterator method to get the next token of the stream. * * @return the next token */ public JsonToken next() { return currentToken; } /** * Method not implemented. * * @throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException("The method remove() is not supported on this lexer."); } } groovy-1.8.6/src/main/groovy/json/StreamingJsonBuilder.groovy0000644001501200150120000002262411707612044023753 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json /** * A builder for creating JSON payloads. *

    * This builder supports the usual builder syntax made of nested method calls and closures, * but also some specific aspects of JSON data structures, such as list of values, etc. * Please make sure to have a look at the various methods provided by this builder * to be able to learn about the various possibilities of usage. *

    * Unlike the JsonBuilder class which creates a data structure in memory, * which is handy in those situations where you want to alter the structure programmatically before output, * the StreamingJsonBuilder streams to a writter directly without any memory data structure. * So if you don't need to modify the structure, and want a more memory-efficient approach, * please use the StreamingJsonBuilder. *

    * Example: *

     *     new StringWriter().with { w ->
     *         def builder = new groovy.json.StreamingJsonBuilder( w )
     *         builder.people {
     *             person {
     *                 firstName 'Tim'
     *                 lastName 'Yates'
     *                 // Named arguments are valid values for objects too
     *                 address(
     *                     city: 'Manchester',
     *                     country: 'UK',
     *                     zip: 'M1 2AB',
     *                 )
     *                 living true
     *                 eyes 'left', 'right'
     *             }
     *         }
     *
     *         assert w.toString() == '{"people":{"person":{"firstName":"Tim","lastName":"Yates","address":{"city":"Manchester","country":"UK","zip":"M1 2AB"},"living":true,"eyes":["left","right"]}}}'
     *    }
     * 
    * * @author Tim Yates * @since 1.8.1 */ class StreamingJsonBuilder { Writer writer /** * Instantiates a JSON builder, possibly with some existing data structure. * * @param writer A writer to which Json will be written * @param content a pre-existing data structure, default to null */ StreamingJsonBuilder( Writer writer, content = null) { this.writer = writer if( content ) writer.write( JsonOutput.toJson( content ) ) } /** * Named arguments can be passed to the JSON builder instance to create a root JSON object *

    * Example: *

         * new StringWriter().with { w ->
         *   def json = new groovy.json.StreamingJsonBuilder( w )
         *   json name: "Tim", age: 31
         *
         *   assert w.toString() == '{"name":"Tim","age":31}'
         * }
         * 
    * * @param m a map of key / value pairs * @return a map of key / value pairs */ def call(Map m) { writer.write JsonOutput.toJson( m ) return m } /** * A list of elements as arguments to the JSON builder creates a root JSON array *

    * Example: *

         * new StringWriter().with { w ->
         *   def json = new groovy.json.StreamingJsonBuilder( w )
         *   def result = json([1, 2, 3])
         *
         *   assert result == [ 1, 2, 3 ]
         *   assert w.toString() == "[1,2,3]"
         * }
         * 
    * * @param l a list of values * @return a list of values */ def call(List l) { writer.write( JsonOutput.toJson( l ) ) return l } /** * Varargs elements as arguments to the JSON builder create a root JSON array *

    * Example: *

         * new StringWriter().with { w ->
         *   def json = new groovy.json.StreamingJsonBuilder( w )
         *   def result = json 1, 2, 3
         *
         *   assert result instanceof List
         *   assert w.toString() == "[1,2,3]"
         * }
         * 
    * @param args an array of values * @return a list of values */ def call(Object... args) { def l = args.toList() writer.write JsonOutput.toJson( l ) return l } /** * A closure passed to a JSON builder will create a root JSON object *

    * Example: *

         * new StringWriter().with { w ->
         *   def json = new groovy.json.StreamingJsonBuilder( w )
         *   json {
         *      name "Tim"
         *      age 39
         *   }
         *
         *   assert w.toString() == '{"name":"Tim","age":39}'
         * }
         * 
    * * @param c a closure whose method call statements represent key / values of a JSON object */ def call(Closure c) { writer.write( '{' ) StreamingJsonDelegate.cloneDelegateAndGetContent( writer, c ) writer.write( '}' ) } /** * A method call on the JSON builder instance will create a root object with only one key * whose name is the name of the method being called. * This method takes as arguments: *
      *
    • a closure
    • *
    • a map (ie. named arguments)
    • *
    • a map and a closure
    • *
    • or no argument at all
    • *
    *

    * Example with a classicala builder-style: *

         * new StringWriter().with { w ->
         *     def json = new groovy.json.StreamingJsonBuilder( w )
         *     json.person {
         *         name "Tim"
         *          age 28
         *     }
         *
         *     assert w.toString() == '{"person":{"name":"Tim","age":28}}'
         * }
         * 
    * * Or alternatively with a method call taking named arguments: *
         * new StringWriter().with { w ->
         *     def json = new groovy.json.StreamingJsonBuilder( w )
         *     json.person name: "Tim", age: 32
         *
         *     assert w.toString() == '{"person":{"name":"Tim","age":32}}'
         * }
         * 
    * * If you use named arguments and a closure as last argument, * the key/value pairs of the map (as named arguments) * and the key/value pairs represented in the closure * will be merged together — * the closure properties overriding the map key/values * in case the same key is used. *
         * new StringWriter().with { w ->
         *     def json = new groovy.json.StreamingJsonBuilder( w )
         *     json.person(name: "Tim", age: 35) { town "Manchester" }
         *
         *     assert w.toString() == '{"person":{"name":"Tim","age":35,"town":"Manchester"}}'
         * }
         * 
    * * The empty args call will create a key whose value will be an empty JSON object: *
         * new StringWriter().with { w ->
         *     def json = new groovy.json.StreamingJsonBuilder( w )
         *     json.person()
         *
         *     assert w.toString() == '{"person":{}}'
         * }
         * 
    * * @param name the single key * @param args the value associated with the key */ def invokeMethod(String name, Object args) { if (args?.size() == 0) { writer.write JsonOutput.toJson( [(name): [:]] ) } else if (args?.size() == 1) { if (args[0] instanceof Closure) { writer.write "{${JsonOutput.toJson( name )}:" this.call( args[0] ) writer.write '}' } else if (args[0] instanceof Map) { writer.write JsonOutput.toJson( [(name): args[0]] ) } else { throw new JsonException("Expected no arguments, a single map, a single closure, or a map and closure as arguments.") } } else if (args?.size() == 2 && args[0] instanceof Map && args[1] instanceof Closure) { writer.write "{${JsonOutput.toJson( name )}:{" args[0].eachWithIndex { it, idx -> if( idx > 0 ) writer.write ',' writer.write JsonOutput.toJson( it.key ) writer.write ':' writer.write JsonOutput.toJson( it.value ) } StreamingJsonDelegate.cloneDelegateAndGetContent( writer, args[1], !args[0].size() ) writer.write '}}' } else { throw new JsonException("Expected no arguments, a single map, a single closure, or a map and closure as arguments.") } } } class StreamingJsonDelegate { Writer writer boolean first StreamingJsonDelegate( Writer w, boolean first ) { this.writer = w this.first = first } def invokeMethod(String name, Object args) { if (args) { if( !first ) { writer.write ',' } writer.write JsonOutput.toJson( name ) writer.write ':' writer.write JsonOutput.toJson( args.size() == 1 ? args[0] : args.toList() ) first = false } } static cloneDelegateAndGetContent(Writer w, Closure c, boolean first=true ) { def delegate = new StreamingJsonDelegate( w, first ) Closure cloned = c.clone() cloned.delegate = delegate cloned.resolveStrategy = Closure.DELEGATE_FIRST cloned() } } groovy-1.8.6/src/main/groovy/json/JsonDelegate.groovy0000644001501200150120000000313711707612044022223 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json /** * Utility class used as delegate of closures representing JSON objects. * * @author Guillaume Laforge * @since 1.8.0 */ class JsonDelegate { def content = [:] /** * Intercepts calls for setting a key and value for a JSON object * * @param name the key name * @param args the value associated with the key */ def invokeMethod(String name, Object args) { if (args) { content[name] = args.size() == 1 ? args[0] : args.toList() } } /** * Factory method for creating JsonDelegates from closures. * * @param c closure representing JSON objects * @return an instance of JsonDelegate */ static cloneDelegateAndGetContent(Closure c) { def delegate = new JsonDelegate() Closure cloned = c.clone() cloned.delegate = delegate cloned.resolveStrategy = Closure.DELEGATE_FIRST cloned() return delegate.content } } groovy-1.8.6/src/main/groovy/json/JsonBuilder.groovy0000644001501200150120000002121411707612044022073 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json /** * A builder for creating JSON payloads. *

    * This builder supports the usual builder syntax made of nested method calls and closures, * but also some specific aspects of JSON data structures, such as list of values, etc. * Please make sure to have a look at the various methods provided by this builder * to be able to learn about the various possibilities of usage. *

    * Example: *

    
     *       def builder = new groovy.json.JsonBuilder()
     *       def root = builder.people {
     *           person {
     *               firstName 'Guillame'
     *               lastName 'Laforge'
     *               // Named arguments are valid values for objects too
     *               address(
     *                       city: 'Paris',
     *                       country: 'France',
     *                       zip: 12345,
     *               )
     *               married true
     *               // a list of values
     *               conferences 'JavaOne', 'Gr8conf'
     *           }
     *       }
     *
     *       // creates a data structure made of maps (Json object) and lists (Json array)
     *       assert root instanceof Map
     *
     *       assert builder.toString() == '{"people":{"person":{"firstName":"Guillame","lastName":"Laforge","address":{"city":"Paris","country":"France","zip":12345},"married":true,"conferences":["JavaOne","Gr8conf"]}}}'
     * 
    * * @author Guillaume Laforge * @since 1.8.0 */ class JsonBuilder implements Writable { /** * Resulting data structure made of lists and maps, representing a JSON payload */ def content /** * Instanciates a JSON builder, possibly with some existing data structure. * * @param content a pre-existing data structure, default to null */ JsonBuilder(content = null) { this.content = content } /** * Named arguments can be passed to the JSON builder instance to create a root JSON object *

    * Example: *

    
         * def json = new JsonBuilder()
         * json name: "Guillaume", age: 33
         *
         * assert json.toString() == '{"name":"Guillaume","age":33}'
         * 
    * * @param m a map of key / value pairs * @return a map of key / value pairs */ def call(Map m) { this.content = m return content } /** * A list of elements as arguments to the JSON builder creates a root JSON array *

    * Example: *

    
         * def json = new JsonBuilder()
         * def result = json([1, 2, 3])
         *
         * assert result instanceof List
         * assert json.toString() == "[1,2,3]"
         * 
    * * @param l a list of values * @return a list of values */ def call(List l) { this.content = l return content } /** * Varargs elements as arguments to the JSON builder create a root JSON array *

    * Example: *

    
         * def json = new JsonBuilder()
         * def result = json 1, 2, 3
         *
         * assert result instanceof List
         * assert json.toString() == "[1,2,3]"
         * 
    * @param args an array of values * @return a list of values */ def call(Object... args) { this.content = args.toList() return this.content } /** * A closure passed to a JSON builder will create a root JSON object *

    * Example: *

    
         * def json = new JsonBuilder()
         * def result = json {
         *      name "Guillaume"
         *      age 33
         * }
         *
         * assert result instanceof Map
         * assert json.toString() == '{"name":"Guillaume","age":33}'
         * 
    * * @param c a closure whose method call statements represent key / values of a JSON object * @return a map of key / value pairs */ def call(Closure c) { this.content = JsonDelegate.cloneDelegateAndGetContent(c) return content } /** * A method call on the JSON builder instance will create a root object with only one key * whose name is the name of the method being called. * This method takes as arguments: *
      *
    • a closure
    • *
    • a map (ie. named arguments)
    • *
    • a map and a closure
    • *
    • or no argument at all
    • *
    *

    * Example with a classicala builder-style: *

    
         * def json = new JsonBuilder()
         * def result = json.person {
         *      name "Guillaume"
         *      age 33
         * }
         *
         * assert result instanceof Map
         * assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
         * 
    * * Or alternatively with a method call taking named arguments: *
    
         * def json = new JsonBuilder()
         * json.person name: "Guillaume", age: 33
         *
         * assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
         * 
    * * If you use named arguments and a closure as last argument, * the key/value pairs of the map (as named arguments) * and the key/value pairs represented in the closure * will be merged together — * the closure properties overriding the map key/values * in case the same key is used. *
    
         * def json = new JsonBuilder()
         * json.person(name: "Guillaume", age: 33) { town "Paris" }
         *
         * assert json.toString() == '{"person":{"name":"Guillaume","age":33,"town":"Paris"}}'
         * 
    * * The empty args call will create a key whose value will be an empty JSON object: *
    
         * def json = new JsonBuilder()
         * json.person()
         *
         * assert json.toString() == '{"person":{}}'
         * 
    * * @param name the single key * @param args the value associated with the key * @return a map with a single key */ def invokeMethod(String name, Object args) { if (args?.size() == 0) { this.content = [(name): [:]] return content } else if (args?.size() == 1) { if (args[0] instanceof Closure) { this.content = [(name): JsonDelegate.cloneDelegateAndGetContent(args[0])] return content } else if (args[0] instanceof Map) { this.content = [(name): args[0]] return content } } else if (args?.size() == 2 && args[0] instanceof Map && args[1] instanceof Closure) { this.content = [(name): [*:args[0], *:JsonDelegate.cloneDelegateAndGetContent(args[1])]] return content } throw new JsonException("Expected no arguments, a single map, a single closure, or a map and closure as arguments.") } /** * Serializes the internal data structure built with the builder to a conformant JSON payload string *

    * Example: *

    
         * def json = new JsonBuilder()
         * json { temperature 37 }
         * 
         * assert json.toString() == '{"temperature":37}'
         * 
    * * @return a JSON output */ String toString() { JsonOutput.toJson(content) } /** * Pretty-prints and formats the JSON payload. *

    * This method calls the JsonLexer to parser the output of the builder, * so this may not be an optimal method to call, * and should be used mainly for debugging purpose * for a human-readable output of the JSON content. * * @return a pretty printed JSON output */ String toPrettyString() { JsonOutput.prettyPrint(toString()) } /** * The JSON builder implements the Writable interface, * so that you can have the builder serialize itself the JSON payload to a writer. *

    * Example: *

    
         * def json = new JsonBuilder()
         * json { temperature 37 }
         *
         * def out = new StringWriter()
         * out << json
         *
         * assert out.toString() == '{"temperature":37}' 
         * 
    * * @param out a writer on which to serialize the JSON payload * @return the writer */ Writer writeTo(Writer out) { out << toString() } }groovy-1.8.6/src/main/groovy/json/JsonOutput.groovy0000644001501200150120000001345511707612074022020 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json import static JsonTokenType.* import java.text.SimpleDateFormat import java.text.DateFormat /** * Class responsible for the actual String serialization of the possible values of a JSON structure. * This class can also be used as a category, so as to add toJson() methods to various types. * * @author Guillaume Laforge * @author Roshan Dawrani * @since 1.8.0 */ class JsonOutput { /** * Date formatter for outputting dates to a string * that can be parsed back from JavaScript with: * Date.parse(stringRepresentation) */ private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US) static { dateFormat.timeZone = TimeZone.getTimeZone('GMT') } /** * @return "true" or "false" for a boolean value */ static String toJson(Boolean bool) { bool.toString() } /** * @return a string representation for a number * @throws JsonException if the number is infinite or not a number. */ static String toJson(Number n) { if (n.class in [Double, Float] && (n.isInfinite() || n.isNaN())) { throw new JsonException("Number ${n} can't be serialized as JSON: infinite or NaN are not allowed in JSON.") } n.toString() } /** * @return a JSON string representation of the character */ static String toJson(Character c) { "\"$c\"" } /** * @return a properly encoded string with escape sequences */ static String toJson(String s) { "\"${StringEscapeUtils.escapeJava(s)}\"" } /** * Format a date that is parseable from JavaScript, according to ISO-8601. * * @param date the date to format to a JSON string * @return a formatted date in the form of a string */ static String toJson(Date date) { "\"${dateFormat.format(date)}\"" } /** * Format a calendar instance that is parseable from JavaScript, according to ISO-8601. * * @param cal the calendar to format to a JSON string * @return a formatted date in the form of a string */ static String toJson(Calendar cal) { "\"${dateFormat.format(cal.time)}\"" } /** * @return the string representation of an uuid */ static String toJson(UUID uuid) { "\"${uuid.toString()}\"" } /** * @return the string representation of the URL */ static String toJson(URL url) { "\"${url.toString()}\"" } /** * @return an object representation of a closure */ static String toJson(Closure closure) { toJson(JsonDelegate.cloneDelegateAndGetContent(closure)) } /** * @return "null" for a null value, or a JSON array representation for a collection, array, iterator or enumeration. */ static String toJson(object) { if (object == null) { "null" } else if (object instanceof Collection || object.class.isArray() || object instanceof Iterator || object instanceof Enumeration) { "[" + object.collect { toJson(it) }.join(',') + "]" } else if (object instanceof Enum) { '"' + object.name() + '"' } else { def properties = object.properties properties.remove('class') properties.remove('declaringClass') properties.remove('metaClass') toJson(properties) } } /** * @return a JSON object representation for a map */ static String toJson(Map m) { "{" + m.collect { k, v -> if (k == null) { throw new IllegalArgumentException('Null key for a Map not allowed') } toJson(k.toString()) + ':' + toJson(v) }.join(',') + "}" } /** * Pretty print a JSON payload * * @param jsonPayload * @return */ static String prettyPrint(String jsonPayload) { int indent = 0 def output = new StringBuilder() def lexer = new JsonLexer(new StringReader(jsonPayload)) while (lexer.hasNext()) { JsonToken token = lexer.next() if (token.type == OPEN_CURLY) { indent += 4 output.append('{\n') output.append(' ' * indent) } else if (token.type == CLOSE_CURLY) { indent -= 4 output.append('\n') output.append(' ' * indent) output.append('}') } else if(token.type == OPEN_BRACKET) { indent += 4 output.append('[\n') output.append(' ' * indent) } else if(token.type == CLOSE_BRACKET) { indent -= 4 output.append('\n') output.append(' ' * indent) output.append(']') } else if (token.type == COMMA) { output.append(',\n') output.append(' ' * indent) } else if (token.type == COLON) { output.append(': ') } else { output.append(token.text) } } return output.toString() } } groovy-1.8.6/src/main/groovy/json/JsonSlurper.java0000644001501200150120000002415611707612044021545 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; import static groovy.json.JsonTokenType.*; import groovy.io.LineColumnReader; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * JSON slurper which parses text or reader content into a data structure of lists and maps. *

    * Example usage: *

     * def slurper = new JsonSlurper()
     * def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
     *
     * assert result.person.name == "Guillaume"
     * assert result.person.age == 33
     * assert result.person.pets.size() == 2
     * assert result.person.pets[0] == "dog"
     * assert result.person.pets[1] == "cat"
     * 
    * * @author Guillaume Laforge * @since 1.8.0 */ public class JsonSlurper { /** * Parse a text representation of a JSON data structure * * @param text JSON text to parse * @return a data structure of lists and maps */ public Object parseText(String text) { if (text == null || text.length() == 0) { throw new IllegalArgumentException("The JSON input text should neither be null nor empty."); } return parse(new LineColumnReader(new StringReader(text))); } /** * Parse a JSON data structure from content from a reader * * @param reader reader over a JSON content * @return a data structure of lists and maps */ public Object parse(Reader reader) { Object content; JsonLexer lexer = new JsonLexer(reader); JsonToken token = lexer.nextToken(); if (token.getType() == OPEN_CURLY) { content = parseObject(lexer); } else if (token.getType() == OPEN_BRACKET) { content = parseArray(lexer); } else { throw new JsonException( "A JSON payload should start with " + OPEN_CURLY.getLabel() + " or " + OPEN_BRACKET.getLabel() + ".\n" + "Instead, '" + token.getText() + "' was found " + "on line: " + token.getStartLine() + ", " + "column: " + token.getStartColumn() ); } return content; } /** * Parse an array from the lexer * * @param lexer the lexer * @return a list of JSON values */ private List parseArray(JsonLexer lexer) { List content = new ArrayList(); JsonToken currentToken; for(;;) { currentToken = lexer.nextToken(); if (currentToken == null) { throw new JsonException( "Expected a value on line: " + lexer.getReader().getLine() + ", " + "column: " + lexer.getReader().getColumn() + ".\n" + "But got an unterminated array." ); } if (currentToken.getType() == OPEN_CURLY) { content.add(parseObject(lexer)); } else if (currentToken.getType() == OPEN_BRACKET) { content.add(parseArray(lexer)); } else if (currentToken.getType().ordinal() >= NULL.ordinal()) { content.add(currentToken.getValue()); } else if (currentToken.getType() == CLOSE_BRACKET) { return content; } else { throw new JsonException( "Expected a value, an array, or an object " + "on line: " + currentToken.getStartLine() + ", " + "column: " + currentToken.getStartColumn() + ".\n" + "But got '" + currentToken.getText() + "' instead." ); } currentToken = lexer.nextToken(); if (currentToken == null) { throw new JsonException( "Expected " + CLOSE_BRACKET.getLabel() + " " + "or " + COMMA.getLabel() + " " + "on line: " + lexer.getReader().getLine() + ", " + "column: " + lexer.getReader().getColumn() + ".\n" + "But got an unterminated array." ); } // Expect a comma for an upcoming value // or a closing bracket for the end of the array if (currentToken.getType() == CLOSE_BRACKET) { break; } else if (currentToken.getType() != COMMA) { throw new JsonException( "Expected a value or " + CLOSE_BRACKET.getLabel() + " " + "on line: " + currentToken.getStartLine() + " " + "column: " + currentToken.getStartColumn() + ".\n" + "But got '" + currentToken.getText() + "' instead." ); } } return content; } /** * Parses an object from the lexer * * @param lexer the lexer * @return a Map representing a JSON object */ private Map parseObject(JsonLexer lexer) { Map content = new HashMap(); JsonToken previousToken = null; JsonToken currentToken = null; for(;;) { currentToken = lexer.nextToken(); if (currentToken == null) { throw new JsonException( "Expected a String key on line: " + lexer.getReader().getLine() + ", " + "column: " + lexer.getReader().getColumn() + ".\n" + "But got an unterminated object." ); } // expect a string key, or already a closing curly brace if (currentToken.getType() == CLOSE_CURLY) { return content; } else if (currentToken.getType() != STRING) { throw new JsonException( "Expected " + STRING.getLabel() + " key " + "on line: " + currentToken.getStartLine() + ", " + "column: " + currentToken.getStartColumn() + ".\n" + "Bug got '" + currentToken.getText() + "' instead." ); } String mapKey = (String) currentToken.getValue(); currentToken = lexer.nextToken(); if (currentToken == null) { throw new JsonException( "Expected a " + COLON.getLabel() + " " + "on line: " + lexer.getReader().getLine() + ", " + "column: " + lexer.getReader().getColumn() + ".\n" + "But got an unterminated object." ); } // expect a colon between the key and value pair if (currentToken.getType() != COLON) { throw new JsonException( "Expected " + COLON.getLabel() + " " + "on line: " + currentToken.getStartLine() + ", " + "column: " + currentToken.getStartColumn() + ".\n" + "Bug got '" + currentToken.getText() + "' instead." ); } currentToken = lexer.nextToken(); if (currentToken == null) { throw new JsonException( "Expected a value " + "on line: " + lexer.getReader().getLine() + ", " + "column: " + lexer.getReader().getColumn() + ".\n" + "But got an unterminated object." ); } // value can be an object, an array, a number, string, boolean or null values if (currentToken.getType() == OPEN_CURLY) { content.put(mapKey, parseObject(lexer)); } else if (currentToken.getType() == OPEN_BRACKET) { content.put(mapKey, parseArray(lexer)); } else if (currentToken.getType().ordinal() >= NULL.ordinal()) { content.put(mapKey, currentToken.getValue()); } else { throw new JsonException( "Expected a value, an array, or an object " + "on line: " + currentToken.getStartLine() + ", " + "column: " + currentToken.getStartColumn() + ".\n" + "But got '" + currentToken.getText() + "' instead." ); } previousToken = currentToken; currentToken = lexer.nextToken(); // premature end of the object if (currentToken == null) { throw new JsonException( "Expected " + CLOSE_CURLY.getLabel() + " or " + COMMA.getLabel() + " " + "on line: " + previousToken.getEndLine() + ", " + "column: " + previousToken.getEndColumn() + ".\n" + "But got an unterminated object." ); } // Expect a comma for an upcoming key/value pair // or a closing curly brace for the end of the object if (currentToken.getType() == CLOSE_CURLY) { break; } else if (currentToken.getType() != COMMA) { throw new JsonException( "Expected a value or " + CLOSE_CURLY.getLabel() + " " + "on line: " + currentToken.getStartLine() + ", " + "column: " + currentToken.getStartColumn() + ".\n" + "But got '" + currentToken.getText() + "' instead." ); } } return content; } } groovy-1.8.6/src/main/groovy/json/JsonTokenType.java0000644001501200150120000001020111707612044022015 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.json; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Enum listing all the possible JSON tokens that should be recognized by the lexer. * * @author Guillaume Laforge * @since 1.8.0 */ public enum JsonTokenType { OPEN_CURLY ( "an openning curly brace '{'", "{" ), CLOSE_CURLY ( "a closing curly brace '}'", "}" ), OPEN_BRACKET ( "an openning square bracket '['", "[" ), CLOSE_BRACKET ( "a closing square bracket ']'", "]" ), COLON ( "a colon ':'", ":" ), COMMA ( "a comma ','", "," ), NULL ( "the constant 'null'", "null" ), TRUE ( "the constant 'true'", "true" ), FALSE ( "the constant 'false'", "false" ), NUMBER ( "a number", Pattern.compile("-?\\d+(\\.\\d+)?((e|E)(\\+|-)?\\d+)?")), STRING ( "a string", Pattern.compile("\"([^\"\\\\]*|\\\\[\"\\\\bfnrt\\/]|\\\\u[0-9a-fA-F]{4})*\"", Pattern.DOTALL)); /** * A String constant or a Pattern, serving as a validator for matching tokens. */ private Object validator; /** * A label describing the token */ private String label; /** * Construct a token type with a label and a validator * * @param label a label describing the token * @param validator a String or Pattern validating input strings as valid tokens */ JsonTokenType(String label, Object validator) { this.validator = validator; this.label = label; } /** * Tells if an input string matches a token. * * @param input the input string to match * * @return a Matching enum value: * YES if this is an exact match, * POSSIBLE if more characters could turn the input string into a valid token, * or NO if the string cannot possibly match the pattern even with more characters to read. */ public boolean matching(String input) { if (validator instanceof Pattern) { Matcher matcher = ((Pattern)validator).matcher(input); return matcher.matches(); } else if (validator instanceof String) { return input.equals(validator); } else { return false; } } /** * Find which JSON value might be starting with a given character * * @param c the character * @return the possible token type found */ public static JsonTokenType startingWith(char c) { switch (c) { case '{': return OPEN_CURLY; case '}': return CLOSE_CURLY; case '[': return OPEN_BRACKET; case ']': return CLOSE_BRACKET; case ',': return COMMA; case ':': return COLON; case 't': return TRUE; case 'f': return FALSE; case 'n': return NULL; case '"': return STRING; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return NUMBER; } return null; } public String getLabel() { return label; } public Object getValidator() { return validator; } } groovy-1.8.6/src/main/groovy/time/0000755001501200150120000000000011714271434016373 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/time/BaseDuration.java0000644001501200150120000000760311714271434021624 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.ArrayList; /** * Base class for date and time durations. * @see Duration * @author John Wilson tug@wilson.co.uk */ public abstract class BaseDuration implements Comparable { protected final int years; protected final int months; protected final int days; protected final int hours; protected final int minutes; protected final int seconds; protected final int millis; protected BaseDuration(final int years, final int months, final int days, final int hours, final int minutes, final int seconds, final int millis) { this.years = years; this.months = months; this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.millis = millis; } protected BaseDuration(final int days, final int hours, final int minutes, final int seconds, final int millis) { this(0, 0, days, hours, minutes, seconds, millis); } public int getYears() { return this.years; } public int getMonths() { return this.months; } public int getDays() { return this.days; } public int getHours() { return this.hours; } public int getMinutes() { return this.minutes; } public int getSeconds() { return this.seconds; } public int getMillis() { return this.millis; } public Date plus(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, this.years); cal.add(Calendar.MONTH, this.months); cal.add(Calendar.DAY_OF_YEAR, this.days); cal.add(Calendar.HOUR_OF_DAY, this.hours); cal.add(Calendar.MINUTE, this.minutes); cal.add(Calendar.SECOND, this.seconds); cal.add(Calendar.MILLISECOND, this.millis); return cal.getTime(); } public String toString() { List buffer = new ArrayList(); if (this.years != 0) buffer.add(this.years + " years"); if (this.months != 0) buffer.add(this.months + " months"); if (this.days != 0) buffer.add(this.days + " days"); if (this.hours != 0) buffer.add(this.hours + " hours"); if (this.minutes != 0) buffer.add(this.minutes + " minutes"); if (this.seconds != 0 || this.millis != 0) buffer.add((seconds == 0 ? (millis < 0 ? "-0" : "0") : seconds) + "." + DefaultGroovyMethods.padLeft("" + Math.abs(millis), 3, "0") + " seconds"); if (buffer.size()!=0) { return DefaultGroovyMethods.join(buffer, ", "); } else { return "0"; } } public abstract long toMilliseconds(); public abstract Date getAgo(); public abstract From getFrom(); public int compareTo(BaseDuration otherDuration) { return Long.signum(toMilliseconds() - otherDuration.toMilliseconds()); } public abstract static class From { public abstract Date getNow(); public Date getToday() { return getNow(); } } } groovy-1.8.6/src/main/groovy/time/Duration.java0000644001501200150120000001261311707612044021024 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; /** *

    Duration represents time periods which have values independent of the context. * So, whilst we can't say how long a month is without knowing the year and the name of the month, * we know how long a day is independent of the date.

    * *

    This is not 100% true for days. * Days can actually be 23, 24 or 25 hours long (due to daylight saving adjustments.)

    * *

    If you ask Duration to convert itself to milliseconds then it will work on the basis of 24 hours * in a day. If you add or subtract it from a date it will take daylight saving into account.

    * * @author John Wilson tug@wilson.co.uk */ public class Duration extends BaseDuration { public Duration(final int days, final int hours, final int minutes, final int seconds, final int millis) { super(days, hours, minutes, seconds, millis); } public Duration plus(final Duration rhs) { return new Duration(this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public Duration plus(final TimeDuration rhs) { return rhs.plus(this); } public DatumDependentDuration plus(final DatumDependentDuration rhs) { return rhs.plus(this); } public Duration minus(final Duration rhs) { return new Duration(this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public TimeDuration minus(final TimeDuration rhs) { return new TimeDuration(this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public DatumDependentDuration minus(final DatumDependentDuration rhs) { return new DatumDependentDuration(-rhs.getYears(), -rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public TimeDatumDependentDuration minus(final TimeDatumDependentDuration rhs) { return new TimeDatumDependentDuration(-rhs.getYears(), -rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public long toMilliseconds() { return ((((((long)(this.getDays() * 24 ) + this.getHours()) * 60 + this.getMinutes()) * 60) + this.getSeconds()) * 1000) + this.getMillis(); } public Date getAgo() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -this.getDays()); cal.add(Calendar.HOUR_OF_DAY, -this.getHours()); cal.add(Calendar.MINUTE, -this.getMinutes()); cal.add(Calendar.SECOND, -this.getSeconds()); cal.add(Calendar.MILLISECOND, -this.getMillis()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. // We do the adds first incase we get carry into the day field // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } public From getFrom() { return new From() { public Date getNow() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, Duration.this.getDays()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. // We do the adds first incase we get carry into the day field // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } }; } } groovy-1.8.6/src/main/groovy/time/TimeCategory.java0000644001501200150120000001422711627206700021635 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Apply a number of methods to allow convenient Date/Time manipulation,such as: *

    *

     * use ( TimeCategory ) {
     *     // application on numbers:
     *     println 1.minute.from.now
     *     println 10.hours.ago
     * 

    * // application on dates * def someDate = new Date() * println someDate - 3.months * }

    * * @see BaseDuration */ public class TimeCategory { /* * Methods to allow Date Duration arithmetic */ public static Date plus(final Date date, final BaseDuration duration) { return duration.plus(date); } public static Date minus(final Date date, final BaseDuration duration) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, -duration.getYears()); cal.add(Calendar.MONTH, -duration.getMonths()); cal.add(Calendar.DAY_OF_YEAR, -duration.getDays()); cal.add(Calendar.HOUR_OF_DAY, -duration.getHours()); cal.add(Calendar.MINUTE, -duration.getMinutes()); cal.add(Calendar.SECOND, -duration.getSeconds()); cal.add(Calendar.MILLISECOND, -duration.getMillis()); return cal.getTime(); } /** * Retrieves the default TimeZone for a date by using the default Locale * settings. * * @param self a Date * @return the TimeZone */ public static TimeZone getTimeZone(Date self) { Calendar calendar = Calendar.getInstance(); calendar.setTime(self); return calendar.getTimeZone(); } /** * Get the DST offset (if any) for the default locale and the given date. * * @param self a Date * @return the DST offset as a Duration. */ public static Duration getDaylightSavingsOffset(Date self) { TimeZone timeZone = getTimeZone(self); int millis = (timeZone.useDaylightTime() && timeZone.inDaylightTime(self)) ? timeZone.getDSTSavings() : 0; return new TimeDuration(0, 0, 0, millis); } public static Duration getDaylightSavingsOffset(BaseDuration self) { return getDaylightSavingsOffset(new Date(self.toMilliseconds() + 1)); } /** * Return a Duration representing the DST difference (if any) between two * dates. i.e. if one date is before the DST changeover, and the other * date is after, the resulting duration will represent the DST offset. * * @param self a Date * @param other another Date * @return a Duration */ public static Duration getRelativeDaylightSavingsOffset(Date self, Date other) { Duration d1 = getDaylightSavingsOffset(self); Duration d2 = getDaylightSavingsOffset(other); return new TimeDuration(0, 0, 0, (int) (d2.toMilliseconds() - d1.toMilliseconds())); } /** * Subtract one date from the other. * * @param lhs a Date * @param rhs another Date * @return a Duration */ public static TimeDuration minus(final Date lhs, final Date rhs) { long milliseconds = lhs.getTime() - rhs.getTime(); long days = milliseconds / (24 * 60 * 60 * 1000); milliseconds -= days * 24 * 60 * 60 * 1000; int hours = (int) (milliseconds / (60 * 60 * 1000)); milliseconds -= hours * 60 * 60 * 1000; int minutes = (int) (milliseconds / (60 * 1000)); milliseconds -= minutes * 60 * 1000; int seconds = (int) (milliseconds / 1000); milliseconds -= seconds * 1000; return new TimeDuration((int) days, hours, minutes, seconds, (int) milliseconds); } /* * Methods on Integer to implement 1.month, 4.years etc. */ public static DatumDependentDuration getMonths(final Integer self) { return new DatumDependentDuration(0, self, 0, 0, 0, 0, 0); } public static DatumDependentDuration getMonth(final Integer self) { return getMonths(self); } public static DatumDependentDuration getYears(final Integer self) { return new DatumDependentDuration(self, 0, 0, 0, 0, 0, 0); } public static DatumDependentDuration getYear(final Integer self) { return getYears(self); } /* * Methods on Integer to implement 1.week, 4.days etc. */ public static Duration getWeeks(final Integer self) { return new Duration(self * 7, 0, 0, 0, 0); } public static Duration getWeek(final Integer self) { return getWeeks(self); } public static Duration getDays(final Integer self) { return new Duration(self, 0, 0, 0, 0); } public static Duration getDay(final Integer self) { return getDays(self); } public static TimeDuration getHours(final Integer self) { return new TimeDuration(0, self, 0, 0, 0); } public static TimeDuration getHour(final Integer self) { return getHours(self); } public static TimeDuration getMinutes(final Integer self) { return new TimeDuration(0, 0, self, 0, 0); } public static TimeDuration getMinute(final Integer self) { return getMinutes(self); } public static TimeDuration getSeconds(final Integer self) { return new TimeDuration(0, 0, 0, self, 0); } public static TimeDuration getSecond(final Integer self) { return getSeconds(self); } public static TimeDuration getMilliseconds(final Integer self) { return new TimeDuration(0, 0, 0, 0, self); } public static TimeDuration getMillisecond(final Integer self) { return getMilliseconds(self); } } groovy-1.8.6/src/main/groovy/time/TimeDatumDependentDuration.java0000644001501200150120000000764611627206700024476 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; /** * TimeDatumDuration represents a time period which results from an * arithmetic operation between a TimeDuration object and a DatumDuration object * * @author John Wilson tug@wilson.co.uk */ public class TimeDatumDependentDuration extends DatumDependentDuration { public TimeDatumDependentDuration(int years, int months, int days, int hours, int minutes, int seconds, int millis) { super(years, months, days, hours, minutes, seconds, millis); } public DatumDependentDuration plus(final Duration rhs) { return new TimeDatumDependentDuration(this.getYears(), this.getMonths(), this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public DatumDependentDuration plus(final DatumDependentDuration rhs) { return new TimeDatumDependentDuration(this.getYears() + rhs.getYears(), this.getMonths() + rhs.getMonths(), this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public DatumDependentDuration minus(final Duration rhs) { return new TimeDatumDependentDuration(this.getYears(), this.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public DatumDependentDuration minus(final DatumDependentDuration rhs) { return new TimeDatumDependentDuration(this.getYears() - rhs.getYears(), this.getMonths() - rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public From getFrom() { return new From() { public Date getNow() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, TimeDatumDependentDuration.this.getYears()); cal.add(Calendar.MONTH, TimeDatumDependentDuration.this.getMonths()); cal.add(Calendar.DAY_OF_YEAR, TimeDatumDependentDuration.this.getDays()); cal.add(Calendar.HOUR_OF_DAY, TimeDatumDependentDuration.this.getHours()); cal.add(Calendar.MINUTE, TimeDatumDependentDuration.this.getMinutes()); cal.add(Calendar.SECOND, TimeDatumDependentDuration.this.getSeconds()); cal.add(Calendar.MILLISECOND, TimeDatumDependentDuration.this.getMillis()); return cal.getTime(); } }; } } groovy-1.8.6/src/main/groovy/time/package.html0000644001501200150120000000136211627206700020653 0ustar miguelmiguel package groovy.time.*

    Classes for easily manipulating Dates and times. While java.util.Date has GDK methods for adding or subtracting days, this is not so useful for different durations of time. {@link groovy.time.TimeCategory TimeCategory} creates a simple internal DSL for manipulating dates and times in a clean and precise fashion.

    Examples

      use ( TimeCategory ) {
      	// application on numbers:
      	println 1.minute.from.now
      	println 10.days.ago
      
      	// application on dates
      	def someDate = new Date()
      	println someDate - 3.months 
      }
    @see groovy.time.TimeCategory groovy-1.8.6/src/main/groovy/time/DatumDependentDuration.java0000644001501200150120000001341211627206700023643 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; /** * DatumDependentDuration represents durations whose length in milliseconds * cannot be determined without knowing the datum point. *

    * I don't know how many days in a year unless I know if it's a leap year or not. *

    * I don't know how many days in a month unless I know the name of the month * (and if it's a leap year if the month is February) * * @author John Wilson tug@wilson.co.uk */ public class DatumDependentDuration extends BaseDuration { public DatumDependentDuration(final int years, final int months, final int days, final int hours, final int minutes, final int seconds, final int millis) { super(years, months, days, hours, minutes, seconds, millis); } public int getMonths() { return this.months; } public int getYears() { return this.years; } public DatumDependentDuration plus(final DatumDependentDuration rhs) { return new DatumDependentDuration(this.getYears() + rhs.getYears(), this.getMonths() + rhs.getMonths(), this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public DatumDependentDuration plus(final TimeDatumDependentDuration rhs) { return rhs.plus(this); } public DatumDependentDuration plus(final Duration rhs) { return new DatumDependentDuration(this.getYears(), this.getMonths(), this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public DatumDependentDuration plus(final TimeDuration rhs) { return rhs.plus(this); } public DatumDependentDuration minus(final DatumDependentDuration rhs) { return new DatumDependentDuration(this.getYears() - rhs.getYears(), this.getMonths() - rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public DatumDependentDuration minus(final Duration rhs) { return new DatumDependentDuration(this.getYears(), this.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } /** * @see groovy.time.BaseDuration#toMilliseconds() * * Change the duration into milliseconds, relative to 'now.' Therefore * things like timezone and time of year will affect how this conversion * occurs. */ public long toMilliseconds() { final Date now = new Date(); return TimeCategory.minus(plus(now), now).toMilliseconds(); } public Date getAgo() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -this.getYears()); cal.add(Calendar.MONTH, -this.getMonths()); cal.add(Calendar.DAY_OF_YEAR, -this.getDays()); cal.add(Calendar.HOUR_OF_DAY, -this.getHours()); cal.add(Calendar.MINUTE, -this.getMinutes()); cal.add(Calendar.SECOND, -this.getSeconds()); cal.add(Calendar.MILLISECOND, -this.getMillis()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. We do the adds first in case we get carry into the day field. // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } public From getFrom() { return new From() { public Date getNow() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, DatumDependentDuration.this.getYears()); cal.add(Calendar.MONTH, DatumDependentDuration.this.getMonths()); cal.add(Calendar.DAY_OF_YEAR, DatumDependentDuration.this.getDays()); cal.add(Calendar.HOUR_OF_DAY, DatumDependentDuration.this.getHours()); cal.add(Calendar.MINUTE, DatumDependentDuration.this.getMinutes()); cal.add(Calendar.SECOND, DatumDependentDuration.this.getSeconds()); cal.add(Calendar.MILLISECOND, DatumDependentDuration.this.getMillis()); // // SqlDate should not really care about these values but it seems to "remember" them // so we clear them. We do the adds first in case we get carry into the day field. // cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new java.sql.Date(cal.getTimeInMillis()); } }; } } groovy-1.8.6/src/main/groovy/time/TimeDuration.java0000644001501200150120000001045611707612044021646 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.time; import java.util.Calendar; import java.util.Date; /** *

    TimeDuration represents time periods expressed in units of hours, minutes, * seconds and milliseconds. * * Whilst we can't say how long a month is without knowing the year and the name of the month, * we know how long a second is independent of the date.

    * *

    This is not 100% true for minutes. * Minutes can be 59, 60 or 61 seconds long (due to leap seconds.)

    * *

    If you ask Duration to convert itself to milliseconds then it will work on the basis of 60 seconds in a minute. * If you add or subtract it from a date it will take leap seconds into account.

    * * @author John Wilson tug@wilson.co.uk * */ public class TimeDuration extends Duration { public TimeDuration(final int hours, final int minutes, final int seconds, final int millis) { super(0, hours, minutes, seconds, millis); } public TimeDuration(final int days, final int hours, final int minutes, final int seconds, final int millis) { super(days, hours, minutes, seconds, millis); } public Duration plus(final Duration rhs) { return new TimeDuration(this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public DatumDependentDuration plus(final DatumDependentDuration rhs) { return new TimeDatumDependentDuration(rhs.getYears(), rhs.getMonths(), this.getDays() + rhs.getDays(), this.getHours() + rhs.getHours(), this.getMinutes() + rhs.getMinutes(), this.getSeconds() + rhs.getSeconds(), this.getMillis() + rhs.getMillis()); } public Duration minus(final Duration rhs) { return new TimeDuration(this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public DatumDependentDuration minus(final DatumDependentDuration rhs) { return new TimeDatumDependentDuration(-rhs.getYears(), -rhs.getMonths(), this.getDays() - rhs.getDays(), this.getHours() - rhs.getHours(), this.getMinutes() - rhs.getMinutes(), this.getSeconds() - rhs.getSeconds(), this.getMillis() - rhs.getMillis()); } public Date getAgo() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -this.getDays()); cal.add(Calendar.HOUR_OF_DAY, -this.getHours()); cal.add(Calendar.MINUTE, -this.getMinutes()); cal.add(Calendar.SECOND, -this.getSeconds()); cal.add(Calendar.MILLISECOND, -this.getMillis()); return cal.getTime(); } public From getFrom() { return new From() { public Date getNow() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, TimeDuration.this.getDays()); cal.add(Calendar.HOUR_OF_DAY, TimeDuration.this.getHours()); cal.add(Calendar.MINUTE, TimeDuration.this.getMinutes()); cal.add(Calendar.SECOND, TimeDuration.this.getSeconds()); cal.add(Calendar.MILLISECOND, TimeDuration.this.getMillis()); return cal.getTime(); } }; } } groovy-1.8.6/src/main/groovy/mock/0000755001501200150120000000000011715031256016363 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/mock/interceptor/0000755001501200150120000000000011715031256020721 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/mock/interceptor/MockInterceptor.groovy0000644001501200150120000000460411715031256025304 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor /** * Intercepting calls to the collaborating object and notify the expectation object. * * @author Dierk Koenig */ class MockInterceptor implements PropertyAccessInterceptor { def expectation = null def beforeInvoke(Object object, String methodName, Object[] arguments) { if (!expectation) throw new IllegalStateException("Property 'expectation' must be set before use.") def result = expectation.match(methodName) if (result == MockProxyMetaClass.FALL_THROUGH_MARKER) return result return result(*arguments) } def beforeGet(Object object, String property) { if (!expectation) throw new IllegalStateException("Property 'expectation' must be set before use.") String name = "get${property[0].toUpperCase()}${property[1..-1]}" def result = expectation.match(name) if (result == MockProxyMetaClass.FALL_THROUGH_MARKER) return result return result() } void beforeSet(Object object, String property, Object newValue) { if (!expectation) throw new IllegalStateException("Property 'expectation' must be set before use.") String name = "set${property[0].toUpperCase()}${property[1..-1]}" def result = expectation.match(name) if (result != MockProxyMetaClass.FALL_THROUGH_MARKER) { result(newValue) result = null } // object is never used so cheat and use it for return value if (object instanceof Object[]) ((Object[])object)[0] = result } def afterInvoke(Object object, String methodName, Object[] arguments, Object result) { return null // never used } boolean doInvoke() { return false // future versions may allow collaborator method calls depending on state } }groovy-1.8.6/src/main/groovy/mock/interceptor/Demand.groovy0000644001501200150120000000365011715031256023364 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor import junit.framework.AssertionFailedError /** * The object that registers method calls on it for the use with Mocks and Stubs. * For each call a CallSpec object is added to the recorded list. * @author Dierk Koenig */ class Demand { List recorded = [] Map ignore = [:] Object invokeMethod(String methodName, Object args) { def range = 1..1 if (args[0] instanceof IntRange) { range = args[0] if (range.reverse) throw new IllegalArgumentException('Reverse ranges not supported.') } else if (args[0] instanceof Integer) { range = args[0]..args[0] } if (args[-1] instanceof Closure) { recorded << new CallSpec(name:methodName, behavior:args[-1], range:range) } } def verify(List calls) { for (i in 0 ..< recorded.size()) { def call = recorded[i] def callCounter = calls[i] ? calls[i] : 0 if (! call.range.contains( callCounter ) ) { def msg = "verify[$i]: expected ${call.range.toString()} call(s) to '${call.name}' but was " throw new AssertionFailedError(msg + "called $callCounter time(s).") } } } } class CallSpec { String name Closure behavior Range range } groovy-1.8.6/src/main/groovy/mock/interceptor/MockFor.groovy0000644001501200150120000002764211715031256023543 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor import java.lang.reflect.Modifier import java.util.regex.Pattern /** * MockFor supports (typically unit) testing of classes in isolation by allowing * a strictly ordered expectation of the behavior of collaborators to be defined. * * A typical test scenario involves a class under test (CUT) and one or more * collaborators. In such a scenario it is often desirable to just test the * business logic of the CUT. One strategy for doing that is to replace * the collaborator instances with simplified mock objects to help isolate out * the logic in the CUT. MockFor allows such mocks to be created using * meta-programming. The desired behavior of collaborators is defined as a * behavior specification. The behavior is enforced and checked automatically. * With MockFor, a mock's expectation is always sequence dependent and its use * automatically ends with a verify(). * * Typical usage is as follows: *
     * import groovy.mock.interceptor.MockFor
     *
     * class Person {
     *   String first, last
     * }
     *
     * class Family {
     *   Person father, mother
     *   def nameOfMother() { "$mother.first $mother.last" }
     * }
     *
     * def mock = new MockFor(Person)
     * mock.demand.getFirst{ 'dummy' }
     * mock.demand.getLast{ 'name' }
     * mock.use {
     *   def mary = new Person(first:'Mary', last:'Smith')
     *   def f = new Family(mother:mary)
     *   assert f.nameOfMother() == 'dummy name'
     * }
     * 
    * Here, Family is our class under test and Person is the collaborator. * We are using normal Groovy property semantics here; hence the statement * mother.last causes a call to mother.getLast() to occur. * * The following features are supported: *
      *
    • typical mock style of failing early *
    • mocks instance and class/static methods *
    • mocks property access using normal getters and setters *
    • mocks final methods and final Collaborators *
    • mocks Groovy and Java Collaborators (Caller must normally be Groovy but see proxyDelegateInstance()) *
    • can mock all objects of a given class (or a single Groovy object) *
    • mocks even if Collaborator cannot be injected into the Caller *
    • mocks even if Collaborator is not accessible on the Caller (no getter) *
    • demanded calls specified via recording calls on the Demand object (EasyMock style). *
    • cardinality specified as Integers or Ranges, default is 1..1; 'optional' can be achieved with 0..1 *
    • behavior specified via Closures, allowing static or calculated return values, throwing exceptions, asserting argument values, etc. (even tricky sequence constraints by sharing state in the testMethod scope between the behavior Closures) *
    • matching parameter list specified via Closure's parameter list, supporting typed or untyped params, default params, and varargs. *
    • not dependent on any external mock library *
    • can mock constructors using an overloaded constructor for MockFor *
    • can support an instance-style mode rather than the default behaviour-style mode using proxyInstance() and proxyDelegateInstance() *
    • can support half-mocks using an ignore specification on the mock instead of a demand specification *
    • can mock non-existing methods if desired *
    * * See also: {@link StubFor}. * * @author Dierk Koenig * @author Paul King */ class MockFor { MockProxyMetaClass proxy Demand demand Ignore ignore def expect Map instanceExpectations = [:] Class clazz /** * The optional interceptConstruction flag allows mocking of * constructor calls. These are represented in the demand specification * using the class name as this example shows: *
         * import groovy.mock.interceptor.MockFor
         * class Person {
         *   String first, last
         * }
         * def interceptConstructorCalls = true
         * def mock = new MockFor(Person, interceptConstructorCalls)
         * def dummy = new Person(first:'Tom', last:'Jones')
         * mock.demand.with {
         *   Person() { dummy } // expect constructor call, return dummy
         *   getFirst() {'John'}
         *   getLast() {'Doe'}
         * }
         * mock.use {
         *   def p = new Person(first:'Mary', last:'Smith')
         *   assert p.first == 'John'
         *   assert p.last == 'Doe'
         * }
         * 
    */ MockFor(Class clazz, boolean interceptConstruction = false) { if (interceptConstruction && !GroovyObject.isAssignableFrom(clazz)) { throw new IllegalArgumentException("MockFor with constructor interception enabled is only allowed for Groovy objects but found: " + clazz.name) } this.clazz = clazz proxy = MockProxyMetaClass.make(clazz, interceptConstruction) demand = new Demand() ignore = new Ignore(parent:this) expect = new StrictExpectation(demand) proxy.interceptor = new MockInterceptor(expectation: expect) } /** * Identifies the Closure where the mocked collaborator behavior * will be applied and verified. */ void use(Closure closure) { proxy.use closure expect.verify() } void use(GroovyObject obj, Closure closure) { proxy.use obj, closure expect.verify() } /** * If manual verification is required */ void verify(GroovyObject obj) { instanceExpectations[obj].verify() } /** * Allows particular method calls to be ignored and not treated as part of * the required behavior specification. If you don't specify a return closure * the method call will fall through to the underlying instance, i.e. half-mock style. * The filter object is invoked using the normal Groovy isCase() semantics. * * Here are some examples: *
         * import groovy.mock.interceptor.MockFor
         * class Person {
         *   String first, last
         *   def name() { "$first $last" }
         *   def ignoreMe() { 'baz' }
         *   def ignoreMeToo() { ignoreMe() }
         *   def ignoreMeThree() { ignoreMe() }
         * }
         * def mock = new MockFor(Person)
         * mock.ignore(~'get.*')
         * mock.ignore('ignoreMeToo') { 'boo' }
         * mock.ignore(~'ignoreMe.*')
         * mock.demand.name{ 'John' }
         * mock.use {
         *   def p = new Person(first:'Mary', last:'Smith')
         *   assert p.first == 'Mary'
         *   assert p.last == 'Smith'
         *   assert p.name() == 'John'
         *   assert p.ignoreMe() == 'baz'
         *   assert p.ignoreMeToo() == 'boo'
         *   assert p.ignoreMeThree() == 'baz'
         * }
         * 
    * There is also a convenience form of ignore that matches the same style as * demand. E.g. instead of mock.ignore('hasNext') you can use * mock.ignore.hasNext(). A Closure variation is also provided. * This convenience shorthand only applies to the String form of ignore * and cannot be used with methods from java.lang.Object. * * Be careful using this feature while mocking some of the fundamental Java * classes like String or Pattern. As these are used within the * implementation of the ignore capability, strange behavior may be observed. */ def ignore(Object filter, Closure filterBehavior = null) { // if Mocking Strings, attempt not to also match Strings with filter if (clazz.name == 'java.lang.String' && filter instanceof String) { filter = Pattern.compile(filter) } demand.ignore.put(filter, filterBehavior ?: MockProxyMetaClass.FALL_THROUGH_MARKER) } /** * Allows a more traditional instance-style mocking paradigm. This is the * recommended method to call to use the instance-style with Groovy classes. * * When mocking interfaces or abstract classes, a compatible proxy instance * will be returned. When mocking Java classes, a compatible Groovy * class will be generated and proxy instance returned. A MockProxyMetaClass * will be instantiated for the original class. * * Typical example: *
         * import groovy.mock.interceptor.MockFor
         *
         * class Person {
         *   String first, last
         * }
         *
         * class Family {
         *   Person mother, father
         *   String nameOfMother() { fullName(mother) }
         *   String nameOfFather() { fullName(father) }
         *   private fullName(p) { "$p.first $p.last" }
         * }
         *
         * def mock = new MockFor(Person)
         * mock.demand.with {
         *   getFirst{ 'dummy' }
         *   getLast{ 'name' }
         * }
         * Person john = mock.proxyInstance()
         * Person mary = mock.proxyInstance()
         * Family f = new Family(father:john, mother:mary)
         * assert f.nameOfFather() == 'dummy name'
         * assert f.nameOfMother() == 'dummy name'
         * [john, mary].each{ mock.verify(it) }
         * 
    * Normally for mocks, verify() is call automatically at the end of the "use" Closure, * but with this style, no "use" Closure is present, so verify() must be called manually. */ GroovyObject proxyInstance(args=null) { makeProxyInstance(args, false) } /** * Allows a more traditional instance-style mocking paradigm. This is the * recommended method to call to use the instance-style with Java classes. * * When mocking interfaces or abstract classes, a compatible proxy instance * will be returned. When mocking Java classes, a compatible Groovy * class will be generated and proxy instance returned. A MockProxyMetaClass * will be instantiated for the class of the instance (i.e. may be on the * generated class not the original class). */ GroovyObject proxyDelegateInstance(args=null) { makeProxyInstance(args, true) } GroovyObject makeProxyInstance(args, boolean isDelegate) { def instance = getInstance(clazz, args) def thisproxy = MockProxyMetaClass.make(isDelegate ? instance.getClass() : clazz) def thisdemand = new Demand(recorded: new ArrayList(demand.recorded), ignore: new HashMap(demand.ignore)) def thisexpect = new StrictExpectation(thisdemand) thisproxy.interceptor = new MockInterceptor(expectation: thisexpect) instance.metaClass = thisproxy def wrapped = instance if (isDelegate && clazz.isInterface()) { wrapped = ProxyGenerator.INSTANCE.instantiateDelegate([clazz], instance) } instanceExpectations[wrapped] = thisexpect return wrapped } static GroovyObject getInstance(Class clazz, args) { GroovyObject instance = null if (clazz.isInterface()) { instance = ProxyGenerator.INSTANCE.instantiateAggregateFromInterface(clazz) } else if (Modifier.isAbstract(clazz.modifiers)) { instance = ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(clazz, args) } else if (args != null) { if (GroovyObject.isAssignableFrom(clazz)) { instance = clazz.newInstance(args) } else { instance = ProxyGenerator.INSTANCE.instantiateDelegate(clazz.newInstance(args)) } } else { if (GroovyObject.isAssignableFrom(clazz)) { instance = clazz.newInstance() } else { instance = ProxyGenerator.INSTANCE.instantiateDelegate(clazz.newInstance()) } } return instance } }groovy-1.8.6/src/main/groovy/mock/interceptor/package.html0000644001501200150120000000567711715031256023221 0ustar miguelmiguel package groovy.mock.interceptor

    The groovy.mock.interceptor is an all-groovy mock testing library.

    Terms:

    Collaborator
    An ordinary Groovy or Java class that's instance or class methods are to be called. Calling them can be time consuming or produce side effects that are unwanted when testing (e.g. database operations).
    Caller
    A Groovy Object that calls methods on the Collaborator, i.e. collaborates with it.
    Mock
    An object that can be used to augment the Collaborator. Method calls to the Collaborator will be handled by the Mock, showing a demanded behavior. Method calls are expected to occur strictly in the demanded sequence with a given range of cardinality. The use of a Mock implicitly ends with verifying the expectations.
    Stub
    Much like a Mock but the expectation about sequences of method calls on the Collaborator is loose, i.e. calls may occur out of the demanded order as long as the ranges of cardinality are met. The use of a Stub does not end with an implicit verification since the stubbing effect is typically asserted on the Caller. An explicit call to verify can be issued to assert all demanded method call have been effected with the specified cardinality.

    Features:

    • typical mock style of failing early
    • mocks instance and class methods
    • mocks final methods and final Collaborators
    • mocks Groovy and Java Collaborators (but Caller must be groovy)
    • can mock all objects of a given class (or a single Groovy object)
    • mocks even if Collaborator cannot be injected into the Caller
    • mocks even if Collaborator is not accessible on the Caller (no getter)
    • demanded calls specified via recording calls on the Demand object (EasyMock style).
    • cardinality specified as Ranges, default is 1..1; 'optional' can be achieved with 0..1
    • behavior specified via Closures, allowing static or calculated return values, throwing exceptions, asserting argument values, etc. (even tricky sequence constraints by sharing state in the testMethod scope between the behavior Closures)
    • matching parameter list specified via Closure's parameter list, supporting typed or untyped params, default params, and varargs.
    • not dependent on any external mock library

    For an extensive list of usages see the unit tests in this package.

    groovy-1.8.6/src/main/groovy/mock/interceptor/LooseExpectation.groovy0000644001501200150120000000454211715031256025462 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor import junit.framework.AssertionFailedError import org.codehaus.groovy.runtime.DefaultGroovyMethods /** * Expects demanded call cardinalities to match demanded ranges. * The calls are allowed to be out of the recorded sequence. * If a method is demanded multiple times, the ranges are filled by order of recording. * * @see StrictExpectation * @author Dierk Koenig */ class LooseExpectation { Demand fDemand = null List fCalls = [] LooseExpectation(Demand demand) { fDemand = demand } /** * Match the requested method name against eligible demands. * Fail early if no match possible. * Return the demand's behavior closure on match. * Also skips over names matching ignore filter, if any. */ Closure match(String name) { def filter = fDemand.ignore.keySet().find{ DefaultGroovyMethods.grep([name], it) } if (filter) return fDemand.ignore.get(filter) def callIndex = 0 // find first eligible callSpec while (! isEligible(name, callIndex) ) callIndex++ // register the call fCalls[callIndex] += 1 return fDemand.recorded[callIndex].behavior } boolean isEligible(String name, int i) { def calls = fDemand.recorded if (i >= calls.size()) { throw new AssertionFailedError("No more calls to '$name' expected at this point. End of demands.") } if (calls[i].name != name) return false if (null == fCalls[i]) fCalls[i] = 0 if (fCalls[i] >= calls[i].range.to) return false return true } /** verify all calls are in expected range */ void verify() { fDemand.verify(fCalls) } }groovy-1.8.6/src/main/groovy/mock/interceptor/StrictExpectation.groovy0000644001501200150120000000535611715031256025655 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor import junit.framework.AssertionFailedError import org.codehaus.groovy.runtime.DefaultGroovyMethods /** * Expects demanded call cardinalities to match demanded ranges in the sequence of recording. * * @see LooseExpectation * @author Dierk Koenig */ class StrictExpectation { Demand fDemand = null int fCallSpecIdx = 0 List fCalls = [] StrictExpectation(Demand demand) { fDemand = demand } /** * Match the requested method name against eligible demands. * Fail early if no match possible. * Return the demand's behavior closure on match. * Also skips over names matching ignore filter, if any. */ Closure match(String name) { def filter = fDemand.ignore.keySet().find{ DefaultGroovyMethods.grep([name], it) } if (filter) return fDemand.ignore.get(filter) if (!fCalls[fCallSpecIdx]) fCalls[fCallSpecIdx] = 0 if (fCallSpecIdx >= fDemand.recorded.size()) { throw new AssertionFailedError("No more calls to '$name' expected at this point. End of demands.") } def call = fDemand.recorded[fCallSpecIdx] if (name != call.name) { // if name does not match... def open = call.range.from - fCalls[fCallSpecIdx] if ( open > 0) { // ... if we haven't reached the minimum, yet -> Exception throw new AssertionFailedError("No call to '$name' expected at this point. "+ "Still $open call(s) to '${call.name}' expected.") } else { // ... proceed finding fCallSpecIdx++ return match(name) } } // register the call fCalls[fCallSpecIdx] += 1 // store the behavior for returning def result = call.behavior // proceed to next callSpec if we need to if (fCalls[fCallSpecIdx] >= call.range.to ) fCallSpecIdx++ return result } /** verify all calls are in expected range */ void verify() { fDemand.verify(fCalls) } }groovy-1.8.6/src/main/groovy/mock/interceptor/Ignore.groovy0000644001501200150120000000307011715031256023413 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor /** * Helper object to support convenience "ignore.methodName" notation similar to demand notation. * Can't be used with methods within java.lang.Object. * * @author Paul King */ class Ignore { def parent // point back to original MockFor/StubFor Object invokeMethod(String methodName, Object args) { if (args && args.size() > 1) { throw new IllegalArgumentException("Ranges/repetitions not supported for ignored method '$methodName'.") } if (args && args.size() == 1) { if (args[0] instanceof Closure) parent.ignore(methodName, (Closure) args[0]) else throw new IllegalArgumentException( "Optional parameter to ignored method '$methodName' must be a Closure but instead found a ${args[0].getClass().simpleName}.") } else { parent.ignore(methodName, null) } } } groovy-1.8.6/src/main/groovy/mock/interceptor/MockProxyMetaClass.java0000644001501200150120000001547411715031256025327 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor; import groovy.lang.*; import java.beans.IntrospectionException; /** * The ProxyMetaClass for the MockInterceptor. * Instance and class methods are intercepted, but constructors are not to allow mocking of aggregated objects. * * @author Dierk Koenig */ public class MockProxyMetaClass extends ProxyMetaClass { public final boolean interceptConstruction; private boolean fallingThrough; static class FallThroughMarker extends Closure { public FallThroughMarker(Object owner) { super(owner); } } static final FallThroughMarker FALL_THROUGH_MARKER = new FallThroughMarker(new Object()); /** * @param adaptee the MetaClass to decorate with interceptability */ public MockProxyMetaClass(MetaClassRegistry registry, Class theClass, MetaClass adaptee) throws IntrospectionException { this(registry, theClass, adaptee, false); } /** * @param adaptee the MetaClass to decorate with interceptability */ public MockProxyMetaClass(MetaClassRegistry registry, Class theClass, MetaClass adaptee, boolean interceptConstruction) throws IntrospectionException { super(registry, theClass, adaptee); this.interceptConstruction = interceptConstruction; } /** * convenience factory method for the most usual case. */ public static MockProxyMetaClass make(Class theClass) throws IntrospectionException { return make(theClass, false); } /** * convenience factory method allowing interceptConstruction to be set. */ public static MockProxyMetaClass make(Class theClass, boolean interceptConstruction) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new MockProxyMetaClass(metaRegistry, theClass, meta, interceptConstruction); } public Object invokeMethod(final Object object, final String methodName, final Object[] arguments) { if (null == interceptor && !fallingThrough) { throw new RuntimeException("cannot invoke method '" + methodName + "' without interceptor"); } Object result = FALL_THROUGH_MARKER; if (interceptor != null) { result = interceptor.beforeInvoke(object, methodName, arguments); } if (result == FALL_THROUGH_MARKER) { Interceptor saved = interceptor; interceptor = null; boolean savedFallingThrough = fallingThrough; fallingThrough = true; result = adaptee.invokeMethod(object, methodName, arguments); fallingThrough = savedFallingThrough; interceptor = saved; } return result; } public Object invokeStaticMethod(final Object object, final String methodName, final Object[] arguments) { if (null == interceptor && !fallingThrough) { throw new RuntimeException("cannot invoke static method '" + methodName + "' without interceptor"); } Object result = FALL_THROUGH_MARKER; if (interceptor != null) { result = interceptor.beforeInvoke(object, methodName, arguments); } if (result == FALL_THROUGH_MARKER) { Interceptor saved = interceptor; interceptor = null; boolean savedFallingThrough = fallingThrough; fallingThrough = true; result = adaptee.invokeStaticMethod(object, methodName, arguments); fallingThrough = savedFallingThrough; interceptor = saved; } return result; } public Object getProperty(Class aClass, Object object, String property, boolean b, boolean b1) { if (null == interceptor && !fallingThrough) { throw new RuntimeException("cannot get property '" + property + "' without interceptor"); } Object result = FALL_THROUGH_MARKER; if (interceptor != null && interceptor instanceof PropertyAccessInterceptor) { result = ((PropertyAccessInterceptor) interceptor).beforeGet(object, property); } if (result == FALL_THROUGH_MARKER) { Interceptor saved = interceptor; interceptor = null; boolean savedFallingThrough = fallingThrough; fallingThrough = true; result = adaptee.getProperty(aClass, object, property, b, b1); fallingThrough = savedFallingThrough; interceptor = saved; } return result; } public void setProperty(Class aClass, Object object, String property, Object newValue, boolean b, boolean b1) { if (null == interceptor && !fallingThrough) { throw new RuntimeException("cannot set property '" + property + "' without interceptor"); } Object result = FALL_THROUGH_MARKER; if (interceptor != null && interceptor instanceof PropertyAccessInterceptor) { // cheat and borrow first param for result as we don't use it anyway Object[] resultHolder = new Object[1]; ((PropertyAccessInterceptor) interceptor).beforeSet(resultHolder, property, newValue); result = resultHolder[0]; } if (result == FALL_THROUGH_MARKER) { Interceptor saved = interceptor; interceptor = null; boolean savedFallingThrough = fallingThrough; fallingThrough = true; adaptee.setProperty(aClass, object, property, newValue, b, b1); fallingThrough = savedFallingThrough; interceptor = saved; } } /** * Unlike general impl in superclass, ctors are not intercepted but relayed * unless interceptConstruction is set. */ public Object invokeConstructor(final Object[] arguments) { if (interceptConstruction && null == interceptor) throw new RuntimeException("cannot invoke constructor without interceptor"); if (interceptConstruction) { GroovyObject newInstance = (GroovyObject) interceptor.beforeInvoke(null, getTheClass().getSimpleName(), arguments); newInstance.setMetaClass(this); return newInstance; } return adaptee.invokeConstructor(arguments); } } groovy-1.8.6/src/main/groovy/mock/interceptor/StubFor.groovy0000644001501200150120000001323011715031256023553 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.mock.interceptor import java.util.regex.Pattern /** * StubFor supports (typically unit) testing of classes in isolation by allowing * a loosely-ordered expectation of the behavior of collaborators to be defined. * * A typical test scenario involves a class under test (CUT) and one or more * collaborators. In such a scenario it is often desirable to just test the * business logic of the CUT. One strategy for doing that is to replace * the collaborator instances with simplified stub objects to help isolate out * the logic in the CUT. StubFor allows such stubs to be created using * meta-programming. The desired behavior of collaborators is defined as a * behavior specification. The behavior can be checked by the user using verify(). * With StubFor, a stub's expectation is sequence independent and use of verify() * is left to the user. * * Typical usage is as follows: *
     * import groovy.mock.interceptor.StubFor
     *
     * class Person {
     *   String first, last
     * }
     *
     * class Family {
     *   Person mother, father
     *   def nameOfFather() { "$father.first $father.last" }
     * }
     *
     * def stub = new StubFor(Person)
     * stub.demand.with {
     *   getLast{ 'name' }
     *   getFirst{ 'dummy' }
     * }
     * stub.use {
     *   def john = new Person(first:'John', last:'Smith')
     *   def f = new Family(father:john)
     *   assert f.nameOfFather() == 'dummy name'
     * }
     * stub.expect.verify()
     * 
    * Here, Family is our class under test and Person is the collaborator. * We are using normal Groovy property semantics here; hence the statement * father.first causes a call to father.getFirst() to occur. * * For a complete list of features, see: {@link MockFor}. * * @author Dierk Koenig * @author Paul King */ class StubFor { MockProxyMetaClass proxy Demand demand Ignore ignore def expect Map instanceExpectations = [:] Class clazz StubFor(Class clazz, boolean interceptConstruction = false) { if (interceptConstruction && !GroovyObject.isAssignableFrom(clazz)) { throw new IllegalArgumentException("StubFor with constructor interception enabled is only allowed for Groovy objects but found: " + clazz.name) } this.clazz = clazz proxy = MockProxyMetaClass.make(clazz, interceptConstruction) demand = new Demand() ignore = new Ignore(parent:this) expect = new LooseExpectation(demand) proxy.interceptor = new MockInterceptor(expectation: expect) } /** * @See MockFor#use(Closure) */ void use(Closure closure) { proxy.use closure } void use(GroovyObject obj, Closure closure) { proxy.use obj, closure } /** * For manual verification */ void verify(GroovyObject obj) { instanceExpectations[obj].verify() } /** * Convenience method */ void verify() { expect.verify() } /** * Allows particular method calls to be ignored and not treated as part of * the required behavior specification. If you don't specify a return closure * the method call will fall through to the underlying instance, i.e. half-mock style. * The filter object is invoked using the normal Groovy isCase() semantics. * * @See MockFor#ignore(Object, Closure) */ def ignore(Object filter, Closure filterBehavior = null) { // if Stubbing Strings, attempt not to also match Strings with filter if (clazz.name == 'java.lang.String' && filter instanceof String) { filter = Pattern.compile(filter) } demand.ignore.put(filter, filterBehavior ?: MockProxyMetaClass.FALL_THROUGH_MARKER) } /** * Allows a more traditional instance-style stubbing paradigm. This is the * recommended method to call to use the instance-style with Groovy classes. * * @See MockFor#proxyInstance(Object) */ GroovyObject proxyInstance(args=null) { makeProxyInstance(args, false) } /** * Allows a more traditional instance-style stubbing paradigm. This is the * recommended method to call to use the instance-style with Java classes. * * @See MockFor#proxyDelegateInstance(Object) */ GroovyObject proxyDelegateInstance(args=null) { makeProxyInstance(args, true) } GroovyObject makeProxyInstance(args, boolean isDelegate) { def instance = MockFor.getInstance(clazz, args) def thisproxy = MockProxyMetaClass.make(isDelegate ? instance.getClass() : clazz) def thisdemand = new Demand(recorded: new ArrayList(demand.recorded), ignore: new HashMap(demand.ignore)) def thisexpect = new LooseExpectation(thisdemand) thisproxy.interceptor = new MockInterceptor(expectation: thisexpect) instance.metaClass = thisproxy def wrapped = instance if (isDelegate && clazz.isInterface()) { wrapped = ProxyGenerator.INSTANCE.instantiateDelegate([clazz], instance) } instanceExpectations[wrapped] = thisexpect return wrapped } }groovy-1.8.6/src/main/groovy/util/0000755001501200150120000000000011715031256016407 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/util/GroovyShellTestCase.groovy0000644001501200150120000000374311715031256023576 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util /** * Groovy test case, which recreates internal GroovyShell in each setUp () * * @author Alex Tkachman */ class GroovyShellTestCase extends GroovyTestCase { @Delegate protected GroovyShell shell protected void setUp() { super.setUp(); shell = createNewShell(); } protected void tearDown() { shell = null; super.tearDown(); } /** * Create new shell instance. * Overwrite it to customize */ protected GroovyShell createNewShell() { return new GroovyShell() } /** * Executes closure with given binding */ protected def withBinding (Map map, Closure closure) { Binding binding = shell.context Map bmap = binding.variables try { Map vars = new HashMap(bmap) bmap.putAll map return closure.call() } finally { bmap.clear() bmap.putAll vars } } /** * Evaluates script with given binding */ protected def withBinding (Map map, String script) { Binding binding = shell.context Map bmap = binding.variables try { Map vars = new HashMap(bmap) bmap.putAll map return evaluate(script) } finally { bmap.clear() bmap.putAll vars } } }groovy-1.8.6/src/main/groovy/util/AntBuilder.java0000644001501200150120000003603111645141222021303 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.xml.QName; import org.apache.tools.ant.*; import org.apache.tools.ant.dispatch.DispatchUtils; import org.apache.tools.ant.helper.AntXMLContext; import org.apache.tools.ant.helper.ProjectHelper2; import org.codehaus.groovy.ant.FileScanner; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.AttributesImpl; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * Allows Ant tasks to * be used with a Groovy builder-style markup. Requires that {{ant.jar}} is on your classpath which will * happen automatically if you are using the Groovy distribution but will be up * to you to organize if you are embedding Groovy. If you wish to use the * optional tasks * you will need to add one or more additional jars from the ant distribution to * your classpath - see the library * dependencies for more details. * * @author James Strachan * @author Dierk Koenig (dk) * @author Marc Guillemot */ public class AntBuilder extends BuilderSupport { private final Logger log = Logger.getLogger(getClass().getName()); private Project project; private final AntXMLContext antXmlContext; private final ProjectHelper2.ElementHandler antElementHandler = new ProjectHelper2.ElementHandler(); private final ProjectHelper2.TargetHandler antTargetHandler = new ProjectHelper2.TargetHandler(); private final Target collectorTarget; private final Target implicitTarget; private Object lastCompletedNode; // true when inside a task so special ant.target handling occurs just at top level boolean insideTask; public AntBuilder() { this(createProject()); } public AntBuilder(final Project project) { this(project, new Target()); } public AntBuilder(final Project project, final Target owningTarget) { this.project = project; /* * GROOVY-4524: The following is not needed anymore as an ant Project already by default has inputhandler * set to DefaultInputHandler. And if it is again set here, it mistakenly overrides the custom input handler * if set using -inputhandler switch. */ //this.project.setInputHandler(new DefaultInputHandler()); collectorTarget = owningTarget; antXmlContext = new AntXMLContext(project); collectorTarget.setProject(project); antXmlContext.setCurrentTarget(collectorTarget); antXmlContext.setLocator(new AntBuilderLocator()); antXmlContext.setCurrentTargets(new HashMap()); implicitTarget = new Target(); implicitTarget.setProject(project); implicitTarget.setName(""); antXmlContext.setImplicitTarget(implicitTarget); // FileScanner is a Groovy hack (utility?) project.addDataTypeDefinition("fileScanner", FileScanner.class); } public AntBuilder(final Task parentTask) { this(parentTask.getProject(), parentTask.getOwningTarget()); // define "owning" task as wrapper to avoid having tasks added to the target // but it needs to be an UnknownElement and no access is available from // task to its original UnknownElement final UnknownElement ue = new UnknownElement(parentTask.getTaskName()); ue.setProject(parentTask.getProject()); ue.setTaskType(parentTask.getTaskType()); ue.setTaskName(parentTask.getTaskName()); ue.setLocation(parentTask.getLocation()); ue.setOwningTarget(parentTask.getOwningTarget()); ue.setRuntimeConfigurableWrapper(parentTask.getRuntimeConfigurableWrapper()); parentTask.getRuntimeConfigurableWrapper().setProxy(ue); antXmlContext.pushWrapper(parentTask.getRuntimeConfigurableWrapper()); } /** * # * Gets the Ant project in which the tasks are executed * * @return the project */ public Project getProject() { return project; } /** * Gets the xml context of Ant used while creating tasks * * @return the Ant xml context */ public AntXMLContext getAntXmlContext() { return antXmlContext; } /** * @return Factory method to create new Project instances */ protected static Project createProject() { final Project project = new Project(); final ProjectHelper helper = ProjectHelper.getProjectHelper(); project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper); helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty final BuildLogger logger = new NoBannerLogger(); logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO); logger.setOutputPrintStream(System.out); logger.setErrorPrintStream(System.err); project.addBuildListener(logger); project.init(); project.getBaseDir(); return project; } protected void setParent(Object parent, Object child) { } /** * We don't want to return the node as created in {@link #createNode(Object, Map, Object)} * but the one made ready by {@link #nodeCompleted(Object, Object)} * * @see groovy.util.BuilderSupport#doInvokeMethod(java.lang.String, java.lang.Object, java.lang.Object) */ protected Object doInvokeMethod(String methodName, Object name, Object args) { super.doInvokeMethod(methodName, name, args); // return the completed node return lastCompletedNode; } /** * Determines, when the ANT Task that is represented by the "node" should perform. * Node must be an ANT Task or no "perform" is called. * If node is an ANT Task, it performs right after complete construction. * If node is nested in a TaskContainer, calling "perform" is delegated to that * TaskContainer. * * @param parent note: null when node is root * @param node the node that now has all its children applied */ protected void nodeCompleted(final Object parent, final Object node) { if (parent == null) insideTask = false; antElementHandler.onEndElement(null, null, antXmlContext); lastCompletedNode = node; if (parent != null && !(parent instanceof Target)) { log.finest("parent is not null: no perform on nodeCompleted"); return; // parent will care about when children perform } // as in Target.execute() if (node instanceof Task) { Task task = (Task) node; final String taskName = task.getTaskName(); if ("antcall".equals(taskName) && parent == null) { throw new BuildException("antcall not supported within AntBuilder, consider using 'ant.project.executeTarget('targetName')' instead."); } // save original streams InputStream savedProjectInputStream = project.getDefaultInputStream(); InputStream savedIn = System.in; PrintStream savedErr = System.err; PrintStream savedOut = System.out; if (!(savedIn instanceof DemuxInputStream)) { project.setDefaultInputStream(savedIn); System.setIn(new DemuxInputStream(project)); } System.setOut(new PrintStream(new DemuxOutputStream(project, false))); System.setErr(new PrintStream(new DemuxOutputStream(project, true))); try { lastCompletedNode = performTask(task); } finally { // restore original streams project.setDefaultInputStream(savedProjectInputStream); System.setIn(savedIn); System.setOut(savedOut); System.setErr(savedErr); } // restore dummy collector target if ("import".equals(taskName)) { antXmlContext.setCurrentTarget(collectorTarget); } } else if (node instanceof Target) { // restore dummy collector target antXmlContext.setCurrentTarget(collectorTarget); } else { final RuntimeConfigurable r = (RuntimeConfigurable) node; r.maybeConfigure(project); } } // Copied from org.apache.tools.ant.Task, since we need to get a real thing before it gets nulled in DispatchUtils.execute private Object performTask(Task task) { Throwable reason = null; try { // Have to call fireTestStared/fireTestFinished via reflection as they unfortunately have protected access in Project final Method fireTaskStarted = Project.class.getDeclaredMethod("fireTaskStarted", Task.class); fireTaskStarted.setAccessible(true); fireTaskStarted.invoke(project, task); Object realThing; realThing = task; task.maybeConfigure(); if (task instanceof UnknownElement) { realThing = ((UnknownElement) task).getRealThing(); } DispatchUtils.execute(task); return realThing != null ? realThing : task; } catch (BuildException ex) { if (ex.getLocation() == Location.UNKNOWN_LOCATION) { ex.setLocation(task.getLocation()); } reason = ex; throw ex; } catch (Exception ex) { reason = ex; BuildException be = new BuildException(ex); be.setLocation(task.getLocation()); throw be; } catch (Error ex) { reason = ex; throw ex; } finally { try { final Method fireTaskFinished = Project.class.getDeclaredMethod("fireTaskFinished", Task.class, Throwable.class); fireTaskFinished.setAccessible(true); fireTaskFinished.invoke(project, task, reason); } catch (Exception e) { BuildException be = new BuildException(e); be.setLocation(task.getLocation()); throw be; } } } protected Object createNode(Object tagName) { return createNode(tagName, Collections.EMPTY_MAP); } protected Object createNode(Object name, Object value) { Object task = createNode(name); setText(task, value.toString()); return task; } protected Object createNode(Object name, Map attributes, Object value) { Object task = createNode(name, attributes); setText(task, value.toString()); return task; } /** * Builds an {@link Attributes} from a {@link Map} * * @param attributes the attributes to wrap * @return the wrapped attributes */ protected static Attributes buildAttributes(final Map attributes) { final AttributesImpl attr = new AttributesImpl(); for (Object o : attributes.entrySet()) { final Map.Entry entry = (Map.Entry) o; final String attributeName = (String) entry.getKey(); final String attributeValue = String.valueOf(entry.getValue()); attr.addAttribute(null, attributeName, attributeName, "CDATA", attributeValue); } return attr; } protected Object createNode(final Object name, final Map attributes) { final Attributes attrs = buildAttributes(attributes); String tagName = name.toString(); String ns = ""; if (name instanceof QName) { QName q = (QName) name; tagName = q.getLocalPart(); ns = q.getNamespaceURI(); } // import can be used only as top level element if ("import".equals(name)) { antXmlContext.setCurrentTarget(implicitTarget); } else if ("target".equals(name) && !insideTask) { return onStartTarget(attrs, tagName, ns); } try { antElementHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext); } catch (final SAXParseException e) { log.log(Level.SEVERE, "Caught: " + e, e); } insideTask = true; final RuntimeConfigurable wrapper = (RuntimeConfigurable) antXmlContext.getWrapperStack().lastElement(); return wrapper.getProxy(); } private Target onStartTarget(final Attributes attrs, String tagName, String ns) { final Target target = new Target(); target.setProject(project); target.setLocation(new Location(antXmlContext.getLocator())); try { antTargetHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext); final Target newTarget = (Target) getProject().getTargets().get(attrs.getValue("name")); // execute dependencies (if any) final Vector targets = new Vector(); for (final Enumeration deps = newTarget.getDependencies(); deps.hasMoreElements();) { final String targetName = (String) deps.nextElement(); targets.add(project.getTargets().get(targetName)); } getProject().executeSortedTargets(targets); antXmlContext.setCurrentTarget(newTarget); return newTarget; } catch (final SAXParseException e) { log.log(Level.SEVERE, "Caught: " + e, e); } return null; } protected void setText(Object task, String text) { final char[] characters = text.toCharArray(); try { antElementHandler.characters(characters, 0, characters.length, antXmlContext); } catch (final SAXParseException e) { log.log(Level.WARNING, "SetText failed: " + task + ". Reason: " + e, e); } } public Project getAntProject() { return project; } } /** * Would be nice to retrieve location information (from AST?). * In a first time, without info */ class AntBuilderLocator implements Locator { public int getColumnNumber() { return 0; } public int getLineNumber() { return 0; } public String getPublicId() { return ""; } public String getSystemId() { return ""; } } groovy-1.8.6/src/main/groovy/util/XmlSlurper.java0000644001501200150120000003534411645141222021375 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.util.slurpersupport.GPathResult; import groovy.util.slurpersupport.Node; import groovy.util.slurpersupport.NodeChild; import groovy.xml.FactorySupport; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Stack; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** *

    Parse XML into a document tree that may be traversed similar to XPath * expressions. For example:

    *
     * def rootNode = new XmlSlurper().parseText(
     *    '<root><one a1="uno!"/><two>Some text!</two></root>' )
     *
     * assert rootNode.name() == 'root'
     * assert rootNode.one[0].@a1 == 'uno!'
     * assert rootNode.two.text() == 'Some text!'
     * rootNode.children().each { assert it.name() in ['one','two'] }
     * 
    *

    *

    Note that in some cases, a 'selector' expression may not resolve to a * single node. For example:

    *
     * def rootNode = new XmlSlurper().parseText(
     *    '''<root>
     *         <a>one!</a>
     *         <a>two!</a>
     *       </root>''' )
     *
     * assert rootNode.a.size() == 2
     * rootNode.a.each { assert it.text() in ['one!','two!'] }
     * 
    * * @author John Wilson * @see GPathResult */ public class XmlSlurper extends DefaultHandler { private final XMLReader reader; private Node currentNode = null; private final Stack stack = new Stack(); private final StringBuffer charBuffer = new StringBuffer(); private final Map namespaceTagHints = new Hashtable(); private boolean keepWhitespace = false; /** * Uses the defaults of not validating and namespace aware. * * @throws ParserConfigurationException if a parser cannot * be created which satisfies the requested configuration. * @throws SAXException for SAX errors. */ public XmlSlurper() throws ParserConfigurationException, SAXException { this(false, true); } public XmlSlurper(final boolean validating, final boolean namespaceAware) throws ParserConfigurationException, SAXException { SAXParserFactory factory = FactorySupport.createSaxParserFactory(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); reader = factory.newSAXParser().getXMLReader(); } public XmlSlurper(final XMLReader reader) { this.reader = reader; } public XmlSlurper(final SAXParser parser) throws SAXException { this(parser.getXMLReader()); } /** * @param keepWhitespace If true then whitespace before elements is kept. * The default is to discard the whitespace. */ public void setKeepWhitespace(boolean keepWhitespace) { this.keepWhitespace = keepWhitespace; } /** * @return The GPathResult instance created by consuming a stream of SAX events * Note if one of the parse methods has been called then this returns null * Note if this is called more than once all calls after the first will return null */ public GPathResult getDocument() { try { return new NodeChild(currentNode, null, namespaceTagHints); } finally { currentNode = null; } } /** * Parse the content of the specified input source into a GPathResult object * * @param input the InputSource to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parse(final InputSource input) throws IOException, SAXException { reader.setContentHandler(this); reader.parse(input); return getDocument(); } /** * Parses the content of the given file as XML turning it into a GPathResult object * * @param file the File to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parse(final File file) throws IOException, SAXException { final FileInputStream fis = new FileInputStream(file); final InputSource input = new InputSource(fis); input.setSystemId("file://" + file.getAbsolutePath()); try { return parse(input); } finally { fis.close(); } } /** * Parse the content of the specified input stream into an GPathResult Object. * Note that using this method will not provide the parser with any URI * for which to find DTDs etc. It is up to you to close the InputStream * after parsing is complete (if required). * * @param input the InputStream to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parse(final InputStream input) throws IOException, SAXException { return parse(new InputSource(input)); } /** * Parse the content of the specified reader into a GPathResult Object. * Note that using this method will not provide the parser with any URI * for which to find DTDs etc. It is up to you to close the Reader * after parsing is complete (if required). * * @param in the Reader to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parse(final Reader in) throws IOException, SAXException { return parse(new InputSource(in)); } /** * Parse the content of the specified URI into a GPathResult Object * * @param uri a String containing the URI to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parse(final String uri) throws IOException, SAXException { return parse(new InputSource(uri)); } /** * A helper method to parse the given text as XML * * @param text a String containing XML to parse * @return An object which supports GPath expressions * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte stream * or character stream supplied by the application. */ public GPathResult parseText(final String text) throws IOException, SAXException { return parse(new StringReader(text)); } // Delegated XMLReader methods //------------------------------------------------------------------------ /* (non-Javadoc) * @see org.xml.sax.XMLReader#getDTDHandler() */ public DTDHandler getDTDHandler() { return reader.getDTDHandler(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getEntityResolver() */ public EntityResolver getEntityResolver() { return reader.getEntityResolver(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getErrorHandler() */ public ErrorHandler getErrorHandler() { return reader.getErrorHandler(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getFeature(java.lang.String) */ public boolean getFeature(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException { return reader.getFeature(uri); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getProperty(java.lang.String) */ public Object getProperty(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException { return reader.getProperty(uri); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler) */ public void setDTDHandler(final DTDHandler dtdHandler) { reader.setDTDHandler(dtdHandler); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver) */ public void setEntityResolver(final EntityResolver entityResolver) { reader.setEntityResolver(entityResolver); } /** * Resolves entities against using the supplied URL as the base for relative URLs * * @param base The URL used to resolve relative URLs */ public void setEntityBaseUrl(final URL base) { reader.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(final String publicId, final String systemId) throws IOException { return new InputSource(new URL(base, systemId).openStream()); } }); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ public void setErrorHandler(final ErrorHandler errorHandler) { reader.setErrorHandler(errorHandler); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean) */ public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { reader.setFeature(uri, value); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(final String uri, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException { reader.setProperty(uri, value); } // ContentHandler interface //------------------------------------------------------------------------- /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startDocument() */ public void startDocument() throws SAXException { currentNode = null; charBuffer.setLength(0); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#startPrefixMapping(java.lang.String, java.lang.String) */ public void startPrefixMapping(final String tag, final String uri) throws SAXException { namespaceTagHints.put(tag, uri); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException { addCdata(); final Map attributes = new HashMap(); final Map attributeNamespaces = new HashMap(); for (int i = atts.getLength() - 1; i != -1; i--) { if (atts.getURI(i).length() == 0) { attributes.put(atts.getQName(i), atts.getValue(i)); } else { attributes.put(atts.getLocalName(i), atts.getValue(i)); attributeNamespaces.put(atts.getLocalName(i), atts.getURI(i)); } } final Node newElement; if (namespaceURI.length() == 0) { newElement = new Node(currentNode, qName, attributes, attributeNamespaces, namespaceURI); } else { newElement = new Node(currentNode, localName, attributes, attributeNamespaces, namespaceURI); } if (currentNode != null) { currentNode.addChild(newElement); } stack.push(currentNode); currentNode = newElement; } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters(final char[] ch, final int start, final int length) throws SAXException { charBuffer.append(ch, start, length); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { addCdata(); Node oldCurrentNode = stack.pop(); if (oldCurrentNode != null) { currentNode = oldCurrentNode; } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endDocument() */ public void endDocument() throws SAXException { } // Implementation methods //------------------------------------------------------------------------- /** * */ private void addCdata() { if (charBuffer.length() != 0) { // // This element is preceded by CDATA if keepWhitespace is false (the default setting) and // it's not whitespace add it to the body // Note that, according to the XML spec, we should preserve the CDATA if it's all whitespace // but for the sort of work I'm doing ignoring the whitespace is preferable // final String cdata = charBuffer.toString(); charBuffer.setLength(0); if (keepWhitespace || cdata.trim().length() != 0) { currentNode.addChild(cdata); } } } } groovy-1.8.6/src/main/groovy/util/JavadocAssertionTestBuilder.groovy0000644001501200150120000001204111715031256025262 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util import java.util.regex.Pattern /** * JavadocAssertionTestBuilder will dynamically create a test cases from Groovy assertions placed within * the Javadoc comments of a source file. Assertions should be placed within an html tag with a class="groovyTestCase" * attribute assignment. Example: *
    <pre class="groovyTestCase"> assert "example".size() == 7 </pre>
    * * @author Merlyn Albery-Speyer */ class JavadocAssertionTestBuilder { private static Pattern javadocPattern = Pattern.compile( /(?ims)\/\*\*.*?\*\// ) private static Pattern assertionPattern = Pattern.compile( /(?ims)<([a-z]+)\s+class\s*=\s*['"]groovyTestCase['"]\s*>.*?<\s*\/\s*\1>/ ) Class buildTest(String filename, String code) { Class test = null List assertionTags = getAssertionTags(code); if (assertionTags) { String testName = getTestName(filename) Map lineNumberToAssertions = getLineNumberToAssertionsMap(code, assertionTags) List testMethods = getTestMethods(lineNumberToAssertions, filename) String testCode = getTestCode(testName, testMethods) test = createClass(testCode) } return test } private List getAssertionTags(String code) { List assertions = new ArrayList() code.eachMatch(javadocPattern) { javadoc -> assertions.addAll(javadoc.findAll(assertionPattern)) } return assertions } private String getTestName(String filename) { String filenameWithoutPath = new File(filename).name String testName = filenameWithoutPath.substring(0, filenameWithoutPath.lastIndexOf(".")) + "JavadocAssertionTest" return testName } private Map getLineNumberToAssertionsMap(String code, List assertionTags) { Map lineNumberToAssertions = [:] as LinkedHashMap int codeIndex = 0 assertionTags.each { tag -> codeIndex = code.indexOf(tag, codeIndex) int lineNumber = code.substring(0, codeIndex).findAll("(?m)^").size() codeIndex += tag.size() String assertion = getAssertion(tag) lineNumberToAssertions.get(lineNumber, []) << assertion } return lineNumberToAssertions } private String getAssertion(String tag) { String tagInner = tag.substring(tag.indexOf(">")+1, tag.lastIndexOf("<")) String htmlAssertion = tagInner.replaceAll("(?m)^\\s*\\*", "") String assertion = htmlAssertion // TODO improve on this [nbsp:' ', gt:'>', lt:'<', quot:'"', apos:"'", at:'@', ndash:'-', amp:'&'].each { key, value -> assertion = assertion.replaceAll("(?i)&$key;", value) } return assertion } private List getTestMethods(Map lineNumberToAssertions, String filename) { List testMethods = lineNumberToAssertions.collect { lineNumber, assertions -> Character differentiator = 'a' assertions.collect { assertion -> String suffix = (assertions.size() > 1 ? "$lineNumber$differentiator" : lineNumber) differentiator++ getTestMethodCodeForAssertion(suffix, assertion, basename(filename)) } }.flatten() return testMethods } private String basename(String fullPath) { def path = new File(fullPath) def fullName = path.name fullName.substring(0, fullName.lastIndexOf(".")) } private String getTestMethodCodeForAssertion(String suffix, String assertion, String basename) { return """ public void testAssertionFrom${basename}Line$suffix() { byte[] bytes = [ ${(assertion.getBytes("UTF-8") as List).join(", ")} ] as byte[] Eval.me(new String(bytes, "UTF-8")) } """ } private String getTestCode(String testName, List testMethods) { return """ class $testName extends junit.framework.TestCase { """+testMethods.join("\r\n")+""" } """ } private Class createClass(String testCode) { return new GroovyClassLoader().parseClass(testCode) } } groovy-1.8.6/src/main/groovy/util/NodeBuilder.java0000644001501200150120000000327311627206700021453 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.util.ArrayList; import java.util.Map; /** * A helper class for creating nested trees of Node objects for * handling arbitrary data * * @author James Strachan * @version $Revision$ */ public class NodeBuilder extends BuilderSupport { public static NodeBuilder newInstance() { return new NodeBuilder(); } protected void setParent(Object parent, Object child) { } protected Object createNode(Object name) { return new Node(getCurrentNode(), name, new ArrayList()); } protected Object createNode(Object name, Object value) { return new Node(getCurrentNode(), name, value); } protected Object createNode(Object name, Map attributes) { return new Node(getCurrentNode(), name, attributes, new ArrayList()); } protected Object createNode(Object name, Map attributes, Object value) { return new Node(getCurrentNode(), name, attributes, value); } protected Node getCurrentNode() { return (Node) getCurrent(); } } groovy-1.8.6/src/main/groovy/util/IndentPrinter.java0000644001501200150120000001326411627206700022045 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; /** *

    A helper class for printing indented text. This can be used stand-alone or, more commonly, from Builders.

    * *

    By default, a PrintWriter to System.out is used as the Writer, but it is possible * to change the Writer by passing a new one as a constructor argument.

    * *

    Indention by default is 2 characters but can be changed by passing a * different value as a constructor argument.

    * *

    The following is an example usage. Note that within a "with" block you need to * specify a parameter name so that this.println is not called instead of IndentPrinter.println:

    *
     * new IndentPrinter(new PrintWriter(out)).with { p ->
     *     p.printIndent()
     *     p.println('parent1')
     *     p.incrementIndent()
     *     p.printIndent()
     *     p.println('child 1')
     *     p.printIndent()
     *     p.println('child 2')
     *     p.decrementIndent()
     *     p.printIndent()
     *     p.println('parent2')
     *     p.flush()
     * }
     * 
    *

    The above example prints this to standard output:

    *
     * parent1
     *   child 1
     *   child 2
     * parent2
     * 
    * @author James Strachan */ public class IndentPrinter { private int indentLevel; private String indent; private Writer out; private final boolean addNewlines; /** * Creates an IndentPrinter backed by a PrintWriter pointing to System.out, with an indent of two spaces. * * @see #IndentPrinter(Writer, String) */ public IndentPrinter() { this(new PrintWriter(System.out), " "); } /** * Creates an IndentPrinter backed by the supplied Writer, with an indent of two spaces. * * @param out Writer to output to * @see #IndentPrinter(Writer, String) */ public IndentPrinter(Writer out) { this(out, " "); } /** * Creates an IndentPrinter backed by the supplied Writer, * with a user-supplied String to be used for indenting. * * @param out Writer to output to * @param indent character(s) used to indent each line */ public IndentPrinter(Writer out, String indent) { this(out, indent, true); } /** * Creates an IndentPrinter backed by the supplied Writer, * with a user-supplied String to be used for indenting * and the ability to override newline handling. * * @param out Writer to output to * @param indent character(s) used to indent each line * @param addNewlines set to false to gobble all new lines (default true) */ public IndentPrinter(Writer out, String indent, boolean addNewlines) { this.addNewlines = addNewlines; if (out == null) { throw new IllegalArgumentException("Must specify a Writer"); } this.out = out; this.indent = indent; } /** * Prints a string followed by an end of line character. * * @param text String to be written */ public void println(String text) { try { out.write(text); println(); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } /** * Prints a string. * * @param text String to be written */ public void print(String text) { try { out.write(text); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } /** * Prints a character. * * @param c char to be written */ public void print(char c) { try { out.write(c); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } /** * Prints the current indent level. */ public void printIndent() { for (int i = 0; i < indentLevel; i++) { try { out.write(indent); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } } /** * Prints an end-of-line character (if enabled via addNewLines property). * Defaults to outputting a single '\n' character but by using a custom * Writer, e.g. PlatformLineWriter, you can get platform-specific * end-of-line characters. * * @see #IndentPrinter(Writer, String, boolean) */ public void println() { if (addNewlines) { try { out.write("\n"); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } } public void incrementIndent() { ++indentLevel; } public void decrementIndent() { --indentLevel; } public int getIndentLevel() { return indentLevel; } public void setIndentLevel(int indentLevel) { this.indentLevel = indentLevel; } public void flush() { try { out.flush(); } catch(IOException ioe) { throw new GroovyRuntimeException(ioe); } } }groovy-1.8.6/src/main/groovy/util/GroovyLog.java0000644001501200150120000000465611715031256021214 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.GroovyObjectSupport; import org.codehaus.groovy.runtime.DefaultGroovyMethods; // // FIXME: This class really isn't all that useful. It would be *much* better if there // was a simple log API in groovy to dynamically switch to the logging facade that // is actually installed. // /** * Represents an arbitrary logging service. By default this outputs to * System.out though derivations of this class could log to Jakarta Commons Logging * or log4j or JDK 1.5 logging etc * * @author James Strachan * @version $Revision$ */ @Deprecated public class GroovyLog extends GroovyObjectSupport { String prefix; /** * Factory method to create new instances */ public static GroovyLog newInstance(Class aClass) { return new GroovyLog(aClass); } public GroovyLog() { this(""); } public GroovyLog(Class type) { this(type.getName()); } public GroovyLog(Object obj) { this(obj.getClass()); } public GroovyLog(String prefix) { // // FIXME: This kinda sucks as a default... shouldn't tack on any [ or : muck // this.prefix = (prefix != null && prefix.length() > 0) ? "[" + prefix + ":" : "["; } public Object invokeMethod(String name, Object args) { if (args != null && args.getClass().isArray()) { args = DefaultGroovyMethods.join((Object[])args, ","); } // // FIXME: This kinda sucks as an output format, should probably ucase name and then // warp prefix in [] and then output the args. Basically what the SimpleLog // does in JCL. // System.out.println(prefix + name + "] " + args); return null; } } groovy-1.8.6/src/main/groovy/util/XmlNodePrinter.java0000644001501200150120000003276011645141222022171 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.xml.QName; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Prints a groovy.util.Node (as used with XmlParser) including all children in XML format. * Typical usage: *
     * def xml = '<html><head><title>Title</title></head><body><h1>Header</h1></body></html>'
     * def root = new XmlParser().parseText(xml)
     * new XmlNodePrinter(preserveWhitespace:true).print(root.body[0])
     * 
    * which when run produces this on stdout (or use your own PrintWriter to direct elsewhere): *
     * <body>
     *   <h1>Header</h1>
     * </body>
     * 
    * * @author Christian Stein * @see groovy.util.NodePrinter * @see groovy.xml.XmlUtil#serialize(Node) */ public class XmlNodePrinter { protected final IndentPrinter out; private String quote; private boolean namespaceAware = true; private boolean preserveWhitespace = false; private boolean expandEmptyElements = false; public XmlNodePrinter(PrintWriter out) { this(out, " "); } public XmlNodePrinter(PrintWriter out, String indent) { this(out, indent, "\""); } public XmlNodePrinter(PrintWriter out, String indent, String quote) { this(new IndentPrinter(out, indent), quote); } public XmlNodePrinter(IndentPrinter out) { this(out, "\""); } public XmlNodePrinter(IndentPrinter out, String quote) { if (out == null) { throw new IllegalArgumentException("Argument 'IndentPrinter out' must not be null!"); } this.out = out; this.quote = quote; } public XmlNodePrinter() { this(new PrintWriter(new OutputStreamWriter(System.out))); } public void print(Node node) { print(node, new NamespaceContext()); } /** * Check if namespace handling is enabled. * Defaults to true. * * @return true if namespace handling is enabled */ public boolean isNamespaceAware() { return namespaceAware; } /** * Enable and/or disable namespace handling. * * @param namespaceAware the new desired value */ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } /** * Check if whitespace preservation is enabled. * Defaults to false. * * @return true if whitespaces are honoured when printing simple text nodes */ public boolean isPreserveWhitespace() { return preserveWhitespace; } /** * Enable and/or disable preservation of whitespace. * * @param preserveWhitespace the new desired value */ public void setPreserveWhitespace(boolean preserveWhitespace) { this.preserveWhitespace = preserveWhitespace; } /** * Get Quote to use when printing attributes. * * @return the quote character */ public String getQuote() { return quote; } /** * Set Quote to use when printing attributes. * * @param quote the quote character */ public void setQuote(String quote) { this.quote = quote; } /** * Whether empty elements are expanded from <tagName/> to <tagName></tagName>. * * @return true, if empty elements will be represented by an opening tag * followed immediately by a closing tag. */ public boolean isExpandEmptyElements() { return expandEmptyElements; } /** * Whether empty elements are expanded from to . * * @param expandEmptyElements if true, empty * elements will be represented by an opening tag * followed immediately by a closing tag. * Defaults to false. */ public void setExpandEmptyElements(boolean expandEmptyElements) { this.expandEmptyElements = expandEmptyElements; } protected void print(Node node, NamespaceContext ctx) { /* * Handle empty elements like '
    ', ' or '
    . */ if (isEmptyElement(node)) { printLineBegin(); out.print("<"); out.print(getName(node)); if (ctx != null) { printNamespace(node, ctx); } printNameAttributes(node.attributes(), ctx); if (expandEmptyElements) { out.print(">"); } else { out.print("/>"); } printLineEnd(); out.flush(); return; } /* * Hook for extra processing, e.g. GSP tag element! */ if (printSpecialNode(node)) { out.flush(); return; } /* * Handle normal element like ... . */ Object value = node.value(); if (value instanceof List) { printName(node, ctx, true, isListOfSimple((List) value)); printList((List) value, ctx); printName(node, ctx, false, isListOfSimple((List) value)); out.flush(); return; } // treat as simple type - probably a String printName(node, ctx, true, preserveWhitespace); printSimpleItemWithIndent(value); printName(node, ctx, false, preserveWhitespace); out.flush(); } private boolean isListOfSimple(List value) { for (Object p : value) { if (p instanceof Node) return false; } return preserveWhitespace; } protected void printLineBegin() { out.printIndent(); } protected void printLineEnd() { printLineEnd(null); } protected void printLineEnd(String comment) { if (comment != null) { out.print(" "); } out.println(); out.flush(); } protected void printList(List list, NamespaceContext ctx) { out.incrementIndent(); for (Object value : list) { NamespaceContext context = new NamespaceContext(ctx); /* * If the current value is a node, recurse into that node. */ if (value instanceof Node) { print((Node) value, context); continue; } printSimpleItem(value); } out.decrementIndent(); } protected void printSimpleItem(Object value) { if (!preserveWhitespace) printLineBegin(); printEscaped(InvokerHelper.toString(value), false); if (!preserveWhitespace) printLineEnd(); } protected void printName(Node node, NamespaceContext ctx, boolean begin, boolean preserve) { if (node == null) { throw new NullPointerException("Node must not be null."); } Object name = node.name(); if (name == null) { throw new NullPointerException("Name must not be null."); } if (!preserve || begin) printLineBegin(); out.print("<"); if (!begin) { out.print("/"); } out.print(getName(node)); if (ctx != null) { printNamespace(node, ctx); } if (begin) { printNameAttributes(node.attributes(), ctx); } out.print(">"); if (!preserve || !begin) printLineEnd(); } protected boolean printSpecialNode(Node node) { return false; } protected void printNamespace(Object object, NamespaceContext ctx) { if (namespaceAware) { if (object instanceof Node) { printNamespace(((Node) object).name(), ctx); } else if (object instanceof QName) { QName qname = (QName) object; String namespaceUri = qname.getNamespaceURI(); if (namespaceUri != null) { String prefix = qname.getPrefix(); if (!ctx.isPrefixRegistered(prefix, namespaceUri)) { ctx.registerNamespacePrefix(prefix, namespaceUri); out.print(" "); out.print("xmlns"); if (prefix.length() > 0) { out.print(":"); out.print(prefix); } out.print("=" + quote); out.print(namespaceUri); out.print(quote); } } } } } protected void printNameAttributes(Map attributes, NamespaceContext ctx) { if (attributes == null || attributes.isEmpty()) { return; } for (Object p : attributes.entrySet()) { Map.Entry entry = (Map.Entry) p; out.print(" "); out.print(getName(entry.getKey())); out.print("="); Object value = entry.getValue(); out.print(quote); if (value instanceof String) { printEscaped((String) value, true); } else { printEscaped(InvokerHelper.toString(value), true); } out.print(quote); printNamespace(entry.getKey(), ctx); } } private boolean isEmptyElement(Node node) { if (node == null) { throw new IllegalArgumentException("Node must not be null!"); } if (!node.children().isEmpty()) { return false; } return node.text().length() == 0; } private String getName(Object object) { if (object instanceof String) { return (String) object; } else if (object instanceof QName) { QName qname = (QName) object; if (!namespaceAware) { return qname.getLocalPart(); } return qname.getQualifiedName(); } else if (object instanceof Node) { Object name = ((Node) object).name(); return getName(name); } return object.toString(); } private void printSimpleItemWithIndent(Object value) { if (!preserveWhitespace) out.incrementIndent(); printSimpleItem(value); if (!preserveWhitespace) out.decrementIndent(); } // For ' and " we only escape if needed. As far as XML is concerned, // we could always escape if we wanted to. private void printEscaped(String s, boolean isAttributeValue) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '<': out.print("<"); break; case '>': out.print(">"); break; case '&': out.print("&"); break; case '\'': if (quote.equals("'")) out.print("'"); else out.print(c); break; case '"': if (quote.equals("\"")) out.print("""); else out.print(c); break; case '\n': if (isAttributeValue) out.print(" "); else out.print(c); break; case '\r': if (isAttributeValue) out.print(" "); else out.print(c); break; default: out.print(c); } } } protected class NamespaceContext { private final Map namespaceMap; public NamespaceContext() { namespaceMap = new HashMap(); } public NamespaceContext(NamespaceContext context) { this(); namespaceMap.putAll(context.namespaceMap); } public boolean isPrefixRegistered(String prefix, String uri) { return namespaceMap.containsKey(prefix) && namespaceMap.get(prefix).equals(uri); } public void registerNamespacePrefix(String prefix, String uri) { if (!isPrefixRegistered(prefix, uri)) { namespaceMap.put(prefix, uri); } } public String getNamespace(String prefix) { Object uri = namespaceMap.get(prefix); return (uri == null) ? null : uri.toString(); } } } groovy-1.8.6/src/main/groovy/util/slurpersupport/0000755001501200150120000000000011713765676021562 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/util/slurpersupport/Attributes.java0000644001501200150120000001066311627206700024537 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.Writer; import java.util.Map; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * Lazy evaluated representation of a node's attributes. * * @author John Wilson */ class Attributes extends NodeChildren { final String attributeName; /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespacePrefix the namespace prefix if any * @param namespaceTagHints the known tag to namespace mappings */ public Attributes(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) { super(parent, name, namespacePrefix, namespaceTagHints); this.attributeName = this.name.substring(1); } /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespaceTagHints the known tag to namespace mappings */ public Attributes(final GPathResult parent, final String name, final Map namespaceTagHints) { this(parent, name, "*", namespaceTagHints); } public String name() { // this name contains @name we need to return name return this.name.substring(1); } public Iterator childNodes() { throw new GroovyRuntimeException("Can't get the child nodes on a GPath expression selecting attributes: ...." + this.parent.name() + "." + name() + ".childNodes()"); } public Iterator iterator() { return new NodeIterator(nodeIterator()) { protected Object getNextNode(final Iterator iter) { while (iter.hasNext()) { final Object next = iter.next(); if (next instanceof Attribute) { return next; } else { final String value = (String) ((Node) next).attributes().get(Attributes.this.attributeName); if (value != null) { return new Attribute(Attributes.this.name, value, new NodeChild((Node) next, Attributes.this.parent.parent, "", Attributes.this.namespaceTagHints), "", Attributes.this.namespaceTagHints); } } } return null; } }; } public Iterator nodeIterator() { return this.parent.nodeIterator(); } public GPathResult parents() { return super.parents(); } public String text() { final StringBuffer buf = new StringBuffer(); final Iterator iter = iterator(); while (iter.hasNext()) { buf.append(iter.next()); } return buf.toString(); } public List list() { final Iterator iter = iterator(); final List result = new ArrayList(); while (iter.hasNext()) { result.add(iter.next()); } return result; } public GPathResult findAll(final Closure closure) { return new FilteredAttributes(this, closure, this.namespaceTagHints); } public Writer writeTo(final Writer out) throws IOException { out.write(text()); return out; } public void build(final GroovyObject builder) { builder.getProperty("mkp"); builder.invokeMethod("yield", new Object[]{text()}); } } groovy-1.8.6/src/main/groovy/util/slurpersupport/FilteredAttributes.java0000644001501200150120000000374011627206700026214 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import groovy.lang.Closure; /** * Lazy evaluated representation of a node's attributes filtered by a Closure. * * @author John Wilson */ public class FilteredAttributes extends Attributes { private final Closure closure; /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param closure the Closure to use to filter the attributes * @param namespaceTagHints the known tag to namespace mappings */ public FilteredAttributes(final GPathResult parent, final Closure closure, final Map namespaceTagHints) { super(parent, parent.name, namespaceTagHints); this.closure = closure; } public Iterator nodeIterator() { return new NodeIterator(this.parent.iterator()) { protected Object getNextNode(final Iterator iter) { while (iter.hasNext()) { final Object node = iter.next(); if (DefaultTypeTransformation.castToBoolean(FilteredAttributes.this.closure.call(new Object[]{node}))) { return node; } } return null; } }; } } groovy-1.8.6/src/main/groovy/util/slurpersupport/package.html0000644001501200150120000000022711627206700024022 0ustar miguelmiguel package groovy.util.slurpersupport.*

    Helper classes for XmlSlurper.

    groovy-1.8.6/src/main/groovy/util/slurpersupport/NoChildren.java0000644001501200150120000001000711627206700024426 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; /** * Lazy evaluated representation of a GPath expression returning no children. * * @author John Wilson */ public class NoChildren extends GPathResult { /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespaceTagHints the known tag to namespace mappings */ public NoChildren(final GPathResult parent, final String name, final Map namespaceTagHints) { super(parent, name, "*", namespaceTagHints); } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#size() */ public int size() { return 0; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#text() */ public String text() { return ""; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#parents() */ public GPathResult parents() { // TODO Auto-generated method stub throw new GroovyRuntimeException("parents() not implemented yet"); } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#childNodes() */ public Iterator childNodes() { return iterator(); } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#iterator() */ public Iterator iterator() { return new Iterator() { public boolean hasNext() { return false; } public Object next() { return null; } public void remove() { throw new UnsupportedOperationException(); } }; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#find(groovy.lang.Closure) */ public GPathResult find(final Closure closure) { return this; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#findAll(groovy.lang.Closure) */ public GPathResult findAll(final Closure closure) { return this; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.GPathResult#nodeIterator() */ public Iterator nodeIterator() { return iterator(); } /* (non-Javadoc) * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(final Writer out) throws IOException { return out; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.markup.Buildable#build(groovy.lang.GroovyObject) */ public void build(final GroovyObject builder) { } protected void replaceNode(final Closure newValue) { // No elements match GPath expression - do nothing } protected void replaceBody(final Object newValue) { // No elements match GPath expression - do nothing } protected void appendNode(final Object newValue) { // TODO consider creating an element for this } public boolean asBoolean() { return false; } } groovy-1.8.6/src/main/groovy/util/slurpersupport/NodeIterator.java0000644001501200150120000000311211627206700024777 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import java.util.Iterator; /** * Helper class for iterating through nodes. * * @author John Wilson */ public abstract class NodeIterator implements Iterator { private static final Object DELAYED_INIT = new Object(); private final Iterator iter; private Object nextNode; public NodeIterator(final Iterator iter) { this.iter = iter; this.nextNode = DELAYED_INIT; } private void initNextNode(){ if (nextNode==DELAYED_INIT) nextNode = getNextNode(iter); } public boolean hasNext() { initNextNode(); return this.nextNode != null; } public Object next() { initNextNode(); try { return this.nextNode; } finally { this.nextNode = getNextNode(this.iter); } } public void remove() { throw new UnsupportedOperationException(); } protected abstract Object getNextNode(final Iterator iter); } groovy-1.8.6/src/main/groovy/util/slurpersupport/ReplacementNode.java0000644001501200150120000000240111627206700025445 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.GroovyObject; import groovy.lang.Writable; import java.io.IOException; import java.io.Writer; import java.util.Map; /** * Helper base class used for lazy updates. * * @author John Wilson */ public abstract class ReplacementNode implements Buildable, Writable { public abstract void build(GroovyObject builder, Map namespaceMap, Map namespaceTagHints); public void build(final GroovyObject builder) { build(builder, null, null); } public Writer writeTo(final Writer out) throws IOException { return out; } } groovy-1.8.6/src/main/groovy/util/slurpersupport/NodeChildren.java0000644001501200150120000002074011627206700024744 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Lazy evaluated representation of child nodes. * * @author John Wilson */ class NodeChildren extends GPathResult { private int size = -1; /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespacePrefix the namespace prefix if any * @param namespaceTagHints the known tag to namespace mappings */ public NodeChildren(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) { super(parent, name, namespacePrefix, namespaceTagHints); } /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespaceTagHints the known tag to namespace mappings */ public NodeChildren(final GPathResult parent, final String name, final Map namespaceTagHints) { this(parent, name, "*", namespaceTagHints); } /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param namespaceTagHints the known tag to namespace mappings */ public NodeChildren(final GPathResult parent, final Map namespaceTagHints) { this(parent, "*", namespaceTagHints); } public Iterator childNodes() { return new Iterator() { private final Iterator iter = parent.childNodes(); private Iterator childIter = nextChildIter(); /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return childIter != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public Object next() { while (childIter != null) { try { if (childIter.hasNext()) { return childIter.next(); } } finally { if (!childIter.hasNext()) { childIter = nextChildIter(); } } } return null; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } private Iterator nextChildIter() { while (iter.hasNext()) { final Node node = (Node) iter.next(); if (name.equals(node.name()) || name.equals("*")) { final Iterator result = node.childNodes(); if (result.hasNext()) { if ("*".equals(namespacePrefix) || ("".equals(namespacePrefix) && "".equals(node.namespaceURI())) || node.namespaceURI().equals(namespaceMap.get(namespacePrefix))) { return result; } } } } return null; } }; } public Iterator iterator() { return new Iterator() { final Iterator iter = nodeIterator(); public boolean hasNext() { return iter.hasNext(); } public Object next() { return new NodeChild((Node) iter.next(), parent, namespaceTagHints); } public void remove() { throw new UnsupportedOperationException(); } }; } public Iterator nodeIterator() { if ("*".equals(name)) { return parent.childNodes(); } else { return new NodeIterator(parent.childNodes()) { /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.NodeIterator#getNextNode(java.util.Iterator) */ protected Object getNextNode(Iterator iter) { while (iter.hasNext()) { final Node node = (Node) iter.next(); if (name.equals(node.name())) { if ("*".equals(namespacePrefix) || ("".equals(namespacePrefix) && "".equals(node.namespaceURI())) || node.namespaceURI().equals(namespaceMap.get(namespacePrefix))) { return node; } } } return null; } }; } } public GPathResult parents() { // TODO Auto-generated method stub throw new GroovyRuntimeException("parents() not implemented yet"); } public synchronized int size() { if (this.size == -1) { final Iterator iter = iterator(); this.size = 0; while (iter.hasNext()) { iter.next(); this.size++; } } return this.size; } public String text() { final StringBuffer buf = new StringBuffer(); final Iterator iter = nodeIterator(); while (iter.hasNext()) { buf.append(((Node) iter.next()).text()); } return buf.toString(); } public GPathResult find(final Closure closure) { final Iterator iter = iterator(); while (iter.hasNext()) { final Object node = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{node}))) { return (GPathResult) node; } } return new NoChildren(this, this.name, namespaceTagHints); } public GPathResult findAll(final Closure closure) { return new FilteredNodeChildren(this, closure, namespaceTagHints); } public void build(final GroovyObject builder) { final Iterator iter = nodeIterator(); while (iter.hasNext()) { final Object next = iter.next(); if (next instanceof Buildable) { ((Buildable) next).build(builder); } else { ((Node) next).build(builder, namespaceMap, namespaceTagHints); } } } /* (non-Javadoc) * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(final Writer out) throws IOException { final Iterator iter = nodeIterator(); while (iter.hasNext()) { ((Node) iter.next()).writeTo(out); } return out; } protected void replaceNode(final Closure newValue) { final Iterator iter = iterator(); while (iter.hasNext()) { final NodeChild result = (NodeChild) iter.next(); result.replaceNode(newValue); } } protected void replaceBody(final Object newValue) { final Iterator iter = iterator(); while (iter.hasNext()) { final NodeChild result = (NodeChild) iter.next(); result.replaceBody(newValue); } } protected void appendNode(final Object newValue) { final Iterator iter = iterator(); while (iter.hasNext()) { final NodeChild result = (NodeChild) iter.next(); result.appendNode(newValue); } } } groovy-1.8.6/src/main/groovy/util/slurpersupport/Attribute.java0000644001501200150120000000720411627206700024351 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Lazy evaluated representation of a node attribute. * * @author John Wilson */ public class Attribute extends GPathResult { private final String value; /** * @param name of the attribute * @param value of the attribute * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param namespacePrefix the namespace prefix if any * @param namespaceTagHints the known tag to namespace mappings */ public Attribute(final String name, final String value, final GPathResult parent, final String namespacePrefix, final Map namespaceTagHints) { super(parent, name, namespacePrefix, namespaceTagHints); this.value = value; } public String name() { // this name contains @name we need to return name return this.name.substring(1); } public int size() { return 1; } public String text() { return this.value; } public GPathResult parents() { // TODO Auto-generated method stub throw new GroovyRuntimeException("parents() not implemented yet"); } public Iterator childNodes() { throw new GroovyRuntimeException("can't call childNodes() in the attribute " + this.name); } public Iterator iterator() { return nodeIterator(); } public GPathResult find(final Closure closure) { if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this}))) { return this; } else { return new NoChildren(this, "", this.namespaceTagHints); } } public GPathResult findAll(final Closure closure) { return find(closure); } public Iterator nodeIterator() { return new Iterator() { private boolean hasNext = true; public boolean hasNext() { return this.hasNext; } public Object next() { try { return (this.hasNext) ? Attribute.this : null; } finally { this.hasNext = false; } } public void remove() { throw new UnsupportedOperationException(); } }; } public Writer writeTo(final Writer out) throws IOException { out.write(this.value); return out; } public void build(final GroovyObject builder) { builder.getProperty("mkp"); builder.invokeMethod("yield", new Object[]{this.value}); } protected void replaceNode(final Closure newValue) { } protected void replaceBody(final Object newValue) { } protected void appendNode(final Object newValue) { } } groovy-1.8.6/src/main/groovy/util/slurpersupport/FilteredNodeChildren.java0000644001501200150120000000566611627206700026435 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import groovy.lang.Closure; /** * Lazy evaluated representation of child nodes filtered by a Closure. * * @author John Wilson */ public class FilteredNodeChildren extends NodeChildren { private final Closure closure; /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param closure the Closure to use to filter the nodes * @param namespaceTagHints the known tag to namespace mappings */ public FilteredNodeChildren(final GPathResult parent, final Closure closure, final Map namespaceTagHints) { super(parent, parent.name, namespaceTagHints); this.closure = closure; } public Iterator iterator() { return new Iterator() { final Iterator iter = FilteredNodeChildren.this.parent.iterator(); Object next = null; public boolean hasNext() { while (this.iter.hasNext()) { final Object childNode = this.iter.next(); if (closureYieldsTrueForNode(childNode)) { this.next = childNode; return true; } } return false; } public Object next() { return this.next; } public void remove() { throw new UnsupportedOperationException(); } }; } public Iterator nodeIterator() { return new NodeIterator(this.parent.nodeIterator()) { protected Object getNextNode(final Iterator iter) { while (iter.hasNext()) { final Object node = iter.next(); if (closureYieldsTrueForNode(new NodeChild((Node) node, FilteredNodeChildren.this.parent, FilteredNodeChildren.this.namespaceTagHints))) { return node; } } return null; } }; } private boolean closureYieldsTrueForNode(Object childNode) { return DefaultTypeTransformation.castToBoolean(FilteredNodeChildren.this.closure.call(new Object[]{childNode})); } } groovy-1.8.6/src/main/groovy/util/slurpersupport/NodeChild.java0000644001501200150120000001123611627206700024237 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Lazy evaluated representation of a child node. * * @author John Wilson */ public class NodeChild extends GPathResult { private final Node node; /** * @param node a node * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param namespacePrefix the namespace prefix if any * @param namespaceTagHints the known tag to namespace mappings */ public NodeChild(final Node node, final GPathResult parent, final String namespacePrefix, final Map namespaceTagHints) { super(parent, node.name(), namespacePrefix, namespaceTagHints); this.node = node; } /** * @param node a node * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param namespaceTagHints the known tag to namespace mappings */ public NodeChild(final Node node, final GPathResult parent, final Map namespaceTagHints) { this(node, parent, "*", namespaceTagHints); } public int size() { return 1; } public String text() { return this.node.text(); } public String namespaceURI() { return this.node.namespaceURI(); } public GPathResult parents() { // TODO Auto-generated method stub throw new GroovyRuntimeException("parents() not implemented yet"); } public Iterator iterator() { return new Iterator() { private boolean hasNext = true; public boolean hasNext() { return this.hasNext; } public Object next() { try { return (this.hasNext) ? NodeChild.this : null; } finally { this.hasNext = false; } } public void remove() { throw new UnsupportedOperationException(); } }; } public Iterator nodeIterator() { return new Iterator() { private boolean hasNext = true; public boolean hasNext() { return this.hasNext; } public Object next() { try { return (this.hasNext) ? NodeChild.this.node : null; } finally { this.hasNext = false; } } public void remove() { throw new UnsupportedOperationException(); } }; } public Object getAt(final int index) { if (index == 0) { return node; } else { throw new ArrayIndexOutOfBoundsException(index); } } public Map attributes() { return this.node.attributes(); } public Iterator childNodes() { return this.node.childNodes(); } public GPathResult find(final Closure closure) { if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this.node}))) { return this; } else { return new NoChildren(this, "", this.namespaceTagHints); } } public GPathResult findAll(final Closure closure) { return find(closure); } public void build(final GroovyObject builder) { this.node.build(builder, this.namespaceMap, this.namespaceTagHints); } public Writer writeTo(final Writer out) throws IOException { return this.node.writeTo(out); } protected void replaceNode(final Closure newValue) { this.node.replaceNode(newValue, this); } protected void replaceBody(final Object newValue) { this.node.replaceBody(newValue); } protected void appendNode(final Object newValue) { this.node.appendNode(newValue, this); } } groovy-1.8.6/src/main/groovy/util/slurpersupport/GPathResult.java0000644001501200150120000003425711627206700024620 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GString; import groovy.lang.GroovyObject; import groovy.lang.GroovyObjectSupport; import groovy.lang.IntRange; import groovy.lang.MetaClass; import groovy.lang.Writable; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.codehaus.groovy.runtime.DefaultGroovyMethods; /** * Base class for representing lazy evaluated GPath expressions. * * @author John Wilson */ public abstract class GPathResult extends GroovyObjectSupport implements Writable, Buildable { protected final GPathResult parent; protected final String name; protected final String namespacePrefix; protected final Map namespaceMap = new HashMap(); protected final Map namespaceTagHints; /** * @param parent the GPathResult prior to the application of the expression creating this GPathResult * @param name if the GPathResult corresponds to something with a name, e.g. a node * @param namespacePrefix the namespace prefix if any * @param namespaceTagHints the known tag to namespace mappings */ public GPathResult(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) { if (parent == null) { // we are the top of the tree this.parent = this; this.namespaceMap.put("xml", "http://www.w3.org/XML/1998/namespace"); // The XML namespace is always defined } else { this.parent = parent; this.namespaceMap.putAll(parent.namespaceMap); } this.name = name; this.namespacePrefix = namespacePrefix; this.namespaceTagHints = namespaceTagHints; setMetaClass(getMetaClass()); // wrap the standard MetaClass with the delegate } @Override public void setMetaClass(final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { @Override public Object getAttribute(final Object object, final String attribute) { return GPathResult.this.getProperty("@" + attribute); } @Override public void setAttribute(final Object object, final String attribute, final Object newValue) { GPathResult.this.setProperty("@" + attribute, newValue); } }; super.setMetaClass(newMetaClass); } public Object getProperty(final String property) { if ("..".equals(property)) { return parent(); } else if ("*".equals(property)) { return children(); } else if ("**".equals(property)) { return depthFirst(); } else if (property.startsWith("@")) { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new Attributes(this, "@" + property.substring(i + 1), property.substring(1, i), this.namespaceTagHints); } else { return new Attributes(this, property, this.namespaceTagHints); } } else { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new NodeChildren(this, property.substring(i + 1), property.substring(0, i), this.namespaceTagHints); } else { return new NodeChildren(this, property, this.namespaceTagHints); } } } public void setProperty(final String property, final Object newValue) { if (property.startsWith("@")) { if (newValue instanceof String || newValue instanceof GString) { final Iterator iter = iterator(); while (iter.hasNext()) { final NodeChild child = (NodeChild) iter.next(); child.attributes().put(property.substring(1), newValue); } } } else { final GPathResult result = new NodeChildren(this, property, this.namespaceTagHints); if (newValue instanceof Map) { for (Object o : ((Map) newValue).entrySet()) { final Map.Entry entry = (Map.Entry) o; result.setProperty("@" + entry.getKey(), entry.getValue()); } } else { if (newValue instanceof Closure) { result.replaceNode((Closure) newValue); } else { result.replaceBody(newValue); } } } } public Object leftShift(final Object newValue) { appendNode(newValue); return this; } public Object plus(final Object newValue) { this.replaceNode(new Closure(this) { public void doCall(Object[] args) { final GroovyObject delegate = (GroovyObject)getDelegate(); delegate.getProperty("mkp"); delegate.invokeMethod("yield", args); delegate.getProperty("mkp"); delegate.invokeMethod("yield", new Object[]{newValue}); } }); return this; } protected abstract void replaceNode(Closure newValue); protected abstract void replaceBody(Object newValue); protected abstract void appendNode(Object newValue); public String name() { return this.name; } public GPathResult parent() { return this.parent; } public GPathResult children() { return new NodeChildren(this, this.namespaceTagHints); } public String lookupNamespace(final String prefix) { return this.namespaceTagHints.get(prefix); } public String toString() { return text(); } public Integer toInteger() { return DefaultGroovyMethods.toInteger(text()); } public Long toLong() { return DefaultGroovyMethods.toLong(text()); } public Float toFloat() { return DefaultGroovyMethods.toFloat(text()); } public Double toDouble() { return DefaultGroovyMethods.toDouble(text()); } public BigDecimal toBigDecimal() { return DefaultGroovyMethods.toBigDecimal(text()); } public BigInteger toBigInteger() { return DefaultGroovyMethods.toBigInteger(text()); } public URL toURL() throws MalformedURLException { return DefaultGroovyMethods.toURL(text()); } public URI toURI() throws URISyntaxException { return DefaultGroovyMethods.toURI(text()); } public Boolean toBoolean() { return DefaultGroovyMethods.toBoolean(text()); } public GPathResult declareNamespace(final Map newNamespaceMapping) { this.namespaceMap.putAll(newNamespaceMapping); return this; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return text().equals(obj.toString()); } public Object getAt(final int index) { if (index < 0) { // calculate whole list in this case // recommend avoiding -ve's as this is obviously not as efficient List list = list(); int adjustedIndex = index + list.size(); if (adjustedIndex >= 0 && adjustedIndex < list.size()) return list.get(adjustedIndex); } else { final Iterator iter = iterator(); int count = 0; while (iter.hasNext()) { if (count++ == index) { return iter.next(); } else { iter.next(); } } } return new NoChildren(this, this.name, this.namespaceTagHints); } public Object getAt(final IntRange range) { return DefaultGroovyMethods.getAt(list(), range); } public void putAt(final int index, final Object newValue) { final GPathResult result = (GPathResult)getAt(index); if (newValue instanceof Closure) { result.replaceNode((Closure)newValue); } else { result.replaceBody(newValue); } } public Iterator depthFirst() { return new Iterator() { private final List list = new LinkedList(); private final Stack stack = new Stack(); private Iterator iter = iterator(); private GPathResult next = getNextByDepth(); public boolean hasNext() { return this.next != null; } public Object next() { try { return this.next; } finally { this.next = getNextByDepth(); } } public void remove() { throw new UnsupportedOperationException(); } private GPathResult getNextByDepth() { while (this.iter.hasNext()) { final GPathResult node = (GPathResult) this.iter.next(); this.list.add(node); this.stack.push(this.iter); this.iter = node.children().iterator(); } if (this.list.isEmpty()) { return null; } else { GPathResult result = (GPathResult) this.list.get(0); this.list.remove(0); this.iter = (Iterator) this.stack.pop(); return result; } } }; } /** * An iterator useful for traversing XML documents/fragments in breadth-first order. * * @return Iterator the iterator of GPathResult objects */ public Iterator breadthFirst() { return new Iterator() { private final List list = new LinkedList(); private Iterator iter = iterator(); private GPathResult next = getNextByBreadth(); public boolean hasNext() { return this.next != null; } public Object next() { try { return this.next; } finally { this.next = getNextByBreadth(); } } public void remove() { throw new UnsupportedOperationException(); } private GPathResult getNextByBreadth() { List children = new ArrayList(); while (this.iter.hasNext() || !children.isEmpty()) { if (this.iter.hasNext()) { final GPathResult node = (GPathResult) this.iter.next(); this.list.add(node); this.list.add(this.iter); children.add(node.children()); } else { List nextLevel = new ArrayList(); for (Object child : children) { GPathResult next = (GPathResult) child; Iterator iterator = next.iterator(); while (iterator.hasNext()) { nextLevel.add(iterator.next()); } } this.iter = nextLevel.iterator(); children = new ArrayList(); } } if (this.list.isEmpty()) { return null; } else { GPathResult result = (GPathResult) this.list.get(0); this.list.remove(0); this.iter = (Iterator) this.list.get(0); this.list.remove(0); return result; } } }; } public List list() { final Iterator iter = nodeIterator(); final List result = new LinkedList(); while (iter.hasNext()) { result.add(new NodeChild((Node) iter.next(), this.parent, this.namespacePrefix, this.namespaceTagHints)); } return result; } public boolean isEmpty() { return size() == 0; } public Closure getBody() { return new Closure(this.parent(),this) { public void doCall(Object[] args) { final GroovyObject delegate = (GroovyObject)getDelegate(); final GPathResult thisObject = (GPathResult)getThisObject(); Node node = (Node)thisObject.getAt(0); List children = node.children(); for (Object child : children) { delegate.getProperty("mkp"); if (child instanceof Node) { delegate.invokeMethod("yield", new Object[]{new NodeChild((Node) child, thisObject, "*", null)}); } else { delegate.invokeMethod("yield", new Object[]{child}); } } } }; } public abstract int size(); public abstract String text(); public abstract GPathResult parents(); public abstract Iterator childNodes(); public abstract Iterator iterator(); public abstract GPathResult find(Closure closure); public abstract GPathResult findAll(Closure closure); public abstract Iterator nodeIterator(); } groovy-1.8.6/src/main/groovy/util/slurpersupport/Node.java0000644001501200150120000002575011713765676023323 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.Writable; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; /** * Represents a node. * * @author John Wilson */ public class Node implements Writable { private final String name; private final Map attributes; private final Map attributeNamespaces; private final String namespaceURI; private final List children = new LinkedList(); private final Stack replacementNodeStack = new Stack(); /** * @param parent the parent node * @param name the name for the node * @param attributes the attributes for the node * @param attributeNamespaces the namespace mappings for attributes * @param namespaceURI the namespace URI if any */ public Node(final Node parent, final String name, final Map attributes, final Map attributeNamespaces, final String namespaceURI) { this.name = name; this.attributes = attributes; this.attributeNamespaces = attributeNamespaces; this.namespaceURI = namespaceURI; } public String name() { return this.name; } public String namespaceURI() { return this.namespaceURI; } public Map attributes() { return this.attributes; } public List children() { return this.children; } public void addChild(final Object child) { this.children.add(child); } public void replaceNode(final Closure replacementClosure, final GPathResult result) { this.replacementNodeStack.push(new ReplacementNode() { public void build(final GroovyObject builder, final Map namespaceMap, final Map namespaceTagHints) { final Closure c = (Closure) replacementClosure.clone(); Node.this.replacementNodeStack.pop(); // disable the replacement whilst the closure is being executed c.setDelegate(builder); c.call(new Object[]{result}); Node.this.replacementNodeStack.push(this); } }); } protected void replaceBody(final Object newValue) { this.children.clear(); this.children.add(newValue); } protected void appendNode(final Object newValue, final GPathResult result) { if (newValue instanceof Closure) { this.children.add(new ReplacementNode() { public void build(final GroovyObject builder, final Map namespaceMap, final Map namespaceTagHints) { final Closure c = (Closure) ((Closure) newValue).clone(); c.setDelegate(builder); c.call(new Object[]{result}); } }); } else { this.children.add(newValue); } } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.Node#text() */ public String text() { final StringBuilder sb = new StringBuilder(); for (Object child : this.children) { if (child instanceof Node) { sb.append(((Node) child).text()); } else { sb.append(child); } } return sb.toString(); } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.Node#childNodes() */ public Iterator childNodes() { return new Iterator() { private final Iterator iter = Node.this.children.iterator(); private Object nextElementNodes = getNextElementNodes(); public boolean hasNext() { return this.nextElementNodes != null; } public Object next() { try { return this.nextElementNodes; } finally { this.nextElementNodes = getNextElementNodes(); } } public void remove() { throw new UnsupportedOperationException(); } private Object getNextElementNodes() { while (iter.hasNext()) { final Object node = iter.next(); if (node instanceof Node) { return node; } } return null; } }; } /* (non-Javadoc) * @see org.codehaus.groovy.sandbox.util.slurpersupport.Node#writeTo(java.io.Writer) */ public Writer writeTo(final Writer out) throws IOException { if (this.replacementNodeStack.empty()) { for (Object child : this.children) { if (child instanceof Writable) { ((Writable) child).writeTo(out); } else { out.write(child.toString()); } } return out; } else { return ((Writable) this.replacementNodeStack.peek()).writeTo(out); } } public void build(final GroovyObject builder, final Map namespaceMap, final Map namespaceTagHints) { if (this.replacementNodeStack.empty()) { final Closure rest = new Closure(null) { public Object doCall(final Object o) { buildChildren(builder, namespaceMap, namespaceTagHints); return null; } }; if (this.namespaceURI.length() == 0 && this.attributeNamespaces.isEmpty()) { builder.invokeMethod(this.name, new Object[]{this.attributes, rest}); } else { final List newTags = new LinkedList(); builder.getProperty("mkp"); final List namespaces = (List) builder.invokeMethod("getNamespaces", new Object[]{}); final Map current = (Map) namespaces.get(0); final Map pending = (Map) namespaces.get(1); if (this.attributeNamespaces.isEmpty()) { builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder)); builder.invokeMethod(this.name, new Object[]{this.attributes, rest}); } else { final Map attributesWithNamespaces = new HashMap(this.attributes); for (Object key : this.attributes.keySet()) { final Object attributeNamespaceURI = this.attributeNamespaces.get(key); if (attributeNamespaceURI != null) { attributesWithNamespaces.put(getTagFor(attributeNamespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder) + "$" + key, attributesWithNamespaces.remove(key)); } } builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder)); builder.invokeMethod(this.name, new Object[]{attributesWithNamespaces, rest}); } // remove the new tags we had to define for this element if (!newTags.isEmpty()) { final Iterator iter = newTags.iterator(); do { pending.remove(iter.next()); } while (iter.hasNext()); } } } else { ((ReplacementNode) this.replacementNodeStack.peek()).build(builder, namespaceMap, namespaceTagHints); } } private static String getTagFor(final Object namespaceURI, final Map current, final Map pending, final Map local, final Map tagHints, final List newTags, final GroovyObject builder) { String tag = findNamespaceTag(pending, namespaceURI); // look in the namespaces whose declaration has already been emitted if (tag == null) { tag = findNamespaceTag(current, namespaceURI); // look in the namespaces who will be declared at the next element if (tag == null) { // we have to declare the namespace - choose a tag tag = findNamespaceTag(local, namespaceURI); // If the namespace has been declared in the GPath expression use that tag if (tag == null || tag.length() == 0) { tag = findNamespaceTag(tagHints, namespaceURI); // If the namespace has been used in the parse document use that tag } if (tag == null || tag.length() == 0) { // otherwise make up a new tag and check it has not been used before int suffix = 0; do { final String possibleTag = "tag" + suffix++; if (!pending.containsKey(possibleTag) && !current.containsKey(possibleTag) && !local.containsKey(possibleTag)) { tag = possibleTag; } } while (tag == null); } final Map newNamespace = new HashMap(); newNamespace.put(tag, namespaceURI); builder.getProperty("mkp"); builder.invokeMethod("declareNamespace", new Object[]{newNamespace}); newTags.add(tag); } } return tag; } private static String findNamespaceTag(final Map tagMap, final Object namespaceURI) { if (tagMap.containsValue(namespaceURI)) { for (Object o : tagMap.entrySet()) { final Map.Entry entry = (Map.Entry) o; if (namespaceURI.equals(entry.getValue())) { return (String) entry.getKey(); } } } return null; } private void buildChildren(final GroovyObject builder, final Map namespaceMap, final Map namespaceTagHints) { for (Object child : this.children) { if (child instanceof Node) { ((Node) child).build(builder, namespaceMap, namespaceTagHints); } else if (child instanceof Buildable) { ((Buildable) child).build(builder); } else { builder.getProperty("mkp"); builder.invokeMethod("yield", new Object[]{child}); } } } } groovy-1.8.6/src/main/groovy/util/FileNameByRegexFinder.groovy0000644001501200150120000000246011715031256023756 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util /** * Find files according to a base directory and an includes and excludes pattern. * The include and exclude patterns conform to regex conventions. * * @author Dierk Koenig * @author Paul King */ class FileNameByRegexFinder implements IFileNameFinder{ List getFileNames(String basedir, String pattern){ getFileNames(basedir, pattern, "") } List getFileNames(String basedir, String pattern, String excludesPattern){ def result = [] new File(basedir).eachFileRecurse { if (it.path =~ pattern && (!excludesPattern || !(it.path =~ excludesPattern))) { result << it.absolutePath } } return result } } groovy-1.8.6/src/main/groovy/util/OrderBy.java0000644001501200150120000000465011707612044020626 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import org.codehaus.groovy.runtime.NumberAwareComparator; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * A helper class for sorting objects via a closure to return the field * or operation on which to sort. * * @author James Strachan * @version $Revision$ */ public class OrderBy implements Comparator { private final List closures; private boolean equalityCheck; private final NumberAwareComparator numberAwareComparator = new NumberAwareComparator(); public OrderBy() { this.closures = new ArrayList(); } public OrderBy(Closure closure) { this(); closures.add(closure); } public OrderBy(List closures) { this.closures = closures; } public void add(Closure closure) { closures.add(closure); } public int compare(T object1, T object2) { for (Closure closure : closures) { Object value1 = closure.call(object1); Object value2 = closure.call(object2); int result; if (!equalityCheck || (value1 instanceof Comparable && value2 instanceof Comparable)) { result = numberAwareComparator.compare(value1, value2); } else { result = DefaultTypeTransformation.compareEqual(value1, value2) ? 0 : -1; } if (result == 0) continue; return result; } return 0; } public boolean isEqualityCheck() { return equalityCheck; } public void setEqualityCheck(boolean equalityCheck) { this.equalityCheck = equalityCheck; } } groovy-1.8.6/src/main/groovy/util/package.html0000644001501200150120000000035211627206700020670 0ustar miguelmiguel package groovy.util.*

    Various Groovy utilities for working with nodes, builders, logging, JUnit test cases, text expressions, Ant tasks or JMX MBeans.

    groovy-1.8.6/src/main/groovy/util/ConfigObject.groovy0000644001501200150120000002006711715031256022217 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util import org.codehaus.groovy.syntax.Types /** * A ConfigObject at a simple level is a Map that creates configuration entries (other ConfigObjects) when referencing them. * This means that navigating to foo.bar.stuff will not return null but nested ConfigObjects which are of course empty maps * The Groovy truth can be used to check for the existence of "real" entries. * * @author Graeme Rocher * @since 1.5 */ class ConfigObject extends LinkedHashMap implements Writable { static final KEYWORDS = Types.getKeywords() static final TAB_CHARACTER = '\t' /** * The config file that was used when parsing this ConfigObject */ URL configFile ConfigObject(URL file) { this.configFile = file } ConfigObject() {} /** * Writes this config object into a String serialized representation which can later be parsed back using the parse() * method * * @see groovy.lang.Writable#writeTo(java.io.Writer) */ Writer writeTo(Writer outArg) { def out try { out = new BufferedWriter(outArg) writeConfig("",this, out, 0, false) } finally { out.flush() } return outArg } /** * Overrides the default getProperty implementation to create nested ConfigObject instances on demand * for non-existent keys */ def getProperty(String name) { if(name == 'configFile') return this.configFile if(!containsKey (name)) { ConfigObject prop = new ConfigObject(this.configFile) put(name, prop) return prop } return get(name) } /** * A ConfigObject is a tree structure consisting of nested maps. This flattens the maps into * a single level structure like a properties file */ Map flatten() { return flatten(null) } /** * Flattens this ConfigObject populating the results into the target Map * * @see ConfigObject#flatten() */ Map flatten(Map target) { if(target == null)target = new ConfigObject() populate("", target, this) target } /** * Merges the given map with this ConfigObject overriding any matching configuration entries in this ConfigObject * * @param other The ConfigObject to merge with * @return The result of the merge */ Map merge(ConfigObject other) { return merge(this,other) } /** * Converts this ConfigObject into a the java.util.Properties format, flattening the tree structure beforehand * @return A java.util.Properties instance */ Properties toProperties() { def props = new Properties() flatten(props) props = convertValuesToString(props) return props } /** * Converts this ConfigObject ino the java.util.Properties format, flatten the tree and prefixing all entries with the given prefix * @param prefix The prefix to append before property entries * @return A java.util.Properties instance */ Properties toProperties(String prefix) { def props = new Properties() populate("${prefix}.", props, this) props = convertValuesToString(props) return props } private merge(Map config, Map other) { for(entry in other) { def configEntry = config[entry.key] if(configEntry == null) { config[entry.key] = entry.value continue } else { if(configEntry instanceof Map && configEntry.size() > 0 && entry.value instanceof Map) { // recur merge(configEntry, entry.value) } else { config[entry.key] = entry.value } } } return config } private writeConfig(String prefix,ConfigObject map, out, Integer tab, boolean apply) { def space = apply ? TAB_CHARACTER*tab : '' for(key in map.keySet()) { def value = map.get(key) if(value instanceof ConfigObject) { if(!value.isEmpty()) { def dotsInKeys = value.find { entry -> entry.key.indexOf('.') > -1 } def configSize = value.size() def firstKey = value.keySet().iterator().next() def firstValue = value.values().iterator().next() def firstSize if(firstValue instanceof ConfigObject){ firstSize = firstValue.size() } else { firstSize = 1 } if(configSize == 1|| dotsInKeys ) { if(firstSize == 1 && firstValue instanceof ConfigObject) { key = KEYWORDS.contains(key) ? key.inspect() : key def writePrefix = "${prefix}${key}.${firstKey}." writeConfig(writePrefix, firstValue, out, tab, true) } else if(!dotsInKeys && firstValue instanceof ConfigObject) { writeNode(key, space, tab,value, out) } else { for(j in value.keySet()) { def v2 = value.get(j) def k2 = j.indexOf('.') > -1 ? j.inspect() : j if(v2 instanceof ConfigObject) { key = KEYWORDS.contains(key) ? key.inspect() : key writeConfig("${prefix}${key}", v2, out, tab, false) } else { writeValue("${key}.${k2}", space, prefix, v2, out) } } } } else { writeNode(key, space,tab, value, out) } } } else { writeValue(key, space, prefix, value, out) } } } private writeValue(key, space, prefix, value, out) { key = key.indexOf('.') > -1 ? key.inspect() : key boolean isKeyword = KEYWORDS.contains(key) key = isKeyword ? key.inspect() : key if(!prefix && isKeyword) prefix = "this." out << "${space}${prefix}$key=${value.inspect()}" out.newLine() } private writeNode(key, space, tab, value, out) { key = KEYWORDS.contains(key) ? key.inspect() : key out << "${space}$key {" out.newLine() writeConfig("",value, out, tab+1, true) def last = "${space}}" out << last out.newLine() } private convertValuesToString(props) { def newProps = [:] for(e in props) { newProps[e.key] = e.value?.toString() } return newProps } private populate(suffix, config, map) { for(key in map.keySet()) { def value = map.get(key) if(value instanceof Map) { populate(suffix+"${key}.", config, value) } else { try { config[suffix+key] = value } catch (java.lang.NullPointerException e) { // it is idiotic story but if config map doesn't allow null values (like Hashtable) // we can't do too much } } } } } groovy-1.8.6/src/main/groovy/util/ProxyGenerator.java0000644001501200150120000005015311715031256022246 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.*; import org.codehaus.groovy.control.MultipleCompilationErrorsException; import org.codehaus.groovy.runtime.ConversionHandler; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; /** * Classes to generate 'Proxy' objects which implement interfaces, * maps of closures and/or extend classes/delegates. * * @author Paul King * @author Guillaume Laforge */ public class ProxyGenerator { public static final ProxyGenerator INSTANCE = new ProxyGenerator(); static { // wrap the standard MetaClass with the delegate setMetaClass(GroovySystem.getMetaClassRegistry().getMetaClass(ProxyGenerator.class)); } private ClassLoader override = null; private boolean debug = false; private boolean emptyMethods = false; private List objectMethods = getInheritedMethods(Object.class, new ArrayList()); private List groovyObjectMethods = getInheritedMethods(GroovyObject.class, new ArrayList()); public boolean getDebug() { return debug; } /** * Instructs ProxyGenerator to dump generated Groovy * source code to standard output during construction. This is useful * for debugging purposes but should be turned off in production. * * @param debug true if you want generated source to be printed */ public void setDebug(boolean debug) { this.debug = debug; } public boolean getEmptyMethods() { return emptyMethods; } /** * Changes generated methods to have empty implementations. *

    * Methods in generated aggregates not supplied in a closures map or * base class are given 'default' implementations. The implementation * will normally throw an UnsupportedOperationException * but setting this boolean will leave it empty. * * @param emptyMethods true if you want generated methods to be empty */ public void setEmptyMethods(boolean emptyMethods) { this.emptyMethods = emptyMethods; } public ClassLoader getOverride() { return override; } public void setOverride(ClassLoader override) { this.override = override; } public GroovyObject instantiateAggregateFromBaseClass(Class clazz) { return instantiateAggregateFromBaseClass((Map) null, clazz); } public GroovyObject instantiateAggregateFromBaseClass(Map map, Class clazz) { return instantiateAggregateFromBaseClass(map, clazz, null); } public GroovyObject instantiateAggregateFromBaseClass(Closure cl, Class clazz) { Map m = new HashMap(); m.put("*", cl); return instantiateAggregateFromBaseClass(m, clazz, null); } public GroovyObject instantiateAggregateFromBaseClass(Class clazz, Object[] constructorArgs) { return instantiateAggregate(null, null, clazz, constructorArgs); } public GroovyObject instantiateAggregateFromBaseClass(Map map, Class clazz, Object[] constructorArgs) { return instantiateAggregate(map, null, clazz, constructorArgs); } public GroovyObject instantiateAggregateFromInterface(Class clazz) { return instantiateAggregateFromInterface(null, clazz); } public GroovyObject instantiateAggregateFromInterface(Map map, Class clazz) { List interfaces = new ArrayList(); interfaces.add(clazz); return instantiateAggregate(map, interfaces); } public GroovyObject instantiateAggregate(List interfaces) { return instantiateAggregate(null, interfaces); } public GroovyObject instantiateAggregate(Map closureMap, List interfaces) { return instantiateAggregate(closureMap, interfaces, null); } public GroovyObject instantiateAggregate(Map closureMap, List interfaces, Class clazz) { return instantiateAggregate(closureMap, interfaces, clazz, null); } public GroovyObject instantiateAggregate(Map closureMap, List interfaces, Class clazz, Object[] constructorArgs) { Map map = new HashMap(); if (closureMap != null) { map = closureMap; } List interfacesToImplement; if (interfaces == null) { interfacesToImplement = new ArrayList(); } else { interfacesToImplement = interfaces; } Class baseClass = GroovyObjectSupport.class; if (clazz != null) { baseClass = clazz; } boolean hasArgs = constructorArgs != null && constructorArgs.length > 0; String name = shortName(baseClass.getName()) + "_groovyProxy"; StringBuffer buffer = new StringBuffer(); // add class header and fields buffer.append("class ").append(name); if (clazz != null) { buffer.append(" extends ").append(baseClass.getName()); } for (int i = 0; i < interfacesToImplement.size(); i++) { Class thisInterface = interfacesToImplement.get(i); if (i == 0) { buffer.append(" implements "); } else { buffer.append(", "); } buffer.append(thisInterface.getName()); } buffer.append(" {\n").append(" private closureMap\n "); // add constructor buffer.append(name).append("(map"); if (hasArgs) { buffer.append(", args"); } buffer.append(") {\n"); buffer.append(" super("); if (hasArgs) { buffer.append("*args"); } buffer.append(")\n"); buffer.append(" this.closureMap = map\n"); buffer.append(" }\n"); // add overwriting methods Map selectedMethods = new HashMap(); List publicAndProtectedMethods = getInheritedMethods(baseClass, new ArrayList()); boolean closureIndicator = map.containsKey("*"); for (Method method : publicAndProtectedMethods) { if (method.getName().indexOf('$') != -1 || Modifier.isFinal(method.getModifiers()) || (!"toString".equals(method.getName()) && ConversionHandler.isCoreObjectMethod(method)) || containsEquivalentMethod(selectedMethods.values(), method)) continue; if (map.containsKey(method.getName()) || closureIndicator) { selectedMethods.put(method.getName(), method); addOverridingMapCall(buffer, method, closureIndicator); } else if (Modifier.isAbstract(method.getModifiers())) { selectedMethods.put(method.getName(), method); addMapOrDummyCall(map, buffer, method); } } // add interface methods List interfaceMethods = new ArrayList(); for (Class thisInterface : interfacesToImplement) { getInheritedMethods(thisInterface, interfaceMethods); } for (Method method : interfaceMethods) { if (!containsEquivalentMethod(publicAndProtectedMethods, method)) { selectedMethods.put(method.getName(), method); addMapOrDummyCall(map, buffer, method); } } // add leftover methods from the map for (Object o : map.keySet()) { String methodName = (String) o; if (methodName.indexOf('$') != -1 || methodName.indexOf('*') != -1) continue; if (selectedMethods.keySet().contains(methodName)) continue; addNewMapCall(buffer, methodName); } // end class buffer.append("}\n").append("new ").append(name); buffer.append("(map"); if (hasArgs) { buffer.append(", constructorArgs"); } buffer.append(")"); Binding binding = new Binding(); binding.setVariable("map", map); binding.setVariable("constructorArgs", constructorArgs); ClassLoader cl = override != null ? override : baseClass.getClassLoader(); if (clazz == null && interfacesToImplement.size() > 0) { Class c = interfacesToImplement.get(0); cl = c.getClassLoader(); } GroovyShell shell = new GroovyShell(cl, binding); if (debug) System.out.println("proxy source:\n------------------\n" + buffer.toString() + "\n------------------"); try { return (GroovyObject) shell.evaluate(buffer.toString()); } catch (MultipleCompilationErrorsException err) { throw new GroovyRuntimeException("Error creating proxy: " + err.getMessage()); } } public GroovyObject instantiateDelegate(Object delegate) { return instantiateDelegate(null, delegate); } public GroovyObject instantiateDelegate(List interfaces, Object delegate) { return instantiateDelegate(null, interfaces, delegate); } public GroovyObject instantiateDelegate(Map closureMap, List interfaces, Object delegate) { return instantiateDelegateWithBaseClass(closureMap, interfaces, delegate, null); } public GroovyObject instantiateDelegateWithBaseClass(Map closureMap, List interfaces, Object delegate) { return instantiateDelegateWithBaseClass(closureMap, interfaces, delegate, delegate.getClass()); } public GroovyObject instantiateDelegateWithBaseClass(Map closureMap, List interfaces, Object delegate, Class baseClass) { String name = shortName(delegate.getClass().getName()) + "_delegateProxy"; return instantiateDelegateWithBaseClass(closureMap, interfaces, delegate, baseClass, name); } public GroovyObject instantiateDelegateWithBaseClass(Map closureMap, List interfaces, Object delegate, Class baseClass, String name) { Map map = new HashMap(); if (closureMap != null) { map = closureMap; } List selectedMethods = new ArrayList(); List interfacesToImplement; if (interfaces == null) { interfacesToImplement = new ArrayList(); } else { interfacesToImplement = interfaces; } StringBuffer buffer = new StringBuffer(); // add class header and fields buffer.append("import org.codehaus.groovy.runtime.InvokerHelper\nclass ").append(name); if (baseClass != null) { buffer.append(" extends ").append(baseClass.getName()); } for (int i = 0; i < interfacesToImplement.size(); i++) { Class thisInterface = interfacesToImplement.get(i); if (i == 0) { buffer.append(" implements "); } else { buffer.append(", "); } buffer.append(thisInterface.getName()); } buffer.append(" {\n").append(" private delegate\n").append(" private closureMap\n "); // add constructor buffer.append(name).append("(map, delegate) {\n"); buffer.append(" this.closureMap = map\n"); buffer.append(" this.delegate = delegate\n"); buffer.append(" }\n"); // add interface methods List interfaceMethods = new ArrayList(); for (Class thisInterface : interfacesToImplement) { getInheritedMethods(thisInterface, interfaceMethods); } for (Method method : interfaceMethods) { if (!containsEquivalentMethod(objectMethods, method) && !containsEquivalentMethod(groovyObjectMethods, method)) { selectedMethods.add(method.getName()); addWrappedCall(buffer, method, map); } } List additionalMethods = getInheritedMethods(delegate.getClass(), new ArrayList()); for (Method method : additionalMethods) { if (method.getName().indexOf('$') != -1) continue; if (!containsEquivalentMethod(interfaceMethods, method) && !containsEquivalentMethod(objectMethods, method) && !containsEquivalentMethod(groovyObjectMethods, method)) { selectedMethods.add(method.getName()); addWrappedCall(buffer, method, map); } } // add leftover methods from the map for (Object o : map.keySet()) { String methodName = (String) o; if (selectedMethods.contains(methodName)) continue; addNewMapCall(buffer, methodName); } // end class buffer.append("}\n").append("new ").append(name); buffer.append("(map, delegate)"); Binding binding = new Binding(); binding.setVariable("map", map); binding.setVariable("delegate", delegate); ClassLoader cl = override != null ? override : delegate.getClass().getClassLoader(); GroovyShell shell = new GroovyShell(cl, binding); if (debug) System.out.println("proxy source:\n------------------\n" + buffer.toString() + "\n------------------"); try { return (GroovyObject) shell.evaluate(buffer.toString()); } catch (MultipleCompilationErrorsException err) { throw new GroovyRuntimeException("Error creating proxy: " + err.getMessage()); } } private void addWrappedCall(StringBuffer buffer, Method method, Map map) { if (map.containsKey(method.getName())) { addOverridingMapCall(buffer, method, false); } else { Class[] parameterTypes = addMethodPrefix(buffer, method); addWrappedMethodBody(buffer, method, parameterTypes); addMethodSuffix(buffer); } } private boolean containsEquivalentMethod(Collection publicAndProtectedMethods, Method candidate) { for (Method method : publicAndProtectedMethods) { if (candidate.getName().equals(method.getName()) && candidate.getReturnType().equals(method.getReturnType()) && hasMatchingParameterTypes(candidate, method)) { return true; } } return false; } private boolean hasMatchingParameterTypes(Method method, Method candidate) { Class[] candidateParamTypes = candidate.getParameterTypes(); Class[] methodParamTypes = method.getParameterTypes(); if (candidateParamTypes.length != methodParamTypes.length) return false; for (int i = 0; i < methodParamTypes.length; i++) { if (!candidateParamTypes[i].equals(methodParamTypes[i])) return false; } return true; } private List getInheritedMethods(Class baseClass, List methods) { methods.addAll(DefaultGroovyMethods.toList(baseClass.getMethods())); Class currentClass = baseClass; while (currentClass != null) { Method[] protectedMethods = currentClass.getDeclaredMethods(); for (Method method : protectedMethods) { if (method.getName().indexOf('$') != -1) continue; if (Modifier.isProtected(method.getModifiers()) && !containsEquivalentMethod(methods, method)) methods.add(method); } currentClass = currentClass.getSuperclass(); } return methods; } private void addNewMapCall(StringBuffer buffer, String methodName) { buffer.append(" def ").append(methodName).append("(Object[] args) {\n") .append(" this.@closureMap['").append(methodName).append("'] (*args)\n }\n"); } private void addOverridingMapCall(StringBuffer buffer, Method method, boolean closureIndicator) { Class[] parameterTypes = addMethodPrefix(buffer, method); addMethodBody(buffer, closureIndicator ? "*" : method.getName(), parameterTypes); addMethodSuffix(buffer); } private void addMapOrDummyCall(Map map, StringBuffer buffer, Method method) { Class[] parameterTypes = addMethodPrefix(buffer, method); if (map.containsKey(method.getName())) { addMethodBody(buffer, method.getName(), parameterTypes); } else if (!emptyMethods) { addUnsupportedBody(buffer); } addMethodSuffix(buffer); } private void addUnsupportedBody(StringBuffer buffer) { buffer.append("throw new UnsupportedOperationException()"); } private Class[] addMethodPrefix(StringBuffer buffer, Method method) { buffer.append(" ").append(getSimpleName(method.getReturnType())) .append(" ").append(method.getName()).append("("); Class[] parameterTypes = method.getParameterTypes(); for (int parameterTypeIndex = 0; parameterTypeIndex < parameterTypes.length; parameterTypeIndex++) { Class parameter = parameterTypes[parameterTypeIndex]; if (parameterTypeIndex != 0) { buffer.append(", "); } buffer.append(getSimpleName(parameter)).append(" ") .append("p").append(parameterTypeIndex); } buffer.append(") { "); return parameterTypes; } private void addMethodBody(StringBuffer buffer, String method, Class[] parameterTypes) { buffer.append("this.@closureMap['").append(method).append("'] ("); for (int j = 0; j < parameterTypes.length; j++) { if (j != 0) { buffer.append(", "); } buffer.append("p").append(j); } buffer.append(")"); } private void addWrappedMethodBody(StringBuffer buffer, Method method, Class[] parameterTypes) { buffer.append("\n Object[] args = ["); for (int j = 0; j < parameterTypes.length; j++) { if (j != 0) { buffer.append(", "); } buffer.append("p").append(j); } buffer.append("]\n "); buffer.append("InvokerHelper.invokeMethod(delegate, '").append(method.getName()).append("', args)\n"); } private void addMethodSuffix(StringBuffer buffer) { buffer.append(" }\n"); } /** * TODO once we switch to Java 1.5 bt default, use Class#getSimpleName() directly * * @param c the class of which we want the readable simple name * @return the readable simple name */ public String getSimpleName(Class c) { if (c.isArray()) { int dimension = 0; Class componentClass = c; while (componentClass.isArray()) { componentClass = componentClass.getComponentType(); dimension++; } return componentClass.getName().replaceAll("\\$", "\\.") + DefaultGroovyMethods.multiply("[]", dimension); } else { return c.getName().replaceAll("\\$", "\\."); } } public String shortName(String name) { int index = name.lastIndexOf('.'); if (index == -1) return name; return name.substring(index + 1, name.length()); } private static void setMetaClass(final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { @Override public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { return InvokerHelper.invokeMethod(INSTANCE, methodName, arguments); } }; GroovySystem.getMetaClassRegistry().setMetaClass(ProxyGenerator.class, newMetaClass); } } groovy-1.8.6/src/main/groovy/util/PermutationGenerator.java0000644001501200150120000001001511627206700023425 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Systematically generate permutations. * * Adapted from Java Code by Michael Gilleland (released with no restrictions) using an algorithm described here: * Kenneth H. Rosen, Discrete Mathematics and Its Applications, 2nd edition (NY: McGraw-Hill, 1991), pp. 282-284 */ public class PermutationGenerator implements Iterator> { private int[] a; private BigInteger numLeft; private BigInteger total; private List items; /** * WARNING: Don't make n too large. * Recall that the number of permutations is n! * which can be very large, even when n is as small as 20 -- * 20! = 2,432,902,008,176,640,000 and * 21! is too big to fit into a Java long, which is * why we use BigInteger instead. * * @param items the items to permute */ public PermutationGenerator(Collection items) { this.items = new ArrayList(items); int n = items.size(); if (n < 1) { throw new IllegalArgumentException("At least one item required"); } a = new int[n]; total = getFactorial(n); reset(); } public void reset() { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public BigInteger getTotal() { return total; } public boolean hasNext() { return numLeft.compareTo(BigInteger.ZERO) == 1; } /** * Compute factorial (TODO: expose this) * * @param n the input integer * @return the factorial for n */ private static BigInteger getFactorial(int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } /** * Generate next permutation (algorithm from Rosen p. 284) * * @return the items permuted */ public List next() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return items; } int temp; // Find largest index j with a[j] < a[j+1] int j = a.length - 2; while (a[j] > a[j + 1]) { j--; } // Find index k such that a[k] is smallest integer // greater than a[j] to the right of a[j] int k = a.length - 1; while (a[j] > a[k]) { k--; } // Interchange a[j] and a[k] temp = a[k]; a[k] = a[j]; a[j] = temp; // Put tail end of permutation after jth position in increasing order int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); List ans = new ArrayList(a.length); for (int index : a) { ans.add(items.get(index)); } return ans; } public void remove() { throw new UnsupportedOperationException("remove() not allowed for PermutationGenerator"); } } groovy-1.8.6/src/main/groovy/util/GroovyTestCase.java0000644001501200150120000003567311715031256022211 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovyShell; import junit.framework.TestCase; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.logging.Logger; /** * A default JUnit TestCase in Groovy. This provides a number of helper methods * plus avoids the JUnit restriction of requiring all test* methods to be void * return type. * * @author bob mcwhirter * @author James Strachan * @author Dierk Koenig (the notYetImplemented feature, changes to shouldFail) * @version $Revision$ */ public class GroovyTestCase extends TestCase { protected static Logger log = Logger.getLogger(GroovyTestCase.class.getName()); private static int counter; private static final int MAX_NESTED_EXCEPTIONS = 10; public static final String TEST_SCRIPT_NAME_PREFIX = "TestScript"; private boolean useAgileDoxNaming = false; public GroovyTestCase() { } /** * Overload the getName() method to make the test cases look more like AgileDox * (thanks to Joe Walnes for this tip!) */ public String getName() { if (useAgileDoxNaming) { return super.getName().substring(4).replaceAll("([A-Z])", " $1").toLowerCase(); } else { return super.getName(); } } public String getMethodName() { return super.getName(); } /** * Asserts that the arrays are equivalent and contain the same values * * @param expected * @param value */ protected void assertArrayEquals(Object[] expected, Object[] value) { String message = "expected array: " + InvokerHelper.toString(expected) + " value array: " + InvokerHelper.toString(value); assertNotNull(message + ": expected should not be null", expected); assertNotNull(message + ": value should not be null", value); assertEquals(message, expected.length, value.length); for (int i = 0, size = expected.length; i < size; i++) { assertEquals("value[" + i + "] when " + message, expected[i], value[i]); } } /** * Asserts that the array of characters has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, char[] array) { assertEquals(length, array.length); } /** * Asserts that the array of ints has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, int[] array) { assertEquals(length, array.length); } /** * Asserts that the array of objects has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, Object[] array) { assertEquals(length, array.length); } /** * Asserts that the array of characters contains a given char * * @param expected expected character to be found * @param array the array */ protected void assertContains(char expected, char[] array) { for (int i = 0; i < array.length; ++i) { if (array[i] == expected) { return; } } StringBuffer message = new StringBuffer(); message.append(expected).append(" not in {"); for (int i = 0; i < array.length; ++i) { message.append("'").append(array[i]).append("'"); if (i < (array.length - 1)) { message.append(", "); } } message.append(" }"); fail(message.toString()); } /** * Asserts that the array of ints contains a given int * * @param expected expected int * @param array the array */ protected void assertContains(int expected, int[] array) { for (int anInt : array) { if (anInt == expected) { return; } } StringBuffer message = new StringBuffer(); message.append(expected).append(" not in {"); for (int i = 0; i < array.length; ++i) { message.append("'").append(array[i]).append("'"); if (i < (array.length - 1)) { message.append(", "); } } message.append(" }"); fail(message.toString()); } /** * Asserts that the value of toString() on the given object matches the * given text string * * @param value the object to be output to the console * @param expected the expected String representation */ protected void assertToString(Object value, String expected) { Object console = InvokerHelper.invokeMethod(value, "toString", null); assertEquals("toString() on value: " + value, expected, console); } /** * Asserts that the value of inspect() on the given object matches the * given text string * * @param value the object to be output to the console * @param expected the expected String representation */ protected void assertInspect(Object value, String expected) { Object console = InvokerHelper.invokeMethod(value, "inspect", null); assertEquals("inspect() on value: " + value, expected, console); } /** * Asserts that the script runs without any exceptions * * @param script the script that should pass without any exception thrown */ protected void assertScript(final String script) throws Exception { GroovyShell shell = new GroovyShell(); shell.evaluate(script, getTestClassName()); } protected String getTestClassName() { return TEST_SCRIPT_NAME_PREFIX + getMethodName() + (counter++) + ".groovy"; } /** * Asserts that the given code closure fails when it is evaluated * * @param code * @return the message of the thrown Throwable */ protected String shouldFail(Closure code) { boolean failed = false; String result = null; try { code.call(); } catch (GroovyRuntimeException gre) { failed = true; result = ScriptBytecodeAdapter.unwrap(gre).getMessage(); } catch (Throwable e) { failed = true; result = e.getMessage(); } assertTrue("Closure " + code + " should have failed", failed); return result; } /** * Asserts that the given code closure fails when it is evaluated * and that a particular exception is thrown. * * @param clazz the class of the expected exception * @param code the closure that should fail * @return the message of the expected Throwable */ protected String shouldFail(Class clazz, Closure code) { Throwable th = null; try { code.call(); } catch (GroovyRuntimeException gre) { th = ScriptBytecodeAdapter.unwrap(gre); } catch (Throwable e) { th = e; } if (th == null) { fail("Closure " + code + " should have failed with an exception of type " + clazz.getName()); } else if (!clazz.isInstance(th)) { fail("Closure " + code + " should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th); } return th.getMessage(); } /** * Asserts that the given code closure fails when it is evaluated * and that a particular exception can be attributed to the cause. * The expected exception class is compared recursively with any nested * exceptions using getCause() until either a match is found or no more * nested exceptions exist. *

    * If a match is found the error message associated with the matching * exception is returned. If no match was found the method will fail. * * @param clazz the class of the expected exception * @param code the closure that should fail * @return the message of the expected Throwable */ protected String shouldFailWithCause(Class clazz, Closure code) { Throwable th = null; Throwable orig = null; int level = 0; try { code.call(); } catch (GroovyRuntimeException gre) { orig = ScriptBytecodeAdapter.unwrap(gre); th = orig.getCause(); } catch (Throwable e) { orig = e; th = orig.getCause(); } while (th != null && !clazz.isInstance(th) && th != th.getCause() && level < MAX_NESTED_EXCEPTIONS) { th = th.getCause(); level++; } if (orig == null) { fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName()); } else if (th == null || !clazz.isInstance(th)) { fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName() + ", instead found these Exceptions:\n" + buildExceptionList(orig)); } return th.getMessage(); } private String buildExceptionList(Throwable th) { StringBuilder sb = new StringBuilder(); int level = 0; while (th != null) { if (level > 1) { for (int i = 0; i < level - 1; i++) sb.append(" "); } if (level > 0) sb.append("-> "); if (level > MAX_NESTED_EXCEPTIONS) { sb.append("..."); break; } sb.append(th.getClass().getName()).append(": ").append(th.getMessage()).append("\n"); if (th == th.getCause()) { break; } th = th.getCause(); level++; } return sb.toString(); } /** * Returns a copy of a string in which all EOLs are \n. */ protected String fixEOLs(String value) { return value.replaceAll("(\\r\\n?)|\n", "\n"); } /** * Runs the calling JUnit test again and fails only if it unexpectedly runs.
    * This is helpful for tests that don't currently work but should work one day, * when the tested functionality has been implemented.
    * The right way to use it is: *

         * public void testXXX() {
         *   if (GroovyTestCase.notYetImplemented(this)) return;
         *   ... the real (now failing) unit test
         * }
         * 
    * Idea copied from HtmlUnit (many thanks to Marc Guillemot). * Future versions maybe available in the JUnit distro. * The purpose of providing a 'static' version is such that you can use the * feature even if not subclassing GroovyTestCase. * * @return when not itself already in the call stack */ public static boolean notYetImplemented(TestCase caller) { if (notYetImplementedFlag.get() != null) { return false; } notYetImplementedFlag.set(Boolean.TRUE); final Method testMethod = findRunningJUnitTestMethod(caller.getClass()); try { log.info("Running " + testMethod.getName() + " as not yet implemented"); testMethod.invoke(caller, (Object[]) new Class[]{}); fail(testMethod.getName() + " is marked as not yet implemented but passes unexpectedly"); } catch (final Exception e) { log.info(testMethod.getName() + " fails which is expected as it is not yet implemented"); // method execution failed, it is really "not yet implemented" } finally { notYetImplementedFlag.set(null); } return true; } /** * Convenience method for subclasses of GroovyTestCase, identical to *
     GroovyTestCase.notYetImplemented(this); 
    . * * @return when not itself already in the call stack * @see #notYetImplemented(junit.framework.TestCase) */ public boolean notYetImplemented() { return notYetImplemented(this); } /** * From JUnit. Finds from the call stack the active running JUnit test case * * @return the test case method * @throws RuntimeException if no method could be found. */ private static Method findRunningJUnitTestMethod(Class caller) { final Class[] args = new Class[]{}; // search the initial junit test final Throwable t = new Exception(); for (int i = t.getStackTrace().length - 1; i >= 0; --i) { final StackTraceElement element = t.getStackTrace()[i]; if (element.getClassName().equals(caller.getName())) { try { final Method m = caller.getMethod(element.getMethodName(), args); if (isPublicTestMethod(m)) { return m; } } catch (final Exception e) { // can't access, ignore it } } } throw new RuntimeException("No JUnit test case method found in call stack"); } /** * From Junit. Test if the method is a junit test. * * @param method the method * @return true if this is a junit test. */ private static boolean isPublicTestMethod(final Method method) { final String name = method.getName(); final Class[] parameters = method.getParameterTypes(); final Class returnType = method.getReturnType(); return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE) && Modifier.isPublic(method.getModifiers()); } public static void assertEquals(String message, Object expected, Object actual) { if (expected == null && actual == null) return; if (expected != null && DefaultTypeTransformation.compareEqual(expected, actual)) return; failNotEquals(message, expected, actual); } public static void assertEquals(Object expected, Object actual) { assertEquals(null, expected, actual); } public static void assertEquals(String expected, String actual) { assertEquals(null, expected, actual); } private static final ThreadLocal notYetImplementedFlag = new ThreadLocal(); } groovy-1.8.6/src/main/groovy/util/ConfigSlurper.groovy0000644001501200150120000002210111715031256022434 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util import java.beans.Introspector import java.beans.BeanInfo import org.codehaus.groovy.runtime.InvokerHelper /** *

    * ConfigSlurper is a utility class for reading configuration files defined in the form of Groovy * scripts. Configuration settings can be defined using dot notation or scoped using closures * *

    
    *   grails.webflow.stateless = true
    *    smtp {
    *        mail.host = 'smtp.myisp.com'
    *        mail.auth.user = 'server'
    *    }
    *    resources.URL = "http://localhost:80/resources"
    * 
    * *

    Settings can either be bound into nested maps or onto a specified JavaBean instance. In the case * of the latter an error will be thrown if a property cannot be bound. * * @author Graeme Rocher * @since 1.5 */ class ConfigSlurper { private static final ENV_METHOD = "environments" static final ENV_SETTINGS = '__env_settings__' //private BeanInfo bean //private instance GroovyClassLoader classLoader = new GroovyClassLoader() String environment private envMode = false private Map bindingVars ConfigSlurper() { } /** * Constructs a new ConfigSlurper instance using the given environment * @param env The Environment to use */ ConfigSlurper(String env) { this.environment = env } /** * Sets any additional variables that should be placed into the binding when evaluating Config scripts */ void setBinding(Map vars) { this.bindingVars = vars } /** * Parses a ConfigObject instances from an instance of java.util.Properties * @param The java.util.Properties instance */ ConfigObject parse(Properties properties) { ConfigObject config = new ConfigObject() for(key in properties.keySet()) { def tokens = key.split(/\./) def current = config def currentToken def last def lastToken def foundBase = false for(token in tokens) { if (foundBase) { // handle not properly nested tokens by ignoring // hierarchy below this point lastToken += "." + token current = last } else { last = current lastToken = token current = current."${token}" if(!(current instanceof ConfigObject)) foundBase = true } } if(current instanceof ConfigObject) { if(last[lastToken]) { def flattened = last.flatten() last.clear() flattened.each { k2, v2 -> last[k2] = v2 } last[lastToken] = properties.get(key) } else { last[lastToken] = properties.get(key) } } current = config } return config } /** * Parse the given script as a string and return the configuration object * * @see ConfigSlurper#parse(groovy.lang.Script) */ ConfigObject parse(String script) { return parse(classLoader.parseClass(script)) } /** * Create a new instance of the given script class and parse a configuration object from it * * @see ConfigSlurper#parse(groovy.lang.Script) */ ConfigObject parse(Class scriptClass) { return parse(scriptClass.newInstance()) } /** * Parse the given script into a configuration object (a Map) * @param script The script to parse * @return A Map of maps that can be navigating with dot de-referencing syntax to obtain configuration entries */ ConfigObject parse(Script script) { return parse(script, null) } /** * Parses a Script represented by the given URL into a ConfigObject * * @param scriptLocation The location of the script to parse * @return The ConfigObject instance */ ConfigObject parse(URL scriptLocation) { return parse(classLoader.parseClass(scriptLocation.text).newInstance(), scriptLocation) } /** * Parses the passed groovy.lang.Script instance using the second argument to allow the ConfigObject * to retain an reference to the original location other Groovy script * * @param script The groovy.lang.Script instance * @param location The original location of the Script as a URL * @return The ConfigObject instance */ ConfigObject parse(Script script, URL location) { def config = location ? new ConfigObject(location) : new ConfigObject() GroovySystem.metaClassRegistry.removeMetaClass(script.class) def mc = script.class.metaClass def prefix = "" LinkedList stack = new LinkedList() stack << [config:config,scope:[:]] def pushStack = { co -> stack << [config:co,scope:stack.last.scope.clone()] } def assignName = { name, co -> def current = stack.last current.config[name] = co current.scope[name] = co } def getPropertyClosure = { String name -> def current = stack.last def result if(current.config.get(name)) { result = current.config.get(name) } else if(current.scope[name]) { result = current.scope[name] } else { try { result = InvokerHelper.getProperty(this, name); } catch (GroovyRuntimeException e) { result = new ConfigObject() assignName.call(name,result) } } result } mc.getProperty = getPropertyClosure mc.invokeMethod = { String name, args -> def result if(args.length == 1 && args[0] instanceof Closure) { if(name == ENV_METHOD) { try { envMode = true args[0].call() } finally { envMode = false } } else if (envMode) { if(name == environment) { def co = new ConfigObject() config[ENV_SETTINGS] = co pushStack.call(co) try { envMode = false args[0].call() } finally { envMode = true } stack.pop() } } else { def co if (stack.last.config.get(name) instanceof ConfigObject) { co = stack.last.config.get(name) } else { co = new ConfigObject() } assignName.call(name, co) pushStack.call(co) args[0].call() stack.pop() } } else if (args.length == 2 && args[1] instanceof Closure) { try { prefix = name +'.' assignName.call(name, args[0]) args[1].call() } finally { prefix = "" } } else { MetaMethod mm = mc.getMetaMethod(name, args) if(mm) { result = mm.invoke(delegate, args) } else { throw new MissingMethodException(name, getClass(), args) } } result } script.metaClass = mc def setProperty = { String name, value -> assignName.call(prefix+name, value) } def binding = new ConfigBinding(setProperty) if(this.bindingVars) { binding.getVariables().putAll(this.bindingVars) } script.binding = binding script.run() def envSettings = config.remove(ENV_SETTINGS) if(envSettings) { config.merge(envSettings) } return config } } /** * Since Groovy Script don't support overriding setProperty, we have to using a trick with the Binding to provide this * functionality */ class ConfigBinding extends Binding { def callable ConfigBinding(Closure c) { this.callable = c } void setVariable(String name, Object value) { callable(name, value) } } groovy-1.8.6/src/main/groovy/util/AllTestSuite.java0000644001501200150120000001313211715031256021634 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.GroovyClassLoader; import groovy.lang.Script; import junit.framework.Test; import junit.framework.TestSuite; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.ScriptTestAdapter; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.logging.Logger; /** * AllTestSuite can be used in extension of GroovyTestSuite to execute TestCases written in Groovy * from inside a Java IDE. * AllTestSuite collects all files below a given directory that comply to a given pattern. * From these files, a TestSuite is constructed that can be run via an IDE graphical Test runner. * The files are assumed to be Groovy source files and be either a TestCase or a Script that can * be wrapped transparently into a TestCase. * The directory and the pattern can be set via System properties (see this classes' constants for details.) * * When setting the loglevel of this class to FINEST, all file loading will be logged. * * See also groovy.util.AllTestSuiteTest.groovy * @author Dierk Koenig based on a prototype by Andrew Glover * @author Paul King * todo: dk: make FileNameFinder injectable */ public class AllTestSuite extends TestSuite { /** The System Property to set as base directory for collection of Test Cases. * The pattern will be used as an Ant fileset include basedir. * Key is "groovy.test.dir". * Default value is "./test/". */ public static final String SYSPROP_TEST_DIR = "groovy.test.dir"; /** The System Property to set as the filename pattern for collection of Test Cases. * The pattern will be used as Regular Expression pattern applied with the find * operator against each candidate file.path. * Key is "groovy.test.pattern". * Default value is "Test.groovy". */ public static final String SYSPROP_TEST_PATTERN = "groovy.test.pattern"; /** The System Property to set as a filename excludes pattern for collection of Test Cases. * When non-empty, the pattern will be used as Regular Expression pattern applied with the * find operator against each candidate file.path. * Key is "groovy.test.excludesPattern". * Default value is "". */ public static final String SYSPROP_TEST_EXCLUDES_PATTERN = "groovy.test.excludesPattern"; private static final Logger LOG = Logger.getLogger(AllTestSuite.class.getName()); private static final ClassLoader JAVA_LOADER = AllTestSuite.class.getClassLoader(); private static final GroovyClassLoader GROOVY_LOADER = new GroovyClassLoader(JAVA_LOADER); private static final String[] EMPTY_ARGS = new String[]{}; private static IFileNameFinder finder = null; static { // this is only needed since the Groovy Build compiles *.groovy files after *.java files try { Class finderClass = Class.forName("groovy.util.FileNameFinder"); finder = (IFileNameFinder) finderClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Cannot find and instantiate class FileNameFinder", e); } } public static Test suite() { String basedir = System.getProperty(SYSPROP_TEST_DIR, "./test/"); String pattern = System.getProperty(SYSPROP_TEST_PATTERN, "**/*Test.groovy"); String excludesPattern = System.getProperty(SYSPROP_TEST_EXCLUDES_PATTERN, ""); return suite(basedir, pattern); } public static Test suite(String basedir, String pattern) { return suite(basedir, pattern, ""); } public static Test suite(String basedir, String pattern, String excludesPattern) { AllTestSuite suite = new AllTestSuite(); String fileName = ""; try { Collection filenames = excludesPattern.length() > 0 ? finder.getFileNames(basedir, pattern, excludesPattern) : finder.getFileNames(basedir, pattern); for (Iterator iter = filenames.iterator(); iter.hasNext();) { fileName = (String) iter.next(); LOG.finest("trying to load "+ fileName); suite.loadTest(fileName); } } catch (CompilationFailedException e1) { e1.printStackTrace(); throw new RuntimeException("CompilationFailedException when loading "+fileName, e1); } catch (IOException e2) { throw new RuntimeException("IOException when loading "+fileName, e2); } return suite; } protected void loadTest(String fileName) throws CompilationFailedException, IOException { Class type = compile(fileName); if (!Test.class.isAssignableFrom(type) && Script.class.isAssignableFrom(type)) { addTest(new ScriptTestAdapter(type, EMPTY_ARGS)); } else { addTestSuite(type); } } protected Class compile(String fileName) throws CompilationFailedException, IOException { return GROOVY_LOADER.parseClass(new File(fileName)); } } groovy-1.8.6/src/main/groovy/util/XmlParser.java0000644001501200150120000003506711627206700021202 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.xml.FactorySupport; import groovy.xml.QName; import org.xml.sax.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A helper class for parsing XML into a tree of Node instances for a * simple way of processing XML. This parser does not preserve the XML * InfoSet - if that's what you need try using W3C DOM, dom4j, JDOM, XOM etc. * This parser ignores comments and processing instructions and converts * the XML into a Node for each element in the XML with attributes * and child Nodes and Strings. This simple model is sufficient for * most simple use cases of processing XML. *

    * Example usage: *

     * def xml = '<root><one a1="uno!"/><two>Some text!</two></root>'
     * def rootNode = new XmlParser().parseText(xml)
     * assert rootNode.name() == 'root'
     * assert rootNode.one[0].@a1 == 'uno!'
     * assert rootNode.two.text() == 'Some text!'
     * rootNode.children().each { assert it.name() in ['one','two'] }
     * 
    * * @author James Strachan * @author Paul King * @version $Revision$ */ public class XmlParser implements ContentHandler { private StringBuffer bodyText = new StringBuffer(); private List stack = new ArrayList(); private Locator locator; private XMLReader reader; private Node parent; private boolean trimWhitespace = true; private boolean namespaceAware; public XmlParser() throws ParserConfigurationException, SAXException { this(false, true); } public XmlParser(boolean validating, boolean namespaceAware) throws ParserConfigurationException, SAXException { SAXParserFactory factory = FactorySupport.createSaxParserFactory(); factory.setNamespaceAware(namespaceAware); this.namespaceAware = namespaceAware; factory.setValidating(validating); reader = factory.newSAXParser().getXMLReader(); } public XmlParser(XMLReader reader) { this.reader = reader; } public XmlParser(SAXParser parser) throws SAXException { reader = parser.getXMLReader(); } /** * Returns the current trim whitespace setting. * * @return true if whitespace will be trimmed */ public boolean isTrimWhitespace() { return trimWhitespace; } /** * Sets the trim whitespace setting value. * * @param trimWhitespace the desired setting value */ public void setTrimWhitespace(boolean trimWhitespace) { this.trimWhitespace = trimWhitespace; } /** * Parses the content of the given file as XML turning it into a tree * of Nodes. * * @param file the File containing the XML to be parsed * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parse(File file) throws IOException, SAXException { InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return parent; } /** * Parse the content of the specified input source into a tree of Nodes. * * @param input the InputSource for the XML to parse * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parse(InputSource input) throws IOException, SAXException { getXMLReader().parse(input); return parent; } /** * Parse the content of the specified input stream into a tree of Nodes. *

    * Note that using this method will not provide the parser with any URI * for which to find DTDs etc * * @param input an InputStream containing the XML to be parsed * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parse(InputStream input) throws IOException, SAXException { InputSource is = new InputSource(input); getXMLReader().parse(is); return parent; } /** * Parse the content of the specified reader into a tree of Nodes. *

    * Note that using this method will not provide the parser with any URI * for which to find DTDs etc * * @param in a Reader to read the XML to be parsed * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parse(Reader in) throws IOException, SAXException { InputSource is = new InputSource(in); getXMLReader().parse(is); return parent; } /** * Parse the content of the specified URI into a tree of Nodes. * * @param uri a String containing a uri pointing to the XML to be parsed * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parse(String uri) throws IOException, SAXException { InputSource is = new InputSource(uri); getXMLReader().parse(is); return parent; } /** * A helper method to parse the given text as XML. * * @param text the XML text to parse * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly * wrapping another exception. * @throws IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public Node parseText(String text) throws IOException, SAXException { return parse(new StringReader(text)); } /** * Determine if namspace handling is enabled. * * @return true if namespace handling is enabled */ public boolean isNamespaceAware() { return namespaceAware; } /** * Enable and/or disable namspace handling. * * @param namespaceAware the new desired value */ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } // Delegated XMLReader methods //------------------------------------------------------------------------ /* (non-Javadoc) * @see org.xml.sax.XMLReader#getDTDHandler() */ public DTDHandler getDTDHandler() { return this.reader.getDTDHandler(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getEntityResolver() */ public EntityResolver getEntityResolver() { return this.reader.getEntityResolver(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getErrorHandler() */ public ErrorHandler getErrorHandler() { return this.reader.getErrorHandler(); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getFeature(java.lang.String) */ public boolean getFeature(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException { return this.reader.getFeature(uri); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#getProperty(java.lang.String) */ public Object getProperty(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException { return this.reader.getProperty(uri); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler) */ public void setDTDHandler(final DTDHandler dtdHandler) { this.reader.setDTDHandler(dtdHandler); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver) */ public void setEntityResolver(final EntityResolver entityResolver) { this.reader.setEntityResolver(entityResolver); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ public void setErrorHandler(final ErrorHandler errorHandler) { this.reader.setErrorHandler(errorHandler); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean) */ public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { this.reader.setFeature(uri, value); } /* (non-Javadoc) * @see org.xml.sax.XMLReader#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(final String uri, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException { reader.setProperty(uri, value); } // ContentHandler interface //------------------------------------------------------------------------- public void startDocument() throws SAXException { parent = null; } public void endDocument() throws SAXException { stack.clear(); } public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { addTextToNode(); Object nodeName = getElementName(namespaceURI, localName, qName); int size = list.getLength(); Map attributes = new LinkedHashMap(size); for (int i = 0; i < size; i++) { Object attributeName = getElementName(list.getURI(i), list.getLocalName(i), list.getQName(i)); String value = list.getValue(i); attributes.put(attributeName, value); } parent = createNode(parent, nodeName, attributes); stack.add(parent); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { addTextToNode(); if (!stack.isEmpty()) { stack.remove(stack.size() - 1); if (!stack.isEmpty()) { parent = stack.get(stack.size() - 1); } } } public void characters(char buffer[], int start, int length) throws SAXException { bodyText.append(buffer, start, length); } public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public Locator getDocumentLocator() { return locator; } public void setDocumentLocator(Locator locator) { this.locator = locator; } public void skippedEntity(String name) throws SAXException { } // Implementation methods //------------------------------------------------------------------------- protected XMLReader getXMLReader() { reader.setContentHandler(this); return reader; } protected void addTextToNode() { String text = bodyText.toString(); if (trimWhitespace) { text = text.trim(); } if (text.length() > 0) { parent.children().add(text); } bodyText = new StringBuffer(); } /** * Creates a new node with the given parent, name, and attributes. The * default implementation returns an instance of * groovy.util.Node. * * @param parent the parent node, or null if the node being created is the * root node * @param name an Object representing the name of the node (typically * an instance of {@link QName}) * @param attributes a Map of attribute names to attribute values * @return a new Node instance representing the current node */ protected Node createNode(Node parent, Object name, Map attributes) { return new Node(parent, name, attributes); } /** * Return a name given the namespaceURI, localName and qName. * * @param namespaceURI the namespace URI * @param localName the local name * @param qName the qualified name * @return the newly created representation of the name */ protected Object getElementName(String namespaceURI, String localName, String qName) { String name = localName; String prefix = ""; if ((name == null) || (name.length() < 1)) { name = qName; } if (namespaceURI == null || namespaceURI.length() <= 0) { return name; } if (qName != null && qName.length() > 0 && namespaceAware) { int index = qName.lastIndexOf(":"); if (index > 0) { prefix = qName.substring(0, index); } } return new QName(namespaceURI, name, prefix); } } groovy-1.8.6/src/main/groovy/util/FileNameFinder.groovy0000644001501200150120000000271611715031256022474 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util /** * Find files according to a base directory and an includes and excludes pattern. * The include and exclude patterns conform to Ant's fileset pattern conventions. * * @author Dierk Koenig * @author Paul King */ class FileNameFinder implements IFileNameFinder { List getFileNames(String basedir, String pattern) { return getFileNames(dir: basedir, includes: pattern) } List getFileNames(String basedir, String pattern, String excludesPattern) { return getFileNames(dir: basedir, includes: pattern, excludes: excludesPattern) } List getFileNames(Map args) { def ant = new AntBuilder() def scanner = ant.fileScanner { fileset(args) } def fls = [] for (f in scanner) { fls << f.getAbsolutePath() } return fls } }groovy-1.8.6/src/main/groovy/util/Proxy.java0000644001501200150120000000356611627206700020405 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.util.Iterator; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingMethodException; import org.codehaus.groovy.runtime.InvokerHelper; /** * Dynamic groovy proxy for another object. All method * invocations get forwarded to actual object, unless the proxy overrides it. * See groovy/util/ProxyTest.groovy for usage details. * * @author Troy Heninger * @author Dierk Koenig */ public class Proxy extends GroovyObjectSupport { private Object adaptee = null; /** * This method is for convenience. * It allows to get around the need for defining dump ctors is subclasses. * See unit tests for details. */ public Proxy wrap(Object adaptee){ setAdaptee(adaptee); return this; } public Object getAdaptee() { return adaptee; } public void setAdaptee(Object adaptee) { this.adaptee = adaptee; } public Object invokeMethod(String name, Object args) { try { return super.invokeMethod(name, args); } catch (MissingMethodException e) { return InvokerHelper.invokeMethod(adaptee, name, args); } } public Iterator iterator() { return InvokerHelper.asIterator(adaptee); } } groovy-1.8.6/src/main/groovy/util/GroovyCollections.java0000644001501200150120000001707711627206700022752 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.*; /** * A Collections utility class * * @author Paul King * @author Jim White */ public class GroovyCollections { /** * Finds all combinations of items from the given collections. * * @param collections the given collections * @return a List of the combinations found * @see #combinations(Collection) */ public static List combinations(Object[] collections) { return combinations(Arrays.asList(collections)); } /** * Finds all non-null subsequences of a list. * E.g. subsequences([1, 2, 3]) would be: * [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] * * @param items the List of items * @return the subsequences from items */ public static Set> subsequences(List items) { // items.inject([]){ ss, h -> ss.collect { it + [h] } + ss + [[h]] } Set> ans = new HashSet>(); for (T h : items) { Set> next = new HashSet>(); for (List it : ans) { List sublist = new ArrayList(it); sublist.add(h); next.add(sublist); } next.addAll(ans); List hlist = new ArrayList(); hlist.add(h); next.add(hlist); ans = next; } return ans; } /** * Finds all combinations of items from the given collections. * So, combinations([[true, false], [true, false]]) * is [[true, true], [false, true], [true, false], [false, false]] * and combinations([['a', 'b'],[1, 2, 3]]) * is [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]. * If a non-collection item is given, it is treated as a singleton collection, * i.e. combinations([[1, 2], 'x']) is [[1, 'x'], [2, 'x']]. * * @param collections the given collections * @return a List of the combinations found */ public static List combinations(Collection collections) { List collectedCombos = new ArrayList(); for (Iterator outer = collections.iterator(); outer.hasNext();) { Collection items = DefaultTypeTransformation.asCollection(outer.next()); if (collectedCombos.isEmpty()) { for (Iterator iterator = items.iterator(); iterator.hasNext();) { List l = new ArrayList(); l.add(iterator.next()); collectedCombos.add(l); } } else { List savedCombos = new ArrayList(collectedCombos); List newCombos = new ArrayList(); for (Iterator inner = items.iterator(); inner.hasNext();) { Object value = inner.next(); for (Iterator combos = savedCombos.iterator(); combos.hasNext();) { List oldlist = new ArrayList((List) combos.next()); oldlist.add(value); newCombos.add(oldlist); } } collectedCombos = newCombos; } } return collectedCombos; } /** * Transposes an array of lists. * * @param lists the given lists * @return a List of the transposed lists * @see #transpose(List) */ public static List transpose(Object[] lists) { return transpose(Arrays.asList(lists)); } /** * Transposes the given lists. * So, transpose([['a', 'b'], [1, 2]]) * is [['a', 1], ['b', 2]] and * transpose([['a', 'b', 'c']]) * is [['a'], ['b'], ['c']]. * * @param lists the given lists * @return a List of the transposed lists */ public static List transpose(List lists) { List result = new ArrayList(); if (lists.isEmpty() || lists.size() == 0) return result; int minSize = Integer.MAX_VALUE; for (Iterator outer = lists.iterator(); outer.hasNext();) { List list = (List) DefaultTypeTransformation.castToType(outer.next(), List.class); if (list.size() < minSize) minSize = list.size(); } if (minSize == 0) return result; for (int i = 0; i < minSize; i++) { result.add(new ArrayList()); } for (Iterator outer = lists.iterator(); outer.hasNext();) { List list = (List) DefaultTypeTransformation.castToType(outer.next(), List.class); for (int i = 0; i < minSize; i++) { List resultList = (List) result.get(i); resultList.add(list.get(i)); } } return result; } /** * Selects the minimum value found in an array of items, so * min([2, 4, 6] as Object[]) == 2. * * @param items an array of items * @return the minimum value */ public static T min(T[] items) { return min(Arrays.asList(items)); } /** * Selects the minimum value found in a collection of items. * * @param items a Collection * @return the minimum value */ public static T min(Collection items) { T answer = null; for (T value : items) { if (value != null) { if (answer == null || ScriptBytecodeAdapter.compareLessThan(value, answer)) { answer = value; } } } return answer; } /** * Selects the maximum value found in an array of items, so * min([2, 4, 6] as Object[]) == 6. * * @param items an array of items * @return the maximum value */ public static T max(T[] items) { return max(Arrays.asList(items)); } /** * Selects the maximum value found in a collection * * @param items a Collection * @return the maximum value */ public static T max(Collection items) { T answer = null; for (T value : items) { if (value != null) { if (answer == null || ScriptBytecodeAdapter.compareGreaterThan(value, answer)) { answer = value; } } } return answer; } /** * Sums all the items from an array of items. * * @param items an array of items * @return the sum of the items */ public static Object sum(Object[] items) { return DefaultGroovyMethods.sum(Arrays.asList(items)); } /** * Sums all the items from a collection of items. * * @param items a collection of items * @return the sum of the items */ public static Object sum(Collection items) { return DefaultGroovyMethods.sum(items); } } groovy-1.8.6/src/main/groovy/util/Factory.java0000644001501200150120000000672011707612044020667 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import java.util.Map; /** * @author Andres Almiray * @author Danno Ferrin */ public interface Factory { /** * * @return true if no child closures should be processed */ boolean isLeaf(); /** * Does this factory "Own" it's child closure. * @return true if the factory should have onContentClosure() called, * false if the builder should handle it */ boolean isHandlesNodeChildren(); /** * Called when a factory is registered to a builder * @param builder the build the factory has been registered to * @param registeredName the name the factory has been registered under */ void onFactoryRegistration(FactoryBuilderSupport builder, String registeredName, String registeredGroupName); /** * * @param builder the FactoryBuilder * @param name the name of the node being built * @param value the 'value' argument in the build node * @param attributes the attributes of the build arg * @return the object created for the builder * @throws InstantiationException if attempting to instantiate an interface or abstract class * @throws IllegalAccessException if the instance can't be created due to a security violation */ Object newInstance( FactoryBuilderSupport builder, Object name, Object value, Map attributes ) throws InstantiationException, IllegalAccessException; /** * * @param builder the FactoryBuilder * @param node the node (returned from newINstance) to consider the attributes for * @param attributes the attributes, a mutable set * @return true if the factory builder should use standerd bean property matching for the remaining attributes */ boolean onHandleNodeAttributes( FactoryBuilderSupport builder, Object node, Map attributes ); /** * Only called if it isLeaf is false and isHandlesNodeChildren is true * @param builder the FactoryBuilder * @param node the node (returned from newINstance) to consider the attributes for * @param childContent the child content closure of the builder * @return true if the factory builder should apply default node processing to the content child */ boolean onNodeChildren( FactoryBuilderSupport builder, Object node, Closure childContent); /** * * @param builder the FactoryBuilder * @param parent the parent node (null if 'root') * @param node the node just completed */ void onNodeCompleted( FactoryBuilderSupport builder, Object parent, Object node ); void setParent( FactoryBuilderSupport builder, Object parent, Object child ); void setChild( FactoryBuilderSupport builder, Object parent, Object child ); } groovy-1.8.6/src/main/groovy/util/AbstractFactory.java0000644001501200150120000000343011707612044022346 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import java.util.Map; /** * @author Andres Almiray * @author Danno Ferrin */ public abstract class AbstractFactory implements Factory { public boolean isLeaf() { return false; } public boolean isHandlesNodeChildren() { return false; } public void onFactoryRegistration(FactoryBuilderSupport builder, String registeredName, String group) { // do nothing } public boolean onHandleNodeAttributes( FactoryBuilderSupport builder, Object node, Map attributes ) { return true; } public boolean onNodeChildren( FactoryBuilderSupport builder, Object node, Closure childContent) { return true; } public void onNodeCompleted( FactoryBuilderSupport builder, Object parent, Object node ) { // do nothing } public void setParent( FactoryBuilderSupport builder, Object parent, Object child ) { // do nothing } public void setChild( FactoryBuilderSupport builder, Object parent, Object child ) { // do nothing } } groovy-1.8.6/src/main/groovy/util/NodePrinter.java0000644001501200150120000000761411627206700021513 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A helper class for creating nested trees of data * * @author James Strachan * @author Christian Stein * @version $Revision$ */ public class NodePrinter { protected final IndentPrinter out; public NodePrinter() { this(new IndentPrinter(new PrintWriter(new OutputStreamWriter(System.out)))); } public NodePrinter(PrintWriter out) { this(new IndentPrinter(out)); } public NodePrinter(IndentPrinter out) { if (out == null) { throw new NullPointerException("IndentPrinter 'out' must not be null!"); } this.out = out; } public void print(Node node) { out.printIndent(); printName(node); Map attributes = node.attributes(); boolean hasAttributes = attributes != null && !attributes.isEmpty(); if (hasAttributes) { printAttributes(attributes); } Object value = node.value(); if (value instanceof List) { if (!hasAttributes) { out.print("()"); } printList((List) value); } else { if (value instanceof String) { out.print("('"); out.print((String) value); out.println("')"); } else { out.println("()"); } } out.flush(); } protected void printName(Node node) { Object name = node.name(); if (name != null) { out.print(name.toString()); } else { out.print("null"); } } protected void printList(List list) { if (list.isEmpty()) { out.println(""); } else { out.println(" {"); out.incrementIndent(); for (Iterator iter = list.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Node) { print((Node) value); } else { out.printIndent(); out.print("builder.append("); out.print(InvokerHelper.toString(value)); out.println(")"); } } out.decrementIndent(); out.printIndent(); out.println("}"); } } protected void printAttributes(Map attributes) { out.print("("); boolean first = true; for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); if (first) { first = false; } else { out.print(", "); } out.print(entry.getKey().toString()); out.print(":"); if (entry.getValue() instanceof String) { out.print("'" + entry.getValue() + "'"); } else { out.print(InvokerHelper.toString(entry.getValue())); } } out.print(")"); } } groovy-1.8.6/src/main/groovy/util/ResourceException.java0000644001501200150120000000232411627206700022721 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; /** * @author sam */ public class ResourceException extends Exception { /** * */ public ResourceException() { super(); // TODO Auto-generated constructor stub } /** * @param message */ public ResourceException(String message) { super(message); } /** * @param message * @param cause */ public ResourceException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public ResourceException(Throwable cause) { super(cause); } } groovy-1.8.6/src/main/groovy/util/FactoryBuilderSupport.java0000644001501200150120000014062111712277626023603 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Binding; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovyClassLoader; import groovy.lang.MetaClass; import groovy.lang.MissingMethodException; import groovy.lang.MissingPropertyException; import groovy.lang.Reference; import groovy.lang.Script; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Mix of BuilderSupport and SwingBuilder's factory support. * * Warning: this implementation is not thread safe and should not be used * across threads in a multi-threaded environment. A locking mechanism * should be implemented by the subclass if use is expected across * multiple threads. * * @author James Strachan * @author Andres Almiray * @author Danno Ferrin */ public abstract class FactoryBuilderSupport extends Binding { public static final String CURRENT_FACTORY = "_CURRENT_FACTORY_"; public static final String PARENT_FACTORY = "_PARENT_FACTORY_"; public static final String PARENT_NODE = "_PARENT_NODE_"; public static final String CURRENT_NODE = "_CURRENT_NODE_"; public static final String PARENT_CONTEXT = "_PARENT_CONTEXT_"; public static final String PARENT_NAME = "_PARENT_NAME_"; public static final String CURRENT_NAME = "_CURRENT_NAME_"; public static final String OWNER = "owner"; public static final String PARENT_BUILDER = "_PARENT_BUILDER_"; public static final String CURRENT_BUILDER = "_CURRENT_BUILDER_"; public static final String CHILD_BUILDER = "_CHILD_BUILDER_"; public static final String SCRIPT_CLASS_NAME = "_SCRIPT_CLASS_NAME_"; private static final Logger LOG = Logger.getLogger(FactoryBuilderSupport.class.getName()); private static final Comparator METHOD_COMPARATOR = new Comparator() { public int compare(final Method o1, final Method o2) { int cmp = o1.getName().compareTo(o2.getName()); if (cmp != 0) return cmp; cmp = o1.getParameterTypes().length - o1.getParameterTypes().length; return cmp; } }; /** * Throws an exception if value is null. * * @param value the node's value * @param name the node's name */ public static void checkValueIsNull(Object value, Object name) { if (value != null) { throw new RuntimeException("'" + name + "' elements do not accept a value argument."); } } /** * Checks type of value against builder type * * @param value the node's value * @param name the node's name * @param type a Class that may be assignable to the value's class * @return true if type is assignable to the value's class, false if value * is null. */ public static boolean checkValueIsType(Object value, Object name, Class type) { if (value != null) { if (type.isAssignableFrom(value.getClass())) { return true; } else { throw new RuntimeException("The value argument of '" + name + "' must be of type " + type.getName() + ". Found: " + value.getClass()); } } else { return false; } } /** * Checks values against factory's type * * @param value the node's value * @param name the node's name * @param type a Class that may be assignable to the value's class * @return Returns true if type is assignable to the value's class, false if value is * null or a String. */ public static boolean checkValueIsTypeNotString(Object value, Object name, Class type) { if (value != null) { if (type.isAssignableFrom(value.getClass())) { return true; } else if (value instanceof String) { return false; } else { throw new RuntimeException("The value argument of '" + name + "' must be of type " + type.getName() + " or a String. Found: " + value.getClass()); } } else { return false; } } private ThreadLocal>> contexts = new ThreadLocal>>(); protected LinkedList attributeDelegates = new LinkedList(); // private List disposalClosures = new ArrayList(); // because of reverse iteration use ArrayList private Map factories = new HashMap(); private Closure nameMappingClosure; private ThreadLocal localProxyBuilder = new ThreadLocal(); private FactoryBuilderSupport globalProxyBuilder; protected LinkedList preInstantiateDelegates = new LinkedList(); protected LinkedList postInstantiateDelegates = new LinkedList(); protected LinkedList postNodeCompletionDelegates = new LinkedList(); protected Map explicitProperties = new HashMap(); protected Map explicitMethods = new HashMap(); protected Map> registrationGroup = new HashMap>(); protected String registrationGroupName = ""; // use binding to store? protected boolean autoRegistrationRunning = false; protected boolean autoRegistrationComplete = false; public FactoryBuilderSupport() { this(false); } public FactoryBuilderSupport(boolean init) { globalProxyBuilder = this; registrationGroup.put(registrationGroupName, new TreeSet()); if (init) { autoRegisterNodes(); } } private Set getRegistrationGroup(String name) { Set group = registrationGroup.get(name); if (group == null ) { group = new TreeSet(); registrationGroup.put(name, group); } return group; } /** * Ask the nodes to be registered */ public void autoRegisterNodes() { // if java did atomic blocks, this would be one synchronized (this) { if (autoRegistrationRunning || autoRegistrationComplete) { // registration already done or in process, abort return; } } autoRegistrationRunning = true; try { callAutoRegisterMethods(getClass()); } finally { autoRegistrationComplete = true; autoRegistrationRunning = false; } } private void callAutoRegisterMethods(Class declaredClass) { if (declaredClass == null) { return; } callAutoRegisterMethods(declaredClass.getSuperclass()); Method[] declaredMethods = declaredClass.getDeclaredMethods(); Arrays.sort(declaredMethods, METHOD_COMPARATOR); for (Method method : declaredMethods) { if (method.getName().startsWith("register") && method.getParameterTypes().length == 0) { registrationGroupName = method.getName().substring("register".length()); registrationGroup.put(registrationGroupName, new TreeSet()); try { if (Modifier.isPublic(method.getModifiers())) { method.invoke(this); } } catch (IllegalAccessException e) { throw new RuntimeException("Could not init " + getClass().getName() + " because of an access error in " + declaredClass.getName() + "." + method.getName(), e); } catch (InvocationTargetException e) { throw new RuntimeException("Could not init " + getClass().getName() + " because of an exception in " + declaredClass.getName() + "." + method.getName(), e); } finally { registrationGroupName = ""; } } } } /** * @param name the name of the variable to lookup * @return the variable value */ public Object getVariable(String name) { return getProxyBuilder().doGetVariable(name); } private Object doGetVariable(String name) { return super.getVariable(name); } /** * Sets the value of the given variable * * @param name the name of the variable to set * @param value the new value for the given variable */ public void setVariable(String name, Object value) { getProxyBuilder().doSetVariable(name, value); } private void doSetVariable(String name, Object value) { super.setVariable(name, value); } public Map getVariables() { return getProxyBuilder().doGetVariables(); } private Map doGetVariables() { return super.getVariables(); } /** * Overloaded to make variables appear as bean properties or via the subscript operator */ public Object getProperty(String property) { try { return getProxyBuilder().doGetProperty(property); } catch (MissingPropertyException mpe) { if ((getContext() != null) && (getContext().containsKey(property))) { return getContext().get(property); } else { return getMetaClass().getProperty(this, property); } } } private Object doGetProperty(String property) { Closure[] accessors = resolveExplicitProperty(property); if (accessors != null) { if (accessors[0] == null) { // write only property throw new MissingPropertyException(property + " is declared as write only"); } else { return accessors[0].call(); } } else { return super.getProperty(property); } } /** * Overloaded to make variables appear as bean properties or via the subscript operator */ public void setProperty(String property, Object newValue) { getProxyBuilder().doSetProperty(property, newValue); } private void doSetProperty(String property, Object newValue) { Closure[] accessors = resolveExplicitProperty(property); if (accessors != null) { if (accessors[1] == null) { // read only property throw new MissingPropertyException(property + " is declared as read only"); } else { accessors[1].call(newValue); } } else { super.setProperty(property, newValue); } } /** * @return the factory map (Unmodifiable Map). */ public Map getFactories() { return Collections.unmodifiableMap(getProxyBuilder().factories); } /** * @return the explicit methods map (Unmodifiable Map). */ public Map getExplicitMethods() { return Collections.unmodifiableMap(getProxyBuilder().explicitMethods); } /** * @return the explicit properties map (Unmodifiable Map). */ public Map getExplicitProperties() { return Collections.unmodifiableMap(getProxyBuilder().explicitProperties); } /** * @return the factory map (Unmodifiable Map). */ public Map getLocalFactories() { return Collections.unmodifiableMap(factories); } /** * @return the explicit methods map (Unmodifiable Map). */ public Map getLocalExplicitMethods() { return Collections.unmodifiableMap(explicitMethods); } /** * @return the explicit properties map (Unmodifiable Map). */ public Map getLocalExplicitProperties() { return Collections.unmodifiableMap(explicitProperties); } public Set getRegistrationGroups() { return Collections.unmodifiableSet(registrationGroup.keySet()); } public Set getRegistrationGroupItems(String group) { Set groupSet = registrationGroup.get(group); if (groupSet != null) { return Collections.unmodifiableSet(groupSet); } else { return Collections.emptySet(); } } public List getAttributeDelegates() { return Collections.unmodifiableList(attributeDelegates); } public List getPreInstantiateDelegates() { return Collections.unmodifiableList(preInstantiateDelegates); } public List getPostInstantiateDelegates() { return Collections.unmodifiableList(postInstantiateDelegates); } public List getPostNodeCompletionDelegates() { return Collections.unmodifiableList(postNodeCompletionDelegates); } /** * @return the context of the current node. */ public Map getContext() { LinkedList> contexts = getProxyBuilder().contexts.get(); if (contexts != null && !contexts.isEmpty()) { return contexts.getFirst(); } return null; } /** * @return the current node being built. */ public Object getCurrent() { return getContextAttribute(CURRENT_NODE); } /** * @return the factory that built the current node. */ public Factory getCurrentFactory() { return (Factory) getContextAttribute(CURRENT_FACTORY); } /** * @return the factory of the parent of the current node. */ public String getCurrentName() { return (String) getContextAttribute(CURRENT_NAME); } /** * @return the builder that built the current node. */ public FactoryBuilderSupport getCurrentBuilder() { return (FactoryBuilderSupport) getContextAttribute(CURRENT_BUILDER); } /** * @return the node of the parent of the current node. */ public Object getParentNode() { return getContextAttribute(PARENT_NODE); } /** * @return the factory of the parent of the current node. */ public Factory getParentFactory() { return (Factory) getContextAttribute(PARENT_FACTORY); } /** * @return the context of the parent of the current node. */ public Map getParentContext() { return (Map) getContextAttribute(PARENT_CONTEXT); } /** * @return the name of the parent of the current node. */ public String getParentName() { return (String) getContextAttribute(PARENT_NAME); } public FactoryBuilderSupport getChildBuilder() { return (FactoryBuilderSupport) getContextAttribute(CHILD_BUILDER); } public Object getContextAttribute(String key) { Map context = getContext(); if (context != null) { return context.get(key); } return null; } /** * Convenience method when no arguments are required * * @param methodName the name of the method to invoke * @return the result of the call */ public Object invokeMethod(String methodName) { return getProxyBuilder().invokeMethod(methodName, null); } public Object invokeMethod(String methodName, Object args) { Object name = getProxyBuilder().getName(methodName); Object result; Object previousContext = getProxyBuilder().getContext(); try { result = getProxyBuilder().doInvokeMethod(methodName, name, args); } catch (RuntimeException e) { // remove contexts created after we started if (getContexts().contains(previousContext)) { Map context = getProxyBuilder().getContext(); while (context != null && context != previousContext) { getProxyBuilder().popContext(); context = getProxyBuilder().getContext(); } } throw e; } return result; } /** * Add an attribute delegate so it can intercept attributes being set. * Attribute delegates are fired in a FILO pattern, so that nested delegates * get first crack. * * @param attrDelegate the closure to be called * @return attrDelegate */ public Closure addAttributeDelegate(Closure attrDelegate) { getProxyBuilder().attributeDelegates.addFirst(attrDelegate); return attrDelegate; } /** * Remove the most recently added instance of the attribute delegate. * * @param attrDelegate the instance of the closure to be removed */ public void removeAttributeDelegate(Closure attrDelegate) { getProxyBuilder().attributeDelegates.remove(attrDelegate); } /** * Add a preInstantiate delegate so it can intercept nodes before they are * created. PreInstantiate delegates are fired in a FILO pattern, so that * nested delegates get first crack. * * @param delegate the closure to invoke * @return delegate */ public Closure addPreInstantiateDelegate(Closure delegate) { getProxyBuilder().preInstantiateDelegates.addFirst(delegate); return delegate; } /** * Remove the most recently added instance of the preInstantiate delegate. * * @param delegate the closure to invoke */ public void removePreInstantiateDelegate(Closure delegate) { getProxyBuilder().preInstantiateDelegates.remove(delegate); } /** * Add a postInstantiate delegate so it can intercept nodes after they are * created. PostInstantiate delegates are fired in a FILO pattern, so that * nested delegates get first crack. * * @param delegate the closure to invoke * @return delegate */ public Closure addPostInstantiateDelegate(Closure delegate) { getProxyBuilder().postInstantiateDelegates.addFirst(delegate); return delegate; } /** * Remove the most recently added instance of the postInstantiate delegate. * * @param delegate the closure to invoke */ public void removePostInstantiateDelegate(Closure delegate) { getProxyBuilder().postInstantiateDelegates.remove(delegate); } /** * Add a nodeCompletion delegate so it can intercept nodes after they done * with building. NodeCompletion delegates are fired in a FILO pattern, so * that nested delegates get first crack. * * @param delegate the closure to invoke * @return delegate */ public Closure addPostNodeCompletionDelegate(Closure delegate) { getProxyBuilder().postNodeCompletionDelegates.addFirst(delegate); return delegate; } /** * Remove the most recently added instance of the nodeCompletion delegate. * * @param delegate the closure to be removed */ public void removePostNodeCompletionDelegate(Closure delegate) { getProxyBuilder().postNodeCompletionDelegates.remove(delegate); } public void registerExplicitProperty(String name, Closure getter, Closure setter) { registerExplicitProperty(name, registrationGroupName, getter, setter); } public void registerExplicitProperty(String name, String groupName, Closure getter, Closure setter) { // set the delegate to FBS so the closure closes over the builder if (getter != null) getter.setDelegate(this); if (setter != null) setter.setDelegate(this); explicitProperties.put(name, new Closure[]{getter, setter}); String methodNameBase = MetaClassHelper.capitalize(name); if (getter != null) { getRegistrationGroup(groupName).add("get" + methodNameBase); } if (setter != null) { getRegistrationGroup(groupName).add("set" + methodNameBase); } } public void registerExplicitMethod(String name, Closure closure) { registerExplicitMethod(name, registrationGroupName, closure); } public void registerExplicitMethod(String name, String groupName, Closure closure) { // set the delegate to FBS so the closure closes over the builder closure.setDelegate(this); explicitMethods.put(name, closure); getRegistrationGroup(groupName).add(name); } /** * Registers a factory for a JavaBean.
    * The JavaBean class should have a no-args constructor. * * @param theName name of the node * @param beanClass the factory to handle the name */ public void registerBeanFactory(String theName, Class beanClass) { registerBeanFactory(theName, registrationGroupName, beanClass); } /** * Registers a factory for a JavaBean.
    * The JavaBean class should have a no-args constructor. * * @param theName name of the node * @param groupName thr group to register this node in * @param beanClass the factory to handle the name */ public void registerBeanFactory(String theName, String groupName, final Class beanClass) { getProxyBuilder().registerFactory(theName, new AbstractFactory() { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { if (checkValueIsTypeNotString(value, name, beanClass)) { return value; } else { return beanClass.newInstance(); } } }); getRegistrationGroup(groupName).add(theName); } /** * Registers a factory for a node name. * * @param name the name of the node * @param factory the factory to return the values */ public void registerFactory(String name, Factory factory) { registerFactory(name, registrationGroupName, factory); } /** * Registers a factory for a node name. * * @param name the name of the node * @param groupName thr group to register this node in * @param factory the factory to return the values */ public void registerFactory(String name, String groupName, Factory factory) { getProxyBuilder().factories.put(name, factory); getRegistrationGroup(groupName).add(name); factory.onFactoryRegistration(this, name, groupName); } /** * This method is responsible for instantiating a node and configure its * properties. * * @param name the name of the node * @param attributes the attributes for the node * @param value the value arguments for the node * @return the object return from the factory */ protected Object createNode(Object name, Map attributes, Object value) { Object node; Factory factory = getProxyBuilder().resolveFactory(name, attributes, value); if (factory == null) { LOG.log(Level.WARNING, "Could not find match for name '" + name + "'"); throw new MissingMethodExceptionNoStack((String) name, Object.class, new Object[]{attributes, value}); //return null; } getProxyBuilder().getContext().put(CURRENT_FACTORY, factory); getProxyBuilder().getContext().put(CURRENT_NAME, String.valueOf(name)); getProxyBuilder().preInstantiate(name, attributes, value); try { node = factory.newInstance(getProxyBuilder().getChildBuilder(), name, value, attributes); if (node == null) { LOG.log(Level.WARNING, "Factory for name '" + name + "' returned null"); return null; } if (LOG.isLoggable(Level.FINE)) { LOG.fine("For name: " + name + " created node: " + node); } } catch (Exception e) { throw new RuntimeException("Failed to create component for '" + name + "' reason: " + e, e); } getProxyBuilder().postInstantiate(name, attributes, node); getProxyBuilder().handleNodeAttributes(node, attributes); return node; } /** * This is a hook for subclasses to plugin a custom strategy for mapping * names to factories. * * @param name the name of the factory * @param attributes the attributes from the node * @param value value arguments from te node * @return the Factory associated with name.
    */ protected Factory resolveFactory(Object name, Map attributes, Object value) { getProxyBuilder().getContext().put(CHILD_BUILDER, getProxyBuilder()); return getProxyBuilder().factories.get(name); } /** * This is a hook for subclasses to plugin a custom strategy for mapping * names to explicit methods. * * @param methodName the name of the explicit method * @param args the arguments for the method * @return the closure for the matched explicit method.
    */ @SuppressWarnings({"UnusedDeclaration"}) protected Closure resolveExplicitMethod(String methodName, Object args) { return explicitMethods.get(methodName); } /** * This is a hook for subclasses to plugin a custom strategy for mapping * names to property methods. * * @param propertyName the name of the explicit method * @return the get and set closures (in that order) for the matched explicit property.
    */ protected Closure[] resolveExplicitProperty(String propertyName) { return explicitProperties.get(propertyName); } /** * This method is the workhorse of the builder. * * @param methodName the name of the method being invoked * @param name the name of the node * @param args the arguments passed into the node * @return the object from the factory */ private Object doInvokeMethod(String methodName, Object name, Object args) { Reference explicitResult = new Reference(); if (checkExplicitMethod(methodName, args, explicitResult)) { return explicitResult.get(); } else { return dispathNodeCall(name, args); } } protected boolean checkExplicitMethod(String methodName, Object args, Reference result) { Closure explicitMethod = resolveExplicitMethod(methodName, args); if (explicitMethod != null) { if (args instanceof Object[]) { result.set(explicitMethod.call((Object[]) args)); } else { //todo push through InvokerHelper.asList? result.set(explicitMethod.call(args)); } return true; } else { return false; } } protected Object dispathNodeCall(Object name, Object args) { Object node; Closure closure = null; List list = InvokerHelper.asList(args); final boolean needToPopContext; if (getProxyBuilder().getContexts().isEmpty()) { // should be called on first build method only getProxyBuilder().newContext(); needToPopContext = true; } else { needToPopContext = false; } try { Map namedArgs = Collections.EMPTY_MAP; // the arguments come in like [named_args?, args..., closure?] // so peel off a hashmap from the front, and a closure from the // end and presume that is what they meant, since there is // no way to distinguish node(a:b,c,d) {..} from // node([a:b],[c,d], {..}), i.e. the user can deliberately confuse // the builder and there is nothing we can really do to prevent // that if ((list.size() > 0) && (list.get(0) instanceof LinkedHashMap)) { namedArgs = (Map) list.get(0); list = list.subList(1, list.size()); } if ((list.size() > 0) && (list.get(list.size() - 1) instanceof Closure)) { closure = (Closure) list.get(list.size() - 1); list = list.subList(0, list.size() - 1); } Object arg; if (list.size() == 0) { arg = null; } else if (list.size() == 1) { arg = list.get(0); } else { arg = list; } node = getProxyBuilder().createNode(name, namedArgs, arg); Object current = getProxyBuilder().getCurrent(); if (current != null) { getProxyBuilder().setParent(current, node); } if (closure != null) { Factory parentFactory = getProxyBuilder().getCurrentFactory(); if (parentFactory.isLeaf()) { throw new RuntimeException("'" + name + "' doesn't support nesting."); } boolean processContent = true; if (parentFactory.isHandlesNodeChildren()) { processContent = parentFactory.onNodeChildren(this, node, closure); } if (processContent) { // push new node on stack String parentName = getProxyBuilder().getCurrentName(); Map parentContext = getProxyBuilder().getContext(); getProxyBuilder().newContext(); try { getProxyBuilder().getContext().put(OWNER, closure.getOwner()); getProxyBuilder().getContext().put(CURRENT_NODE, node); getProxyBuilder().getContext().put(PARENT_FACTORY, parentFactory); getProxyBuilder().getContext().put(PARENT_NODE, current); getProxyBuilder().getContext().put(PARENT_CONTEXT, parentContext); getProxyBuilder().getContext().put(PARENT_NAME, parentName); getProxyBuilder().getContext().put(PARENT_BUILDER, parentContext.get(CURRENT_BUILDER)); getProxyBuilder().getContext().put(CURRENT_BUILDER, parentContext.get(CHILD_BUILDER)); // lets register the builder as the delegate getProxyBuilder().setClosureDelegate(closure, node); closure.call(); } finally { getProxyBuilder().popContext(); } } } getProxyBuilder().nodeCompleted(current, node); node = getProxyBuilder().postNodeCompletion(current, node); } finally { if (needToPopContext) { // pop the first context getProxyBuilder().popContext(); } } return node; } /** * A hook to allow names to be converted into some other object such as a * QName in XML or ObjectName in JMX. * * @param methodName the name of the desired method * @return the object representing the name */ public Object getName(String methodName) { if (getProxyBuilder().nameMappingClosure != null) { return getProxyBuilder().nameMappingClosure.call(methodName); } return methodName; } /** * Proxy builders are useful for changing the building context, thus * enabling mix & match builders. * * @return the current builder that serves as a proxy.
    */ protected FactoryBuilderSupport getProxyBuilder() { FactoryBuilderSupport proxy = localProxyBuilder.get(); if (proxy == null) { return globalProxyBuilder; } else { return proxy; } } /** * Sets the builder to be used as a proxy. * * @param proxyBuilder the new proxy */ protected void setProxyBuilder(FactoryBuilderSupport proxyBuilder) { globalProxyBuilder = proxyBuilder; } public Closure getNameMappingClosure() { return nameMappingClosure; } public void setNameMappingClosure(Closure nameMappingClosure) { this.nameMappingClosure = nameMappingClosure; } /** * Assigns any existing properties to the node.
    * It will call attributeDelegates before passing control to the factory * that built the node. * * @param node the object returned by tne node factory * @param attributes the attributes for the node */ protected void handleNodeAttributes(Object node, Map attributes) { // first, short circuit if (node == null) { return; } for (Closure attrDelegate : getProxyBuilder().attributeDelegates) { FactoryBuilderSupport builder = this; if (attrDelegate.getOwner() instanceof FactoryBuilderSupport) { builder = (FactoryBuilderSupport) attrDelegate.getOwner(); } else if (attrDelegate.getDelegate() instanceof FactoryBuilderSupport) { builder = (FactoryBuilderSupport) attrDelegate.getDelegate(); } attrDelegate.call(new Object[]{builder, node, attributes}); } if (getProxyBuilder().getCurrentFactory().onHandleNodeAttributes(getProxyBuilder().getChildBuilder(), node, attributes)) { getProxyBuilder().setNodeAttributes(node, attributes); } } /** * Pushes a new context on the stack. */ protected void newContext() { getContexts().addFirst(new HashMap()); } /** * A hook to allow nodes to be processed once they have had all of their * children applied. * * @param node the current node being processed * @param parent the parent of the node being processed */ protected void nodeCompleted(Object parent, Object node) { getProxyBuilder().getCurrentFactory().onNodeCompleted(getProxyBuilder().getChildBuilder(), parent, node); } /** * Removes the last context from the stack. * * @return the contet just removed */ protected Map popContext() { if (!getProxyBuilder().getContexts().isEmpty()) { return getProxyBuilder().getContexts().removeFirst(); } return null; } /** * A hook after the factory creates the node and before attributes are set.
    * It will call any registered postInstantiateDelegates, if you override * this method be sure to call this impl somewhere in your code. * * @param name the name of the node * @param attributes the attributes for the node * @param node the object created by the node factory */ protected void postInstantiate(Object name, Map attributes, Object node) { for (Closure postInstantiateDelegate : getProxyBuilder().postInstantiateDelegates) { (postInstantiateDelegate).call(new Object[]{this, attributes, node}); } } /** * A hook to allow nodes to be processed once they have had all of their * children applied and allows the actual node object that represents the * Markup element to be changed.
    * It will call any registered postNodeCompletionDelegates, if you override * this method be sure to call this impl at the end of your code. * * @param node the current node being processed * @param parent the parent of the node being processed * @return the node, possibly new, that represents the markup element */ protected Object postNodeCompletion(Object parent, Object node) { for (Closure postNodeCompletionDelegate : getProxyBuilder().postNodeCompletionDelegates) { (postNodeCompletionDelegate).call(new Object[]{this, parent, node}); } return node; } /** * A hook before the factory creates the node.
    * It will call any registered preInstantiateDelegates, if you override this * method be sure to call this impl somewhere in your code. * * @param name the name of the node * @param attributes the attributes of the node * @param value the value argument(s) of the node */ protected void preInstantiate(Object name, Map attributes, Object value) { for (Closure preInstantiateDelegate : getProxyBuilder().preInstantiateDelegates) { (preInstantiateDelegate).call(new Object[]{this, attributes, value}); } } /** * Clears the context stack. */ protected void reset() { getProxyBuilder().getContexts().clear(); } /** * A strategy method to allow derived builders to use builder-trees and * switch in different kinds of builders. This method should call the * setDelegate() method on the closure which by default passes in this but * if node is-a builder we could pass that in instead (or do something wacky * too) * * @param closure the closure on which to call setDelegate() * @param node the node value that we've just created, which could be a * builder */ @SuppressWarnings({"UnusedDeclaration"}) protected void setClosureDelegate(Closure closure, Object node) { closure.setDelegate(this); } /** * Maps attributes key/values to properties on node. * * @param node the object from the node * @param attributes the attributes to be set */ protected void setNodeAttributes(Object node, Map attributes) { // set the properties //noinspection unchecked for (Map.Entry entry : (Set) attributes.entrySet()) { String property = entry.getKey().toString(); Object value = entry.getValue(); InvokerHelper.setProperty(node, property, value); } } /** * Strategy method to establish parent/child relationships. * * @param parent the object from the parent node * @param child the object from the child node */ protected void setParent(Object parent, Object child) { getProxyBuilder().getCurrentFactory().setParent(getProxyBuilder().getChildBuilder(), parent, child); Factory parentFactory = getProxyBuilder().getParentFactory(); if (parentFactory != null) { parentFactory.setChild(getProxyBuilder().getCurrentBuilder(), parent, child); } } /** * @return the stack of available contexts. */ protected LinkedList> getContexts() { LinkedList> contexts = getProxyBuilder().contexts.get(); if (contexts == null) { contexts = new LinkedList>(); getProxyBuilder().contexts.set(contexts); } return contexts; } /** * Stores the thread local states in a Map that can be passed across threads * @return the map */ protected Map getContinuationData() { Map data = new HashMap(); data.put("proxyBuilder", localProxyBuilder.get()); data.put("contexts", contexts.get()); return data; } /** * Restores the state of the current builder to the same state as an older build. * * Caution, this will destroy rather than merge the current build context if there is any, * @param data the data retrieved from a compatible getContinuationData call */ protected void restoreFromContinuationData(Map data) { //noinspection unchecked localProxyBuilder.set((FactoryBuilderSupport) data.get("proxyBuilder")); //noinspection unchecked contexts.set((LinkedList>) data.get("contexts")); } public Object build(Class viewClass) { if (Script.class.isAssignableFrom(viewClass)) { Script script = InvokerHelper.createScript(viewClass, this); return build(script); } else { throw new RuntimeException("Only scripts can be executed via build(Class)"); } } public Object build(Script script) { // this used to be synchronized, but we also used to remove the // metaclass. Since adding the metaclass is now a side effect, we // don't need to ensure the meta-class won't be observed and don't // need to hide the side effect. MetaClass scriptMetaClass = script.getMetaClass(); script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this)); script.setBinding(this); Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME); try { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName()); return script.run(); } finally { if(oldScriptName != null) { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName); } else { getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME); } } } public Object build(final String script, GroovyClassLoader loader) { return build(loader.parseClass(script)); } /** * Switches the builder's proxyBuilder during the execution of a closure.
    * This is useful to temporary change the building context to another builder * without the need for a contrived setup. It will also take care of restoring * the previous proxyBuilder when the execution finishes, even if an exception * was thrown from inside the closure. * * @param builder the temporary builder to switch to as proxyBuilder. * @param closure the closure to be executed under the temporary builder. * @return the execution result of the closure. * @throws RuntimeException - any exception the closure might have thrown during * execution. */ public Object withBuilder(FactoryBuilderSupport builder, Closure closure) { if (builder == null || closure == null) { return null; } Object result = null; Object previousContext = getProxyBuilder().getContext(); FactoryBuilderSupport previousProxyBuilder = localProxyBuilder.get(); try { localProxyBuilder.set(builder); closure.setDelegate(builder); result = closure.call(); } catch (RuntimeException e) { // remove contexts created after we started localProxyBuilder.set(previousProxyBuilder); if (getProxyBuilder().getContexts().contains(previousContext)) { Map context = getProxyBuilder().getContext(); while (context != null && context != previousContext) { getProxyBuilder().popContext(); context = getProxyBuilder().getContext(); } } throw e; } finally { localProxyBuilder.set(previousProxyBuilder); } return result; } /** * Switches the builder's proxyBuilder during the execution of a closure.
    * This is useful to temporary change the building context to another builder * without the need for a contrived setup. It will also take care of restoring * the previous proxyBuilder when the execution finishes, even if an exception * was thrown from inside the closure. Additionally it will use the closure's * result as the value for the node identified by 'name'. * * @param builder the temporary builder to switch to as proxyBuilder. * @param name the node to build on the 'parent' builder. * @param closure the closure to be executed under the temporary builder. * @return a node that responds to value of name with the closure's result as its * value. * @throws RuntimeException - any exception the closure might have thrown during * execution. */ public Object withBuilder(FactoryBuilderSupport builder, String name, Closure closure) { if (name == null) { return null; } Object result = getProxyBuilder().withBuilder(builder, closure); return getProxyBuilder().invokeMethod(name, new Object[]{result}); } /** * Switches the builder's proxyBuilder during the execution of a closure.
    * This is useful to temporary change the building context to another builder * without the need for a contrived setup. It will also take care of restoring * the previous proxyBuilder when the execution finishes, even if an exception * was thrown from inside the closure. Additionally it will use the closure's * result as the value for the node identified by 'name' and assign any attributes * that might have been set. * * @param attributes additional properties for the node on the parent builder. * @param builder the temporary builder to switch to as proxyBuilder. * @param name the node to build on the 'parent' builder. * @param closure the closure to be executed under the temporary builder. * @return a node that responds to value of name with the closure's result as its * value. * @throws RuntimeException - any exception the closure might have thrown during * execution. */ public Object withBuilder(Map attributes, FactoryBuilderSupport builder, String name, Closure closure) { if (name == null) { return null; } Object result = getProxyBuilder().withBuilder(builder, closure); return getProxyBuilder().invokeMethod(name, new Object[]{attributes, result}); } public void addDisposalClosure(Closure closure) { disposalClosures.add(closure); } public void dispose() { for (int i = disposalClosures.size() - 1; i >= 0; i--) { disposalClosures.get(i).call(); } } } class FactoryInterceptorMetaClass extends DelegatingMetaClass { FactoryBuilderSupport factory; public FactoryInterceptorMetaClass(MetaClass delegate, FactoryBuilderSupport factory) { super(delegate); this.factory = factory; } public Object invokeMethod(Object object, String methodName, Object arguments) { try { return delegate.invokeMethod(object, methodName, arguments); } catch (MissingMethodException mme) { // attempt factory resolution try { if (factory.getMetaClass().respondsTo(factory, methodName).isEmpty()) { // dispatch to factories if it is not a literal method return factory.invokeMethod(methodName, arguments); } else { return InvokerHelper.invokeMethod(factory, methodName, arguments); } } catch (MissingMethodException mme2) { // chain secondary exception Throwable root = mme; while (root.getCause() != null) { root = root.getCause(); } root.initCause(mme2); // throw original throw mme; } } } public Object invokeMethod(Object object, String methodName, Object[] arguments) { try { return delegate.invokeMethod(object, methodName, arguments); } catch (MissingMethodException mme) { // attempt factory resolution try { if (factory.getMetaClass().respondsTo(factory, methodName).isEmpty()) { // dispatch to factories if it is not a literal method return factory.invokeMethod(methodName, arguments); } else { return InvokerHelper.invokeMethod(factory, methodName, arguments); } } catch (MissingMethodException mme2) { // chain secondary exception Throwable root = mme; while (root.getCause() != null) { root = root.getCause(); } root.initCause(mme2); // throw original throw mme; } } } } groovy-1.8.6/src/main/groovy/util/ObservableMap.java0000644001501200150120000003520311715031256021777 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.*; /** * Map decorator that will trigger PropertyChangeEvents when a value changes.
    * An optional Closure may be specified and will work as a filter, if it returns * true the property will trigger an event (if the value indeed changed), * otherwise it won't. The Closure may receive 1 or 2 parameters, the single one * being the value, the other one both the key and value, for example: *

     * // skip all properties whose value is a closure
     * def map = new ObservableMap( {!(it instanceof Closure)} )
     * 

    * // skip all properties whose name matches a regex * def map = new ObservableMap( { name, value -> !(name =~ /[A-Z+]/) } ) *

    *

    *

    The current implementation will trigger specialized events in the following scenarios, * you need not register a different listener as those events extend from PropertyChangeEvent *

      *
    • ObservableMap.PropertyAddedEvent - a new property is added to the map
    • *
    • ObservableMap.PropertyRemovedEvent - a property is removed from the map
    • *
    • ObservableMap.PropertyUpdatedEvent - a property changes value (same as regular PropertyChangeEvent)
    • *
    • ObservableMap.PropertyClearedEvent - all properties have been removed from the map
    • *
    • ObservableMap.MultiPropertyEvent - triggered by calling map.putAll(), contains Added|Updated events
    • *

    *

    *

    * Bound properties *

      *
    • content - read-only.
    • *
    • size - read-only.
    • *
    *

    * * @author Andres Almiray */ public class ObservableMap implements Map { private Map delegate; private PropertyChangeSupport pcs; private Closure test; public static final String SIZE_PROPERTY = "size"; public static final String CONTENT_PROPERTY = "content"; public static final String CLEARED_PROPERTY = "cleared"; public ObservableMap() { this(new LinkedHashMap(), null); } public ObservableMap(Closure test) { this(new LinkedHashMap(), test); } public ObservableMap(Map delegate) { this(delegate, null); } public ObservableMap(Map delegate, Closure test) { this.delegate = delegate; this.test = test; pcs = new PropertyChangeSupport(this); } protected Map getMapDelegate() { return delegate; } protected Closure getTest() { return test; } public Map getContent() { return Collections.unmodifiableMap(delegate); } protected void firePropertyClearedEvent(Map values) { firePropertyEvent(new PropertyClearedEvent(this, values)); } protected void firePropertyAddedEvent(Object key, Object value) { firePropertyEvent(new PropertyAddedEvent(this, String.valueOf(key), value)); } protected void firePropertyUpdatedEvent(Object key, Object oldValue, Object newValue) { firePropertyEvent(new PropertyUpdatedEvent(this, String.valueOf(key), oldValue, newValue)); } protected void fireMultiPropertyEvent(List events) { firePropertyEvent(new MultiPropertyEvent(this, (PropertyEvent[]) events.toArray(new PropertyEvent[events.size()]))); } protected void fireMultiPropertyEvent(PropertyEvent[] events) { firePropertyEvent(new MultiPropertyEvent(this, events)); } protected void firePropertyRemovedEvent(Object key, Object value) { firePropertyEvent(new PropertyRemovedEvent(this, String.valueOf(key), value)); } protected void firePropertyEvent(PropertyEvent event) { pcs.firePropertyChange(event); } protected void fireSizeChangedEvent(int oldValue, int newValue) { pcs.firePropertyChange(new PropertyChangeEvent(this, SIZE_PROPERTY, oldValue, newValue)); } // Map interface public void clear() { int oldSize = size(); Map values = new HashMap(); if (!delegate.isEmpty()) { values.putAll(delegate); } delegate.clear(); firePropertyClearedEvent(values); fireSizeChangedEvent(oldSize, size()); } public boolean containsKey(Object key) { return delegate.containsKey(key); } public boolean containsValue(Object value) { return delegate.containsValue(value); } public Set entrySet() { return delegate.entrySet(); } public boolean equals(Object o) { return delegate.equals(o); } public Object get(Object key) { return delegate.get(key); } public int hashCode() { return delegate.hashCode(); } public boolean isEmpty() { return delegate.isEmpty(); } public Set keySet() { return delegate.keySet(); } public Object put(Object key, Object value) { int oldSize = size(); Object oldValue = null; boolean newKey = !delegate.containsKey(key); if (test != null) { oldValue = delegate.put(key, value); Object result = null; if (test.getMaximumNumberOfParameters() == 2) { result = test.call(new Object[]{key, value}); } else { result = test.call(value); } if (result != null && result instanceof Boolean && (Boolean) result) { if (newKey) { firePropertyAddedEvent(key, value); fireSizeChangedEvent(oldSize, size()); } else if (oldValue != value) { firePropertyUpdatedEvent(key, oldValue, value); } } } else { oldValue = delegate.put(key, value); if (newKey) { firePropertyAddedEvent(key, value); fireSizeChangedEvent(oldSize, size()); } else if (oldValue != value) { firePropertyUpdatedEvent(key, oldValue, value); } } return oldValue; } public void putAll(Map map) { int oldSize = size(); if (map != null) { List events = new ArrayList(); for (Object o : map.entrySet()) { Entry entry = (Entry) o; String key = String.valueOf(entry.getKey()); Object newValue = entry.getValue(); Object oldValue = null; boolean newKey = !delegate.containsKey(key); if (test != null) { oldValue = delegate.put(key, newValue); Object result = null; if (test.getMaximumNumberOfParameters() == 2) { result = test.call(new Object[]{key, newValue}); } else { result = test.call(newValue); } if (result != null && result instanceof Boolean && (Boolean) result) { if (newKey) { events.add(new PropertyAddedEvent(this, key, newValue)); } else if (oldValue != newValue) { events.add(new PropertyUpdatedEvent(this, key, oldValue, newValue)); } } } else { oldValue = delegate.put(key, newValue); if (newKey) { events.add(new PropertyAddedEvent(this, key, newValue)); } else if (oldValue != newValue) { events.add(new PropertyUpdatedEvent(this, key, oldValue, newValue)); } } } if (events.size() > 0) { fireMultiPropertyEvent(events); fireSizeChangedEvent(oldSize, size()); } } } public Object remove(Object key) { int oldSize = size(); Object result = delegate.remove(key); if (key != null) { firePropertyRemovedEvent(key, result); fireSizeChangedEvent(oldSize, size()); } return result; } public int size() { return delegate.size(); } public int getSize() { return size(); } public Collection values() { return delegate.values(); } // observable interface public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } public PropertyChangeListener[] getPropertyChangeListeners() { return pcs.getPropertyChangeListeners(); } public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { return pcs.getPropertyChangeListeners(propertyName); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.removePropertyChangeListener(propertyName, listener); } public boolean hasListeners(String propertyName) { return pcs.hasListeners(propertyName); } public enum ChangeType { ADDED, UPDATED, REMOVED, CLEARED, MULTI, NONE; public static final Object oldValue = new Object(); public static final Object newValue = new Object(); public static ChangeType resolve(int ordinal) { switch (ordinal) { case 0: return ADDED; case 2: return REMOVED; case 3: return CLEARED; case 4: return MULTI; case 5: return NONE; case 1: default: return UPDATED; } } } public abstract static class PropertyEvent extends PropertyChangeEvent { /** * deprecated */ public static final int ADDED = ChangeType.ADDED.ordinal(); /** * deprecated */ public static final int UPDATED = ChangeType.UPDATED.ordinal(); /** * deprecated */ public static final int REMOVED = ChangeType.REMOVED.ordinal(); /** * deprecated */ public static final int CLEARED = ChangeType.CLEARED.ordinal(); /** * deprecated */ public static final int MULTI = ChangeType.MULTI.ordinal(); private ChangeType type; /** * @deprecated */ public PropertyEvent(Object source, String propertyName, Object oldValue, Object newValue, int type) { this(source, propertyName, oldValue, newValue, ChangeType.resolve(type)); } public PropertyEvent(Object source, String propertyName, Object oldValue, Object newValue, ChangeType type) { super(source, propertyName, oldValue, newValue); this.type = type; } public int getType() { return type.ordinal(); } public ChangeType getChangeType() { return type; } public String getTypeAsString() { return type.name().toUpperCase(); } } public static class PropertyAddedEvent extends PropertyEvent { public PropertyAddedEvent(Object source, String propertyName, Object newValue) { super(source, propertyName, null, newValue, ChangeType.ADDED); } } public static class PropertyUpdatedEvent extends PropertyEvent { public PropertyUpdatedEvent(Object source, String propertyName, Object oldValue, Object newValue) { super(source, propertyName, oldValue, newValue, ChangeType.UPDATED); } } public static class PropertyRemovedEvent extends PropertyEvent { public PropertyRemovedEvent(Object source, String propertyName, Object oldValue) { super(source, propertyName, oldValue, null, ChangeType.REMOVED); } } public static class PropertyClearedEvent extends PropertyEvent { /** * @deprecated */ public static final String CLEAR_PROPERTY = ObservableMap.CLEARED_PROPERTY; private Map values = new HashMap(); public PropertyClearedEvent(Object source, Map values) { super(source, ObservableMap.CLEARED_PROPERTY, values, null, ChangeType.CLEARED); if (values != null) { this.values.putAll(values); } } public Map getValues() { return Collections.unmodifiableMap(values); } } public static class MultiPropertyEvent extends PropertyEvent { public static final String MULTI_PROPERTY = "groovy_util_ObservableMap_MultiPropertyEvent_MULTI"; private PropertyEvent[] events = new PropertyEvent[0]; public MultiPropertyEvent(Object source, PropertyEvent[] events) { super(source, MULTI_PROPERTY, ChangeType.oldValue, ChangeType.newValue, ChangeType.MULTI); if (events != null && events.length > 0) { this.events = new PropertyEvent[events.length]; System.arraycopy(events, 0, this.events, 0, events.length); } } public PropertyEvent[] getEvents() { PropertyEvent[] copy = new PropertyEvent[events.length]; System.arraycopy(events, 0, copy, 0, events.length); return copy; } } } groovy-1.8.6/src/main/groovy/util/Expando.java0000644001501200150120000001222111627206700020646 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaExpandoProperty; import groovy.lang.MissingPropertyException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.List; import java.util.ArrayList; /** * Represents a dynamically expandable bean. * * @author James Strachan * @author Hein Meling * @author Pilho Kim * @version $Revision$ */ public class Expando extends GroovyObjectSupport { private Map expandoProperties; public Expando() { } public Expando(Map expandoProperties) { this.expandoProperties = expandoProperties; } /** * @return the dynamically expanded properties */ public Map getProperties() { if (expandoProperties == null) { expandoProperties = createMap(); } return expandoProperties; } public List getMetaPropertyValues() { // run through all our current properties and create MetaProperty objects List ret = new ArrayList(); for (Object o : getProperties().entrySet()) { Entry entry = (Entry) o; ret.add(new MetaExpandoProperty(entry)); } return ret; } public Object getProperty(String property) { // always use the expando properties first Object result = getProperties().get(property); if (result != null) return result; try { return super.getProperty(property); } catch (MissingPropertyException e) { // IGNORE } return null; } public void setProperty(String property, Object newValue) { // always use the expando properties getProperties().put(property, newValue); } public Object invokeMethod(String name, Object args) { try { return super.invokeMethod(name, args); } catch (GroovyRuntimeException e) { // br should get a "native" property match first. getProperty includes such fall-back logic Object value = this.getProperty(name); if (value instanceof Closure) { Closure closure = (Closure) value; closure = (Closure) closure.clone(); closure.setDelegate(this); return closure.call((Object[]) args); } else { throw e; } } } /** * This allows toString to be overridden by a closure field method attached * to the expando object. * * @see java.lang.Object#toString() */ public String toString() { Object method = getProperties().get("toString"); if (method != null && method instanceof Closure) { // invoke overridden toString closure method Closure closure = (Closure) method; closure.setDelegate(this); return closure.call().toString(); } else { return expandoProperties.toString(); } } /** * This allows equals to be overridden by a closure field method attached * to the expando object. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { Object method = getProperties().get("equals"); if (method != null && method instanceof Closure) { // invoke overridden equals closure method Closure closure = (Closure) method; closure.setDelegate(this); Boolean ret = (Boolean) closure.call(obj); return ret.booleanValue(); } else { return super.equals(obj); } } /** * This allows hashCode to be overridden by a closure field method attached * to the expando object. * * @see java.lang.Object#hashCode() */ public int hashCode() { Object method = getProperties().get("hashCode"); if (method != null && method instanceof Closure) { // invoke overridden hashCode closure method Closure closure = (Closure) method; closure.setDelegate(this); Integer ret = (Integer) closure.call(); return ret.intValue(); } else { return super.hashCode(); } } /** * Factory method to create a new Map used to store the expando properties map * * @return a newly created Map implementation */ protected Map createMap() { return new HashMap(); } } groovy-1.8.6/src/main/groovy/util/JavadocAssertionTestSuite.groovy0000644001501200150120000001146111715031256024772 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util import junit.framework.TestSuite import junit.framework.Test import junit.textui.TestRunner /** * JavadocAssertionTestSuite will dynamically create test cases from Groovy assertions placed within * Javadoc comments. Assertions should be placed within an html tag with a class="groovyTestCase" * attribute assignment. Example: *
    <pre class="groovyTestCase"> assert "example".size() == 7 </pre>
    * * Source files will be read from the directory specified by the javadocAssertion.src.dir * system property, including all files matching javadocAssertion.src.pattern and * excluding files matching the javadocAssertion.src.excludesPattern. * * By default all .java and .groovy source files from ./src will * be scanned for assertions. * * You can also run this class as an application from the command line (assumes Groovy, JUnit and Ant * are on the classpath). As an example: *

    * * java groovy.util.JavadocAssertionTestSuite src/main * * * @author Merlyn Albery-Speyer */ class JavadocAssertionTestSuite extends TestSuite { /** The System Property to set as base directory for collection of Classes. * The pattern will be used as an Ant fileset include basedir. * Key is "javadocAssertion.src.dir". * Defaults to the ./src directory */ public static final String SYSPROP_SRC_DIR = "javadocAssertion.src.dir"; /** The System Property to set as the filename pattern for collection of Classes. * The pattern will be used as Regular Expression pattern applied with the find * operator against each candidate file.path. * Key is "javadocAssertion.src.pattern". * Defaults to including all .java and .groovy files. */ public static final String SYSPROP_SRC_PATTERN = "javadocAssertion.src.pattern"; /** The System Property to set as a filename excludes pattern for collection of Classes. * When non-empty, the pattern will be used as Regular Expression pattern applied with the * find operator against each candidate file.path. * Key is "javadocAssertion.src.excludesPattern". * Default value is "". */ public static final String SYSPROP_SRC_EXCLUDES_PATTERN = "javadocAssertion.src.excludesPattern"; private static JavadocAssertionTestBuilder testBuilder = new JavadocAssertionTestBuilder() private static IFileNameFinder finder = new FileNameFinder() static Test suite() { String basedir = System.getProperty(SYSPROP_SRC_DIR, "./src/") return suite(basedir) } static Test suite(String basedir) { String includePattern = System.getProperty(SYSPROP_SRC_PATTERN, "**/*.java,**/*.groovy") return suite(basedir, includePattern) } static Test suite(String basedir, String includePattern) { String excludePattern = System.getProperty(SYSPROP_SRC_EXCLUDES_PATTERN, "") return suite(basedir, includePattern, excludePattern) } static Test suite(String basedir, String includePattern, String excludePattern) { assert new File(basedir).exists() TestSuite suite = new JavadocAssertionTestSuite() Collection filenames = finder.getFileNames([dir:basedir, includes:includePattern, excludes:excludePattern]) filenames.each { filename -> String code = new File(filename).text Class test = testBuilder.buildTest(filename, code) if (test != null) { suite.addTestSuite(test) } } return suite } static void main(String[] args) { switch(args.length) { case 3: TestRunner.run(suite(args[0], args[1], args[2])) break case 2: TestRunner.run(suite(args[0], args[1])) break case 1: TestRunner.run(suite(args[0])) break default: TestRunner.run(suite()) } } } groovy-1.8.6/src/main/groovy/util/ScriptException.java0000644001501200150120000000223311627206700022375 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; /** * @author sam */ public class ScriptException extends Exception { /** * */ public ScriptException() { super(); } /** * @param message */ public ScriptException(String message) { super(message); } /** * @param message * @param cause */ public ScriptException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public ScriptException(Throwable cause) { super(cause); } } groovy-1.8.6/src/main/groovy/util/BuilderSupport.java0000644001501200150120000001714511627206700022245 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingMethodException; import org.codehaus.groovy.runtime.InvokerHelper; import java.util.List; import java.util.Map; /** * An abstract base class for creating arbitrary nested trees of objects * or events * * @author James Strachan * @version $Revision$ */ public abstract class BuilderSupport extends GroovyObjectSupport { private Object current; private Closure nameMappingClosure; private final BuilderSupport proxyBuilder; public BuilderSupport() { this.proxyBuilder = this; } public BuilderSupport(BuilderSupport proxyBuilder) { this(null, proxyBuilder); } public BuilderSupport(Closure nameMappingClosure, BuilderSupport proxyBuilder) { this.nameMappingClosure = nameMappingClosure; this.proxyBuilder = proxyBuilder; } /** * Convenience method when no arguments are required * * @param methodName the name of the method to invoke * @return the result of the call */ public Object invokeMethod(String methodName) { return invokeMethod(methodName, null); } public Object invokeMethod(String methodName, Object args) { Object name = getName(methodName); return doInvokeMethod(methodName, name, args); } protected Object doInvokeMethod(String methodName, Object name, Object args) { Object node = null; Closure closure = null; List list = InvokerHelper.asList(args); //System.out.println("Called invokeMethod with name: " + name + " arguments: " + list); switch (list.size()) { case 0: node = proxyBuilder.createNode(name); break; case 1: { Object object = list.get(0); if (object instanceof Map) { node = proxyBuilder.createNode(name, (Map) object); } else if (object instanceof Closure) { closure = (Closure) object; node = proxyBuilder.createNode(name); } else { node = proxyBuilder.createNode(name, object); } } break; case 2: { Object object1 = list.get(0); Object object2 = list.get(1); if (object1 instanceof Map) { if (object2 instanceof Closure) { closure = (Closure) object2; node = proxyBuilder.createNode(name, (Map) object1); } else { node = proxyBuilder.createNode(name, (Map) object1, object2); } } else { if (object2 instanceof Closure) { closure = (Closure) object2; node = proxyBuilder.createNode(name, object1); } else if (object2 instanceof Map) { node = proxyBuilder.createNode(name, (Map) object2, object1); } else { throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false); } } } break; case 3: { Object arg0 = list.get(0); Object arg1 = list.get(1); Object arg2 = list.get(2); if (arg0 instanceof Map && arg2 instanceof Closure) { closure = (Closure) arg2; node = proxyBuilder.createNode(name, (Map) arg0, arg1); } else if (arg1 instanceof Map && arg2 instanceof Closure) { closure = (Closure) arg2; node = proxyBuilder.createNode(name, (Map) arg1, arg0); } else { throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false); } } break; default: { throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false); } } if (current != null) { proxyBuilder.setParent(current, node); } if (closure != null) { // push new node on stack Object oldCurrent = getCurrent(); setCurrent(node); // let's register the builder as the delegate setClosureDelegate(closure, node); closure.call(); setCurrent(oldCurrent); } proxyBuilder.nodeCompleted(current, node); return proxyBuilder.postNodeCompletion(current, node); } /** * A strategy method to allow derived builders to use * builder-trees and switch in different kinds of builders. * This method should call the setDelegate() method on the closure * which by default passes in this but if node is-a builder * we could pass that in instead (or do something wacky too) * * @param closure the closure on which to call setDelegate() * @param node the node value that we've just created, which could be * a builder */ protected void setClosureDelegate(Closure closure, Object node) { closure.setDelegate(this); } protected abstract void setParent(Object parent, Object child); protected abstract Object createNode(Object name); protected abstract Object createNode(Object name, Object value); protected abstract Object createNode(Object name, Map attributes); protected abstract Object createNode(Object name, Map attributes, Object value); /** * A hook to allow names to be converted into some other object * such as a QName in XML or ObjectName in JMX. * * @param methodName the name of the desired method * @return the object representing the name */ protected Object getName(String methodName) { if (nameMappingClosure != null) { return nameMappingClosure.call(methodName); } return methodName; } /** * A hook to allow nodes to be processed once they have had all of their * children applied. * * @param node the current node being processed * @param parent the parent of the node being processed */ protected void nodeCompleted(Object parent, Object node) { } /** * A hook to allow nodes to be processed once they have had all of their * children applied and allows the actual node object that represents * the Markup element to be changed * * @param node the current node being processed * @param parent the parent of the node being processed * @return the node, possibly new, that represents the markup element */ protected Object postNodeCompletion(Object parent, Object node) { return node; } protected Object getCurrent() { return current; } protected void setCurrent(Object current) { this.current = current; } } groovy-1.8.6/src/main/groovy/util/CliBuilder.groovy0000644001501200150120000003173511645141222021702 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util import org.apache.commons.cli.* import org.codehaus.groovy.runtime.InvokerHelper /** * Provides a builder to assist the processing of command line arguments. *

    * Typical usage (emulate partial arg processing of unix command: ls -alt *.groovy): *

     * def cli = new CliBuilder(usage:'ls')
     * cli.a('display all files')
     * cli.l('use a long listing format')
     * cli.t('sort by modification time')
     * def options = cli.parse(args)
     * assert options // would be null (false) on failure
     * assert options.arguments() == ['*.groovy']
     * assert options.a && options.l && options.t
     * 
    * The usage message for this example (obtained using cli.usage()) is shown below: *
     * usage: ls
     *  -a   display all files
     *  -l   use a long listing format
     *  -t   sort by modification time
     * 
    * An underlying parser that supports what is called argument 'bursting' is used * by default. Bursting would convert '-alt' into '-a -l -t' provided no long * option exists with value 'alt' and provided that none of 'a', 'l' or 't' * takes an argument (in fact the last one is allowed to take an argument). * The bursting behavior can be turned off by using an * alternate underlying parser. The simplest way to achieve this is by setting * the posix property on the CliBuilder to false, i.e. include * posix: false in the constructor call. *

    * Another example (partial emulation of arg processing for 'ant' command line): *

     * def cli = new CliBuilder(usage:'ant [options] [targets]',
     *                          header:'Options:')
     * cli.help('print this message')
     * cli.logfile(args:1, argName:'file', 'use given file for log')
     * cli.D(args:2, valueSeparator:'=', argName:'property=value',
     *       'use value for given property')
     * def options = cli.parse(args)
     * ...
     * 
    * Usage message would be: *
     * usage: ant [options] [targets]
     * Options:
     *  -D <property=value>   use value for given property
     *  -help                 print this message
     *  -logfile <file>       use given file for log
     * 
    * And if called with the following arguments '-logfile foo -Dbar=baz target' * then the following assertions would be true: *
     * assert options // would be null (false) on failure
     * assert options.arguments() == ['target']
     * assert options.Ds == ['bar', 'baz']
     * assert options.logfile == 'foo'
     * 
    * Note the use of some special notation. By adding 's' onto an option * that may appear multiple times and has an argument or as in this case * uses a valueSeparator to separate multiple argument values * causes the list of associated argument values to be returned. *

    * Another example showing long options (partial emulation of arg processing for 'curl' command line): *

     * def cli = new CliBuilder(usage:'curl [options] <url>')
     * cli._(longOpt:'basic', 'Use HTTP Basic Authentication')
     * cli.d(longOpt:'data', args:1, argName:'data', 'HTTP POST data')
     * cli.G(longOpt:'get', 'Send the -d data with a HTTP GET')
     * cli.q('If used as the first parameter disables .curlrc')
     * cli._(longOpt:'url', args:1, argName:'URL', 'Set URL to work with')
     * 
    * Which has the following usage message: *
     * usage: curl [options] <url>
     *     --basic         Use HTTP Basic Authentication
     *  -d,--data <data>   HTTP POST data
     *  -G,--get           Send the -d data with a HTTP GET
     *  -q                 If used as the first parameter disables .curlrc
     *     --url <URL>     Set URL to work with
     * 
    * This example shows a common convention. When mixing short and long names, the * short names are often one character in size. One character options with * arguments don't require a space between the option and the argument, e.g. * -Ddebug=true. The example also shows * the use of '_' when no short option is applicable. *

    * Also note that '_' was used multiple times. This is supported but if * any other shortOpt or any longOpt is repeated, then the behavior is undefined. *

    * Short option names may not contain a hyphen. If a long option name contains a hyphen, e.g. '--max-wait' then you can either * use the long hand method call options.hasOption('max-wait') or surround * the option name in quotes, e.g. options.'max-wait'. *

    * Although CliBuilder on the whole hides away the underlying library used * for processing the arguments, it does provide some hooks which let you * make use of the underlying library directly should the need arise. For * example, the last two lines of the 'curl' example above could be replaced * with the following: *

     * import org.apache.commons.cli.*
     * ... as before ...
     * cli << new Option('q', false, 'If used as the first parameter disables .curlrc')
     * cli << OptionBuilder.withLongOpt('url').hasArg().withArgName('URL').
     *                      withDescription('Set URL to work with').create()
     * ...
     * 
    * * CliBuilder also supports Argument File processing. If an argument starts with * an '@' character followed by a filename, then the contents of the file with name * filename are placed into the command line. The feature can be turned off by * setting expandArgumentFiles to false. If turned on, you can still pass a real * parameter with an initial '@' character by escaping it with an additional '@' * symbol, e.g. '@@foo' will become '@foo' and not be subject to expansion. As an * example, if the file temp.args contains the content: *
     * -arg1
     * paramA
     * paramB paramC
     * 
    * Then calling the command line with: *
     * someCommand @temp.args -arg2 paramD
     * 
    * Is the same as calling this: *
     * someCommand -arg1 paramA paramB paramC -arg2 paramD
     * 
    * This feature is particularly useful on operating systems which place limitations * on the size of the command line (e.g. Windows). The feature is similar to * the 'Command Line Argument File' processing supported by javadoc and javac. * Consult the corresponding documentation for those tools if you wish to see further examples. *

    * Supported Option Properties: *

     *   argName:        String
     *   longOpt:        String
     *   args:           int
     *   optionalArg:    boolean
     *   required:       boolean
     *   type:           Object (not currently used)
     *   valueSeparator: char
     * 
    * See {@link org.apache.commons.cli.Option} for the meaning of these properties * and {@link CliBuilderTest} for further examples. *

    * * @author Dierk Koenig * @author Paul King */ class CliBuilder { /** * Usage summary displayed as the first line when cli.usage() is called. */ String usage = 'groovy' /** * Normally set internally but allows you full customisation of the underlying processing engine. */ CommandLineParser parser = null /** * To change from the default PosixParser to the GnuParser, set this to false. Ignored if the parser is explicitly set. */ boolean posix = true /** * Whether arguments of the form '{@code @}filename' will be expanded into the arguments contained within the file named filename (default true). */ boolean expandArgumentFiles = true /** * Normally set internally but can be overridden if you want to customise how the usage message is displayed. */ HelpFormatter formatter = new HelpFormatter() /** * Defaults to stdout but you can provide your own PrintWriter if desired. */ PrintWriter writer = new PrintWriter(System.out) /** * Optional additional message for usage; displayed after the usage summary but before the options are displayed. */ String header = '' /** * Optional additional message for usage; displayed after the options are displayed. */ String footer = '' /** * Indicates that option processing should continue for all arguments even * if arguments not recognized as options are encountered (default true). */ boolean stopAtNonOption = true /** * Allows customisation of the usage message width. */ int width = formatter.defaultWidth /** * Not normally accessed directly but full access to underlying options if needed. */ Options options = new Options() /** * Internal method: Detect option specification method calls. */ def invokeMethod(String name, Object args) { if (args instanceof Object[]) { if (args.size() == 1 && (args[0] instanceof String || args[0] instanceof GString)) { options.addOption(option(name, [:], args[0])) return null } if (args.size() == 1 && args[0] instanceof Option && name == 'leftShift') { options.addOption(args[0]) return null } if (args.size() == 2 && args[0] instanceof Map) { options.addOption(option(name, args[0], args[1])) return null } } return InvokerHelper.getMetaClass(this).invokeMethod(this, name, args) } /** * Make options accessible from command line args with parser (default: Posix). * Returns null on bad command lines after displaying usage message. */ OptionAccessor parse(args) { if (expandArgumentFiles) args = expandArgumentFiles(args) if (!parser) { parser = posix ? new PosixParser() : new GnuParser() } try { return new OptionAccessor(parser.parse(options, args as String[], stopAtNonOption)) } catch (ParseException pe) { writer.println("error: " + pe.message) usage() return null } } /** * Print the usage message with writer (default: System.out) and formatter (default: HelpFormatter) */ void usage() { formatter.printHelp(writer, width, usage, header, options, formatter.defaultLeftPad, formatter.defaultDescPad, footer) writer.flush() } // implementation details ------------------------------------- /** * Internal method: How to create an option from the specification. */ Option option(shortname, Map details, info) { Option option if (shortname == '_') { option = OptionBuilder.withDescription(info).withLongOpt(details.longOpt).create() details.remove('longOpt') } else { option = new Option(shortname, info) } details.each { key, value -> option[key] = value } return option } static expandArgumentFiles(args) throws IOException { def result = [] for (arg in args) { if (arg && arg != '@' && arg[0] == '@') { arg = arg.substring(1) if (arg[0] != '@') { expandArgumentFile(arg, result) continue } } result << arg } return result } private static expandArgumentFile(name, args) throws IOException { def charAsInt = { String s -> s.toCharacter() as int } new File(name).withReader { r -> new StreamTokenizer(r).with { resetSyntax() wordChars(charAsInt(' '), 255) whitespaceChars(0, charAsInt(' ')) commentChar(charAsInt('#')) quoteChar(charAsInt('"')) quoteChar(charAsInt('\'')) while (nextToken() != StreamTokenizer.TT_EOF) { args << sval } } } } } class OptionAccessor { CommandLine inner OptionAccessor(CommandLine inner) { this.inner = inner } def invokeMethod(String name, Object args) { return InvokerHelper.getMetaClass(inner).invokeMethod(inner, name, args) } def getProperty(String name) { def methodname = 'getOptionValue' if (name.size() > 1 && name.endsWith('s')) { def singularName = name[0..-2] if (hasOption(singularName)) { name = singularName methodname += 's' } } if (name.size() == 1) name = name as char def result = InvokerHelper.getMetaClass(inner).invokeMethod(inner, methodname, name) if (null == result) result = inner.hasOption(name) if (result instanceof String[]) result = result.toList() return result } List arguments() { inner.args.toList() } } groovy-1.8.6/src/main/groovy/util/ObjectGraphBuilder.java0000644001501200150120000010345611627206700022762 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.GString; import groovy.lang.MetaProperty; import groovy.lang.MissingPropertyException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.regex.Pattern; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import org.codehaus.groovy.runtime.InvokerHelper; /** * A builder for creating object graphs.
    * Each node defines the class to be created and the property on its parent (if * any) at the same time. * * @author Scott Vlaminck (http://refactr.com) * @author Andres Almiray */ public class ObjectGraphBuilder extends FactoryBuilderSupport { public static final String NODE_CLASS = "_NODE_CLASS_"; public static final String NODE_NAME = "_NODE_NAME_"; public static final String OBJECT_ID = "_OBJECT_ID_"; public static final String LAZY_REF = "_LAZY_REF_"; public static final String CLASSNAME_RESOLVER_KEY = "name"; public static final String CLASSNAME_RESOLVER_REFLECTION = "reflection"; public static final String CLASSNAME_RESOLVER_REFLECTION_ROOT = "root"; // Regular expression pattern used to identify words ending in 'y' preceded by a consonant private static final Pattern PLURAL_IES_PATTERN = Pattern.compile(".*[^aeiouy]y", Pattern.CASE_INSENSITIVE); private ChildPropertySetter childPropertySetter; private ClassNameResolver classNameResolver; private IdentifierResolver identifierResolver; private NewInstanceResolver newInstanceResolver; private ObjectFactory objectFactory = new ObjectFactory(); private ObjectBeanFactory objectBeanFactory = new ObjectBeanFactory(); private ObjectRefFactory objectRefFactory = new ObjectRefFactory(); private ReferenceResolver referenceResolver; private RelationNameResolver relationNameResolver; private Map resolvedClasses = new HashMap(); private ClassLoader classLoader; private boolean lazyReferencesAllowed = true; private List lazyReferences = new ArrayList(); private String beanFactoryName = "bean"; public ObjectGraphBuilder() { classNameResolver = new DefaultClassNameResolver(); newInstanceResolver = new DefaultNewInstanceResolver(); relationNameResolver = new DefaultRelationNameResolver(); childPropertySetter = new DefaultChildPropertySetter(); identifierResolver = new DefaultIdentifierResolver(); referenceResolver = new DefaultReferenceResolver(); addPostNodeCompletionDelegate(new Closure(this, this) { public void doCall(ObjectGraphBuilder builder, Object parent, Object node) { if (parent == null) { builder.resolveLazyReferences(); builder.dispose(); } } }); } /** * Returns the current name of the 'bean' node. */ public String getBeanFactoryName() { return beanFactoryName; } /** * Returns the current ChildPropertySetter. */ public ChildPropertySetter getChildPropertySetter() { return childPropertySetter; } /** * Returns the classLoader used to load a node's class. */ public ClassLoader getClassLoader() { return classLoader; } /** * Returns the current ClassNameResolver. */ public ClassNameResolver getClassNameResolver() { return classNameResolver; } /** * Returns the current NewInstanceResolver. */ public NewInstanceResolver getNewInstanceResolver() { return newInstanceResolver; } /** * Returns the current RelationNameResolver. */ public RelationNameResolver getRelationNameResolver() { return relationNameResolver; } /** * Returns true if references can be resolved lazily */ public boolean isLazyReferencesAllowed() { return lazyReferencesAllowed; } /** * Sets the name for the 'bean' node. */ public void setBeanFactoryName(String beanFactoryName) { this.beanFactoryName = beanFactoryName; } /** * Sets the current ChildPropertySetter.
    * It will assign DefaultChildPropertySetter if null.
    * It accepts a ChildPropertySetter instance or a Closure. */ public void setChildPropertySetter(final Object childPropertySetter) { if (childPropertySetter instanceof ChildPropertySetter) { this.childPropertySetter = (ChildPropertySetter) childPropertySetter; } else if (childPropertySetter instanceof Closure) { final ObjectGraphBuilder self = this; this.childPropertySetter = new ChildPropertySetter() { public void setChild(Object parent, Object child, String parentName, String propertyName) { Closure cls = (Closure) childPropertySetter; cls.setDelegate(self); cls.call(new Object[]{parent, child, parentName, propertyName}); } }; } else { this.childPropertySetter = new DefaultChildPropertySetter(); } } /** * Sets the classLoader used to load a node's class. */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Sets the current ClassNameResolver.
    * It will assign DefaultClassNameResolver if null.
    * It accepts a ClassNameResolver instance, a String, a Closure or a Map. */ public void setClassNameResolver(final Object classNameResolver) { if (classNameResolver instanceof ClassNameResolver) { this.classNameResolver = (ClassNameResolver) classNameResolver; } else if (classNameResolver instanceof String) { this.classNameResolver = new ClassNameResolver() { public String resolveClassname(String classname) { return makeClassName((String) classNameResolver, classname); } }; } else if (classNameResolver instanceof Closure) { final ObjectGraphBuilder self = this; this.classNameResolver = new ClassNameResolver() { public String resolveClassname(String classname) { Closure cls = (Closure) classNameResolver; cls.setDelegate(self); return (String) cls.call(new Object[]{classname}); } }; } else if (classNameResolver instanceof Map) { Map classNameResolverOptions = (Map) classNameResolver; String resolverName = (String) classNameResolverOptions.get(CLASSNAME_RESOLVER_KEY); if (resolverName == null) { throw new RuntimeException("key '" + CLASSNAME_RESOLVER_KEY + "' not defined"); } if (CLASSNAME_RESOLVER_REFLECTION.equals(resolverName)) { String root = (String) classNameResolverOptions.get(CLASSNAME_RESOLVER_REFLECTION_ROOT); if (root == null) { throw new RuntimeException("key '" + CLASSNAME_RESOLVER_REFLECTION_ROOT + "' not defined"); } this.classNameResolver = new ReflectionClassNameResolver(root); } else { throw new RuntimeException("unknown class name resolver " + resolverName); } } else { this.classNameResolver = new DefaultClassNameResolver(); } } /** * Sets the current IdentifierResolver.
    * It will assign DefaultIdentifierResolver if null.
    * It accepts a IdentifierResolver instance, a String or a Closure. */ public void setIdentifierResolver(final Object identifierResolver) { if (identifierResolver instanceof IdentifierResolver) { this.identifierResolver = (IdentifierResolver) identifierResolver; } else if (identifierResolver instanceof String) { this.identifierResolver = new IdentifierResolver() { public String getIdentifierFor(String nodeName) { return (String) identifierResolver; } }; } else if (identifierResolver instanceof Closure) { final ObjectGraphBuilder self = this; this.identifierResolver = new IdentifierResolver() { public String getIdentifierFor(String nodeName) { Closure cls = (Closure) identifierResolver; cls.setDelegate(self); return (String) cls.call(new Object[]{nodeName}); } }; } else { this.identifierResolver = new DefaultIdentifierResolver(); } } /** * Sets whether references can be resolved lazily or not. */ public void setLazyReferencesAllowed(boolean lazyReferencesAllowed) { this.lazyReferencesAllowed = lazyReferencesAllowed; } /** * Sets the current NewInstanceResolver.
    * It will assign DefaultNewInstanceResolver if null.
    * It accepts a NewInstanceResolver instance or a Closure. */ public void setNewInstanceResolver(final Object newInstanceResolver) { if (newInstanceResolver instanceof NewInstanceResolver) { this.newInstanceResolver = (NewInstanceResolver) newInstanceResolver; } else if (newInstanceResolver instanceof Closure) { final ObjectGraphBuilder self = this; this.newInstanceResolver = new NewInstanceResolver() { public Object newInstance(Class klass, Map attributes) throws InstantiationException, IllegalAccessException { Closure cls = (Closure) newInstanceResolver; cls.setDelegate(self); return cls.call(new Object[]{klass, attributes}); } }; } else { this.newInstanceResolver = new DefaultNewInstanceResolver(); } } /** * Sets the current ReferenceResolver.
    * It will assign DefaultReferenceResolver if null.
    * It accepts a ReferenceResolver instance, a String or a Closure. */ public void setReferenceResolver(final Object referenceResolver) { if (referenceResolver instanceof ReferenceResolver) { this.referenceResolver = (ReferenceResolver) referenceResolver; } else if (referenceResolver instanceof String) { this.referenceResolver = new ReferenceResolver() { public String getReferenceFor(String nodeName) { return (String) referenceResolver; } }; } else if (referenceResolver instanceof Closure) { final ObjectGraphBuilder self = this; this.referenceResolver = new ReferenceResolver() { public String getReferenceFor(String nodeName) { Closure cls = (Closure) referenceResolver; cls.setDelegate(self); return (String) cls.call(new Object[]{nodeName}); } }; } else { this.referenceResolver = new DefaultReferenceResolver(); } } /** * Sets the current RelationNameResolver.
    * It will assign DefaultRelationNameResolver if null. */ public void setRelationNameResolver(RelationNameResolver relationNameResolver) { this.relationNameResolver = relationNameResolver != null ? relationNameResolver : new DefaultRelationNameResolver(); } protected void postInstantiate(Object name, Map attributes, Object node) { super.postInstantiate(name, attributes, node); Map context = getContext(); String objectId = (String) context.get(OBJECT_ID); if (objectId != null && node != null) { setVariable(objectId, node); } } protected void preInstantiate(Object name, Map attributes, Object value) { super.preInstantiate(name, attributes, value); Map context = getContext(); context.put(OBJECT_ID, attributes.remove(identifierResolver.getIdentifierFor((String) name))); } protected Factory resolveFactory(Object name, Map attributes, Object value) { // let custom factories be resolved first Factory factory = super.resolveFactory(name, attributes, value); if (factory != null) { return factory; } if (attributes.get(referenceResolver.getReferenceFor((String) name)) != null) { return objectRefFactory; } if (beanFactoryName != null && beanFactoryName.equals((String) name)) { return objectBeanFactory; } return objectFactory; } /** * Strategy for setting a child node on its parent.
    * Useful for handling Lists/Arrays vs normal properties. */ public interface ChildPropertySetter { /** * @param parent the parent's node value * @param child the child's node value * @param parentName the name of the parent node * @param propertyName the resolved relation name of the child */ void setChild(Object parent, Object child, String parentName, String propertyName); } /** * Strategy for resolving a classname. */ public interface ClassNameResolver { /** * @param classname the node name as written on the building code */ String resolveClassname(String classname); } /** * Default impl that calls parent.propertyName = child
    * If parent.propertyName is a Collection it will try to add child to the * collection. */ public static class DefaultChildPropertySetter implements ChildPropertySetter { public void setChild(Object parent, Object child, String parentName, String propertyName) { try { Object property = InvokerHelper.getProperty(parent, propertyName); if (property != null && Collection.class.isAssignableFrom(property.getClass())) { ((Collection) property).add(child); } else { InvokerHelper.setProperty(parent, propertyName, child); } } catch (MissingPropertyException mpe) { // ignore } } } /** * Default impl that capitalizes the classname. */ public static class DefaultClassNameResolver implements ClassNameResolver { public String resolveClassname(String classname) { if (classname.length() == 1) { return classname.toUpperCase(); } return classname.substring(0, 1) .toUpperCase() + classname.substring(1); } } /** * Build objects using reflection to resolve class names. */ public class ReflectionClassNameResolver implements ClassNameResolver { private final String root; /** * @param root package where the graph root class is located */ public ReflectionClassNameResolver(String root) { this.root = root; } public String resolveClassname(String classname) { Object currentNode = getContext().get(CURRENT_NODE); if (currentNode == null) { return makeClassName(root, classname); } else { try { Class klass = currentNode.getClass().getDeclaredField(classname).getType(); if (Collection.class.isAssignableFrom(klass)) { Type type = currentNode.getClass().getDeclaredField(classname).getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type[] actualTypeArguments = ptype.getActualTypeArguments(); if (actualTypeArguments.length != 1) { throw new RuntimeException("can't determine class name for collection field " + classname + " with multiple generics"); } Type typeArgument = actualTypeArguments[0]; if (typeArgument instanceof Class) { klass = (Class) actualTypeArguments[0]; } else { throw new RuntimeException("can't instantiate collection field " + classname + " elements as they aren't a class"); } } else { throw new RuntimeException("collection field " + classname + " must be genericised"); } } return klass.getName(); } catch (NoSuchFieldException e) { throw new RuntimeException("can't find field " + classname + " for node class " + currentNode.getClass().getName(), e); } } } } /** * Default impl, always returns 'id' */ public static class DefaultIdentifierResolver implements IdentifierResolver { public String getIdentifierFor(String nodeName) { return "id"; } } /** * Default impl that calls Class.newInstance() */ public static class DefaultNewInstanceResolver implements NewInstanceResolver { public Object newInstance(Class klass, Map attributes) throws InstantiationException, IllegalAccessException { return klass.newInstance(); } } /** * Default impl, always returns 'refId' */ public static class DefaultReferenceResolver implements ReferenceResolver { public String getReferenceFor(String nodeName) { return "refId"; } } /** * Default impl that returns parentName & childName accordingly. */ public static class DefaultRelationNameResolver implements RelationNameResolver { /** * Handles the common English regular plurals with the following rules.
    *

      *
    • If childName ends in {consonant}y, replace 'y' with "ies". For example, allergy to allergies.
    • *
    • Otherwise, append 's'. For example, monkey to monkeys; employee to employees.
    • *
    * If the property does not exist then it will return childName unchanged. * * @see English_plural */ public String resolveChildRelationName(String parentName, Object parent, String childName, Object child) { boolean matchesIESRule = PLURAL_IES_PATTERN.matcher(childName).matches(); String childNamePlural = matchesIESRule ? childName.substring(0, childName.length() - 1) + "ies" : childName + "s"; MetaProperty metaProperty = InvokerHelper.getMetaClass(parent) .hasProperty(parent, childNamePlural); return metaProperty != null ? childNamePlural : childName; } /** * Follow the most conventional pattern, returns the parentName * unchanged. */ public String resolveParentRelationName(String parentName, Object parent, String childName, Object child) { return parentName; } } /** * Strategy for picking the correct synthetic identifier. */ public interface IdentifierResolver { /** * Returns the name of the property that will identify the node.
    * * @param nodeName the name of the node */ String getIdentifierFor(String nodeName); } /** * Strategy for creating new instances of a class.
    * Useful for plug-in calls to non-default constructors. */ public interface NewInstanceResolver { /** * Create a new instance of Class klass. * * @param klass the resolved class name * @param attributes the attribute Map available for the node */ Object newInstance(Class klass, Map attributes) throws InstantiationException, IllegalAccessException; } /** * Strategy for picking the correct synthetic reference identifier. */ public interface ReferenceResolver { /** * Returns the name of the property that references another node.
    * * @param nodeName the name of the node */ String getReferenceFor(String nodeName); } /** * Strategy for resolving a relationship property name. */ public interface RelationNameResolver { /** * Returns the mapping name of child -> parent * * @param parentName the name of the parent node * @param parent the parent node * @param childName the name of the child node * @param child the child node */ String resolveChildRelationName(String parentName, Object parent, String childName, Object child); /** * Returns the mapping name of parent -> child * * @param parentName the name of the parent node * @param parent the parent node * @param childName the name of the child node * @param child the child node */ String resolveParentRelationName(String parentName, Object parent, String childName, Object child); } private void resolveLazyReferences() { if (!lazyReferencesAllowed) return; for (NodeReference ref : lazyReferences) { if (ref.parent == null) continue; Object child = null; try { child = getProperty(ref.refId); } catch (MissingPropertyException mpe) { // ignore } if (child == null) { throw new IllegalArgumentException("There is no valid node for reference " + ref.parentName + "." + ref.childName + "=" + ref.refId); } // set child first childPropertySetter.setChild(ref.parent, child, ref.parentName, relationNameResolver.resolveChildRelationName(ref.parentName, ref.parent, ref.childName, child)); // set parent afterwards String propertyName = relationNameResolver.resolveParentRelationName(ref.parentName, ref.parent, ref.childName, child); MetaProperty metaProperty = InvokerHelper.getMetaClass(child) .hasProperty(child, propertyName); if (metaProperty != null) { metaProperty.setProperty(child, ref.parent); } } } private static String makeClassName(String root, String name) { return root + "." + name.substring(0, 1).toUpperCase() + name.substring(1); } private static class ObjectFactory extends AbstractFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; String classname = ogbuilder.classNameResolver.resolveClassname((String) name); Class klass = resolveClass(builder, classname, name, value, properties); Map context = builder.getContext(); context.put(ObjectGraphBuilder.NODE_NAME, name); context.put(ObjectGraphBuilder.NODE_CLASS, klass); return resolveInstance(builder, name, value, klass, properties); } protected Class resolveClass(FactoryBuilderSupport builder, String classname, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; Class klass = ogbuilder.resolvedClasses.get(classname); if (klass == null) { klass = loadClass(ogbuilder.classLoader, classname); if (klass == null) { klass = loadClass(ogbuilder.getClass().getClassLoader(), classname); } if (klass == null) { try { klass = Class.forName(classname); } catch (ClassNotFoundException e) { // ignore } } if (klass == null) { klass = loadClass(Thread.currentThread().getContextClassLoader(), classname); } if (klass == null) { throw new RuntimeException(new ClassNotFoundException(classname)); } ogbuilder.resolvedClasses.put(classname, klass); } return klass; } protected Object resolveInstance(FactoryBuilderSupport builder, Object name, Object value, Class klass, Map properties) throws InstantiationException, IllegalAccessException { ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; if (value != null && klass.isAssignableFrom(value.getClass())) { return value; } return ogbuilder.newInstanceResolver.newInstance(klass, properties); } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (child == null) return; ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; if (parent != null) { Map context = ogbuilder.getContext(); Map parentContext = ogbuilder.getParentContext(); String parentName = null; String childName = (String) context.get(NODE_NAME); if (parentContext != null) { parentName = (String) parentContext.get(NODE_NAME); } String propertyName = ogbuilder.relationNameResolver.resolveParentRelationName( parentName, parent, childName, child); MetaProperty metaProperty = InvokerHelper.getMetaClass(child) .hasProperty(child, propertyName); if (metaProperty != null) { metaProperty.setProperty(child, parent); } } } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (child == null) return; ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; if (parent != null) { Map context = ogbuilder.getContext(); Map parentContext = ogbuilder.getParentContext(); String parentName = null; String childName = (String) context.get(NODE_NAME); if (parentContext != null) { parentName = (String) parentContext.get(NODE_NAME); } ogbuilder.childPropertySetter.setChild(parent, child, parentName, ogbuilder.relationNameResolver.resolveChildRelationName(parentName, parent, childName, child)); } } protected Class loadClass(ClassLoader classLoader, String classname) { if (classLoader == null || classname == null) { return null; } try { return classLoader.loadClass(classname); } catch (ClassNotFoundException e) { return null; } } } private static class ObjectBeanFactory extends ObjectFactory { public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { if(value == null) return super.newInstance(builder, name, value, properties); Object bean = null; Class klass = null; Map context = builder.getContext(); if(value instanceof String || value instanceof GString) { /* String classname = value.toString(); klass = resolveClass(builder, classname, name, value, properties); bean = resolveInstance(builder, name, value, klass, properties); */ throw new IllegalArgumentException("ObjectGraphBuilder."+((ObjectGraphBuilder)builder).getBeanFactoryName()+"() does not accept String nor GString as value."); } else if(value instanceof Class) { klass = (Class) value; bean = resolveInstance(builder, name, value, klass, properties); } else { klass = value.getClass(); bean = value; } String nodename = klass.getSimpleName(); if(nodename.length() > 1) { nodename = nodename.substring(0, 1).toLowerCase() + nodename.substring(1); } else { nodename = nodename.toLowerCase(); } context.put(ObjectGraphBuilder.NODE_NAME, nodename); context.put(ObjectGraphBuilder.NODE_CLASS, klass); return bean; } } private static class ObjectRefFactory extends ObjectFactory { public boolean isLeaf() { return true; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; String refProperty = ogbuilder.referenceResolver.getReferenceFor((String) name); Object refId = properties.remove(refProperty); Object object = null; Boolean lazy = Boolean.FALSE; if (refId instanceof String) { try { object = ogbuilder.getProperty((String) refId); } catch (MissingPropertyException mpe) { // ignore, will try lazy reference } if (object == null) { if (ogbuilder.isLazyReferencesAllowed()) { lazy = Boolean.TRUE; } else { throw new IllegalArgumentException("There is no previous node with " + ogbuilder.identifierResolver.getIdentifierFor((String) name) + "=" + refId); } } } else { // assume we got a true reference to the object object = refId; } if (!properties.isEmpty()) { throw new IllegalArgumentException( "You can not modify the properties of a referenced object."); } Map context = ogbuilder.getContext(); context.put(ObjectGraphBuilder.NODE_NAME, name); context.put(ObjectGraphBuilder.LAZY_REF, lazy); if (lazy.booleanValue()) { Map parentContext = ogbuilder.getParentContext(); Object parent = null; String parentName = null; String childName = (String) name; if (parentContext != null) { parent = context.get(CURRENT_NODE); parentName = (String) parentContext.get(NODE_NAME); } ogbuilder.lazyReferences.add(new NodeReference(parent, parentName, childName, (String) refId)); } else { context.put(ObjectGraphBuilder.NODE_CLASS, object.getClass()); } return object; } public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { Boolean lazy = (Boolean) builder.getContext().get(ObjectGraphBuilder.LAZY_REF); if (!lazy.booleanValue()) super.setChild(builder, parent, child); } public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { Boolean lazy = (Boolean) builder.getContext().get(ObjectGraphBuilder.LAZY_REF); if (!lazy.booleanValue()) super.setParent(builder, parent, child); } } private static class NodeReference { private final Object parent; private final String parentName; private final String childName; private final String refId; private NodeReference(Object parent, String parentName, String childName, String refId) { this.parent = parent; this.parentName = parentName; this.childName = childName; this.refId = refId; } public String toString() { return new StringBuilder().append("[parentName=").append(parentName) .append(", childName=").append(childName) .append(", refId=").append(refId) .append("]").toString(); } } } groovy-1.8.6/src/main/groovy/util/NodeList.java0000644001501200150120000001307511627206700021001 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import groovy.xml.QName; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * A List implementation which is returned by queries on a {@link Node} * which provides some XPath like helper methods for GPath. * * @author James Strachan * @author Paul King */ public class NodeList extends ArrayList { static { // wrap the standard MetaClass with the delegate setMetaClass(NodeList.class, GroovySystem.getMetaClassRegistry().getMetaClass(NodeList.class)); } public NodeList() { } public NodeList(Collection collection) { super(collection); } public NodeList(int size) { super(size); } protected static void setMetaClass(final Class nodelistClass, final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { @Override public Object getAttribute(final Object object, final String attribute) { NodeList nl = (NodeList) object; Iterator it = nl.iterator(); List result = new ArrayList(); while (it.hasNext()) { Node node = (Node) it.next(); result.add(node.attributes().get(attribute)); } return result; } @Override public void setAttribute(final Object object, final String attribute, final Object newValue) { for (Object o : (NodeList) object) { Node node = (Node) o; node.attributes().put(attribute, newValue); } } @Override public Object getProperty(Object object, String property) { if (object instanceof NodeList) { NodeList nl = (NodeList) object; return nl.getAt(property); } return super.getProperty(object, property); } }; GroovySystem.getMetaClassRegistry().setMetaClass(nodelistClass, newMetaClass); } /** * Provides lookup of elements by non-namespaced name. * * @param name the name or shortcut key for nodes of interest * @return the nodes of interest which match name */ public NodeList getAt(String name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; Object temp = childNode.get(name); if (temp instanceof Collection) { answer.addAll((Collection) temp); } else { answer.add(temp); } } } return answer; } /** * Provides lookup of elements by QName. * * @param name the name or shortcut key for nodes of interest * @return the nodes of interest which match name */ public NodeList getAt(QName name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; NodeList temp = childNode.getAt(name); answer.addAll(temp); } } return answer; } /** * Returns the text value of all of the elements in the collection. * * @return the text value of all the elements in the collection or null */ public String text() { String previousText = null; StringBuffer buffer = null; for (Object child : this) { String text = null; if (child instanceof String) { text = (String) child; } else if (child instanceof Node) { text = ((Node) child).text(); } if (text != null) { if (previousText == null) { previousText = text; } else { if (buffer == null) { buffer = new StringBuffer(); buffer.append(previousText); } buffer.append(text); } } } if (buffer != null) { return buffer.toString(); } if (previousText != null) { return previousText; } return ""; } public Node replaceNode(Closure c) { if (size() <= 0 || size() > 1) { throw new GroovyRuntimeException("replaceNode() can only be used to replace a single node."); } return ((Node)get(0)).replaceNode(c); } public void plus(Closure c) { for (Object o : this) { ((Node) o).plus(c); } } } groovy-1.8.6/src/main/groovy/util/Eval.java0000644001501200150120000001134111627206700020141 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import org.codehaus.groovy.control.CompilationFailedException; import groovy.lang.Binding; import groovy.lang.GroovyShell; /** * Allow easy integration from Groovy into Java through convenience methods.

    * * This class is a simple helper on top of GroovyShell. You can use it to evaluate small * Groovy scripts that don't need large Binding objects. For example, this script * executes with no errors: *
     * assert 10 == Eval.me(' 2 * 4 + 2')
     * assert 10 == Eval.x(2, ' x * 4 + 2')
     * 
    * * @see GroovyShell * * @author Dierk Koenig */ public class Eval { /** * Evaluates the specified String expression and returns the result. For example: *
         * assert 10 == Eval.me(' 2 * 4 + 2')
         * 
    * @param expression the Groovy expression to evaluate * @return the result of the expression * @throws CompilationFailedException if expression is not valid Groovy */ public static Object me(final String expression) throws CompilationFailedException { return me(null, null, expression); } /** * Evaluates the specified String expression and makes the parameter available inside * the script, returning the result. For example, this code binds the 'x' variable: *
         * assert 10 == Eval.me('x', 2, ' x * 4 + 2')
         * 
    * @param expression the Groovy expression to evaluate * @return the result of the expression * @throws CompilationFailedException if expression is not valid Groovy */ public static Object me(final String symbol, final Object object, final String expression) throws CompilationFailedException { Binding b = new Binding(); b.setVariable(symbol, object); GroovyShell sh = new GroovyShell(b); return sh.evaluate(expression); } /** * Evaluates the specified String expression and makes the parameter available inside * the script bound to a variable named 'x', returning the result. For example, this * code executes without failure: *
         * assert 10 == Eval.x(2, ' x * 4 + 2')
         * 
    * @param expression the Groovy expression to evaluate * @return the result of the expression * @throws CompilationFailedException if expression is not valid Groovy */ public static Object x(final Object x, final String expression) throws CompilationFailedException { return me("x", x, expression); } /** * Evaluates the specified String expression and makes the first two parameters available inside * the script bound to variables named 'x' and 'y' respectively, returning the result. For example, * this code executes without failure: *
         * assert 10 == Eval.xy(2, 4, ' x * y + 2')
         * 
    * @param expression the Groovy expression to evaluate * @return the result of the expression * @throws CompilationFailedException if expression is not valid Groovy */ public static Object xy(final Object x, final Object y, final String expression) throws CompilationFailedException { Binding b = new Binding(); b.setVariable("x", x); b.setVariable("y", y); GroovyShell sh = new GroovyShell(b); return sh.evaluate(expression); } /** * Evaluates the specified String expression and makes the first three parameters available inside * the script bound to variables named 'x', 'y', and 'z' respectively, returning the result. For * example, this code executes without failure: *
         * assert 10 == Eval.xyz(2, 4, 2, ' x * y + z')
         * 
    * @param expression the Groovy expression to evaluate * @return the result of the expression * @throws CompilationFailedException if expression is not valid Groovy */ public static Object xyz(final Object x, final Object y, final Object z, final String expression) throws CompilationFailedException { Binding b = new Binding(); b.setVariable("x", x); b.setVariable("y", y); b.setVariable("z", z); GroovyShell sh = new GroovyShell(b); return sh.evaluate(expression); } } groovy-1.8.6/src/main/groovy/util/MapEntry.java0000644001501200150120000000402711627206700021014 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.util.Map; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * A Map.Entry implementation. * * @author James Strachan * @version $Revision$ */ public class MapEntry implements Map.Entry { private Object key; private Object value; public MapEntry(Object key, Object value) { this.key = key; this.value = value; } public boolean equals(Object that) { if (that instanceof MapEntry) { return equals((MapEntry) that); } return false; } public boolean equals(MapEntry that) { return DefaultTypeTransformation.compareEqual(this.key, that.key) && DefaultTypeTransformation.compareEqual(this.value, that.value); } public int hashCode() { return hash(key) ^ hash(value); } public String toString() { return "" + key + ":" + value; } public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public Object getValue() { return value; } public Object setValue(Object value) { this.value = value; return value; } /** * Helper method to handle object hashes for possibly null values */ protected int hash(Object object) { return (object == null) ? 0xbabe : object.hashCode(); } } groovy-1.8.6/src/main/groovy/util/ObservableList.java0000644001501200150120000004520611715031256022201 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * List decorator that will trigger PropertyChangeEvents when a value changes.
    * An optional Closure may be specified and will work as a filter, if it returns true the property * will trigger an event (if the value indeed changed), otherwise it won't. The Closure may receive * 1 or 2 parameters, the single one being the value, the other one both the key and value, for * example: *

    *

     * // skip all properties whose value is a closure
     * def map = new ObservableList( {!(it instanceof Closure)} )
     * <p/>
     * // skip all properties whose name matches a regex
     * def map = new ObservableList( { name, value -> !(name =˜ /[A-Z+]/) } )
     * 
    *

    *

    * The current implementation will trigger specialized events in the following scenarios, you need * not register a different listener as those events extend from PropertyChangeEvent *

      *
    • ObservableList.ElementAddedEvent - a new element is added to the list
    • *
    • ObservableList.ElementRemovedEvent - an element is removed from the list
    • *
    • ObservableList.ElementUpdatedEvent - an element changes value (same as regular * PropertyChangeEvent)
    • *
    • ObservableList.ElementClearedEvent - all elements have been removed from the list
    • *
    • ObservableList.MultiElementAddedEvent - triggered by calling list.addAll()
    • *
    • ObservableList.MultiElementRemovedEvent - triggered by calling * list.removeAll()/list.retainAll()
    • *
    *

    *

    *

    * Bound properties *

      *
    • content - read-only.
    • *
    • size - read-only.
    • *
    *

    * * @author Andres Almiray */ public class ObservableList implements List { private List delegate; private PropertyChangeSupport pcs; private Closure test; public static final String SIZE_PROPERTY = "size"; public static final String CONTENT_PROPERTY = "content"; public ObservableList() { this(new ArrayList(), null); } public ObservableList(List delegate) { this(delegate, null); } public ObservableList(Closure test) { this(new ArrayList(), test); } public ObservableList(List delegate, Closure test) { this.delegate = delegate; this.test = test; pcs = new PropertyChangeSupport(this); } public List getContent() { return Collections.unmodifiableList(delegate); } protected List getDelegateList() { return delegate; } protected Closure getTest() { return test; } protected void fireElementAddedEvent(int index, Object element) { fireElementEvent(new ElementAddedEvent(this, element, index)); } protected void fireMultiElementAddedEvent(int index, List values) { fireElementEvent(new MultiElementAddedEvent(this, index, values)); } protected void fireElementClearedEvent(List values) { fireElementEvent(new ElementClearedEvent(this, values)); } protected void fireElementRemovedEvent(int index, Object element) { fireElementEvent(new ElementRemovedEvent(this, element, index)); } protected void fireMultiElementRemovedEvent(List values) { fireElementEvent(new MultiElementRemovedEvent(this, values)); } protected void fireElementUpdatedEvent(int index, Object oldValue, Object newValue) { fireElementEvent(new ElementUpdatedEvent(this, oldValue, newValue, index)); } protected void fireElementEvent(ElementEvent event) { pcs.firePropertyChange(event); } protected void fireSizeChangedEvent(int oldValue, int newValue) { pcs.firePropertyChange(new PropertyChangeEvent(this, SIZE_PROPERTY, oldValue, newValue)); } public void add(int index, Object element) { int oldSize = size(); delegate.add(index, element); if (test != null) { Object result = test.call(element); if (result != null && result instanceof Boolean && (Boolean) result) { fireElementAddedEvent(index, element); fireSizeChangedEvent(oldSize, size()); } } else { fireElementAddedEvent(index, element); fireSizeChangedEvent(oldSize, size()); } } public boolean add(Object o) { int oldSize = size(); boolean success = delegate.add(o); if (success) { if (test != null) { Object result = test.call(o); if (result != null && result instanceof Boolean && (Boolean) result) { fireElementAddedEvent(size() - 1, o); fireSizeChangedEvent(oldSize, size()); } } else { fireElementAddedEvent(size() - 1, o); fireSizeChangedEvent(oldSize, size()); } } return success; } public boolean addAll(Collection c) { int oldSize = size(); int index = size() - 1; index = index < 0 ? 0 : index; boolean success = delegate.addAll(c); if (success && c != null) { List values = new ArrayList(); for (Object element : c) { if (test != null) { Object result = test.call(element); if (result != null && result instanceof Boolean && (Boolean) result) { values.add(element); } } else { values.add(element); } } if (values.size() > 0) { fireMultiElementAddedEvent(index, values); fireSizeChangedEvent(oldSize, size()); } } return success; } public boolean addAll(int index, Collection c) { int oldSize = size(); boolean success = delegate.addAll(index, c); if (success && c != null) { List values = new ArrayList(); for (Object element : c) { if (test != null) { Object result = test.call(element); if (result != null && result instanceof Boolean && (Boolean) result) { values.add(element); } } else { values.add(element); } } if (values.size() > 0) { fireMultiElementAddedEvent(index, values); fireSizeChangedEvent(oldSize, size()); } } return success; } public void clear() { int oldSize = size(); List values = new ArrayList(); values.addAll(delegate); delegate.clear(); if (!values.isEmpty()) { fireElementClearedEvent(values); } fireSizeChangedEvent(oldSize, size()); } public boolean contains(Object o) { return delegate.contains(o); } public boolean containsAll(Collection c) { return delegate.containsAll(c); } public boolean equals(Object o) { return delegate.equals(o); } public Object get(int index) { return delegate.get(index); } public int hashCode() { return delegate.hashCode(); } public int indexOf(Object o) { return delegate.indexOf(o); } public boolean isEmpty() { return delegate.isEmpty(); } public Iterator iterator() { return new ObservableIterator(delegate.iterator()); } public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } public ListIterator listIterator() { return new ObservableListIterator(delegate.listIterator(), 0); } public ListIterator listIterator(int index) { return new ObservableListIterator(delegate.listIterator(index), index); } public Object remove(int index) { int oldSize = size(); Object element = delegate.remove(index); fireElementRemovedEvent(index, element); fireSizeChangedEvent(oldSize, size()); return element; } public boolean remove(Object o) { int oldSize = size(); int index = delegate.indexOf(o); boolean success = delegate.remove(o); if (success) { fireElementRemovedEvent(index, o); fireSizeChangedEvent(oldSize, size()); } return success; } public boolean removeAll(Collection c) { if (c == null) { return false; } List values = new ArrayList(); if (c != null) { for (Object element : c) { if (delegate.contains(element)) { values.add(element); } } } int oldSize = size(); boolean success = delegate.removeAll(c); if (success && !values.isEmpty()) { fireMultiElementRemovedEvent(values); fireSizeChangedEvent(oldSize, size()); } return success; } public boolean retainAll(Collection c) { if (c == null) { return false; } List values = new ArrayList(); if (c != null) { for (Object element : delegate) { if (!c.contains(element)) { values.add(element); } } } int oldSize = size(); boolean success = delegate.retainAll(c); if (success && !values.isEmpty()) { fireMultiElementRemovedEvent(values); fireSizeChangedEvent(oldSize, size()); } return success; } public Object set(int index, Object element) { Object oldValue = delegate.set(index, element); if (test != null) { Object result = test.call(element); if (result != null && result instanceof Boolean && ((Boolean) result).booleanValue()) { fireElementUpdatedEvent(index, oldValue, element); } } else { fireElementUpdatedEvent(index, oldValue, element); } return oldValue; } public int size() { return delegate.size(); } public int getSize() { return size(); } public List subList(int fromIndex, int toIndex) { return delegate.subList(fromIndex, toIndex); } public Object[] toArray() { return delegate.toArray(); } public Object[] toArray(Object[] a) { return delegate.toArray(a); } protected class ObservableIterator implements Iterator { private Iterator iterDelegate; protected int cursor = -1 ; public ObservableIterator(Iterator iterDelegate) { this.iterDelegate = iterDelegate; } public Iterator getDelegate() { return iterDelegate; } public boolean hasNext() { return iterDelegate.hasNext(); } public Object next() { cursor++; return iterDelegate.next(); } public void remove() { int oldSize = ObservableList.this.size(); Object element = ObservableList.this.get(cursor); iterDelegate.remove(); fireElementRemovedEvent(cursor, element); fireSizeChangedEvent(oldSize, size()); cursor--; } } protected class ObservableListIterator extends ObservableIterator implements ListIterator { public ObservableListIterator(ListIterator iterDelegate, int index) { super(iterDelegate); cursor = index - 1; } public ListIterator getListIterator() { return (ListIterator) getDelegate(); } public void add(Object o) { ObservableList.this.add(o); cursor++; } public boolean hasPrevious() { return getListIterator().hasPrevious(); } public int nextIndex() { return getListIterator().nextIndex(); } public Object previous() { return getListIterator().previous(); } public int previousIndex() { return getListIterator().previousIndex(); } public void set(Object o) { ObservableList.this.set(cursor, o); } } // observable interface public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } public PropertyChangeListener[] getPropertyChangeListeners() { return pcs.getPropertyChangeListeners(); } public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { return pcs.getPropertyChangeListeners(propertyName); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.removePropertyChangeListener(propertyName, listener); } public boolean hasListeners(String propertyName) { return pcs.hasListeners(propertyName); } public enum ChangeType { ADDED, UPDATED, REMOVED, CLEARED, MULTI_ADD, MULTI_REMOVE, NONE; public static final Object oldValue = new Object(); public static final Object newValue = new Object(); public static ChangeType resolve(int ordinal) { switch (ordinal) { case 0: return ADDED; case 2: return REMOVED; case 3: return CLEARED; case 4: return MULTI_ADD; case 5: return MULTI_REMOVE; case 6: return NONE; case 1: default: return UPDATED; } } } public abstract static class ElementEvent extends PropertyChangeEvent { /** * deprecated */ public static final int ADDED = ChangeType.ADDED.ordinal(); /** * deprecated */ public static final int UPDATED = ChangeType.UPDATED.ordinal(); /** * deprecated */ public static final int REMOVED = ChangeType.REMOVED.ordinal(); /** * deprecated */ public static final int CLEARED = ChangeType.CLEARED.ordinal(); /** * deprecated */ public static final int MULTI_ADD = ChangeType.MULTI_ADD.ordinal(); /** * deprecated */ public static final int MULTI_REMOVE = ChangeType.MULTI_REMOVE.ordinal(); private final ChangeType type; private final int index; /** * @deprecated */ public ElementEvent(Object source, Object oldValue, Object newValue, int index, int type) { this(source, oldValue, newValue, index, ChangeType.resolve(type)); } public ElementEvent(Object source, Object oldValue, Object newValue, int index, ChangeType type) { super(source, ObservableList.CONTENT_PROPERTY, oldValue, newValue); this.type = type; this.index = index; } public int getIndex() { return index; } public int getType() { return type.ordinal(); } public ChangeType getChangeType() { return type; } public String getTypeAsString() { return type.name().toUpperCase(); } } public static class ElementAddedEvent extends ElementEvent { public ElementAddedEvent(Object source, Object newValue, int index) { super(source, null, newValue, index, ChangeType.ADDED); } } public static class ElementUpdatedEvent extends ElementEvent { public ElementUpdatedEvent(Object source, Object oldValue, Object newValue, int index) { super(source, oldValue, newValue, index, ChangeType.UPDATED); } } public static class ElementRemovedEvent extends ElementEvent { public ElementRemovedEvent(Object source, Object value, int index) { super(source, value, null, index, ChangeType.REMOVED); } } public static class ElementClearedEvent extends ElementEvent { private List values = new ArrayList(); public ElementClearedEvent(Object source, List values) { super(source, ChangeType.oldValue, ChangeType.newValue, 0, ChangeType.CLEARED); if (values != null) { this.values.addAll(values); } } public List getValues() { return Collections.unmodifiableList(values); } } public static class MultiElementAddedEvent extends ElementEvent { private List values = new ArrayList(); public MultiElementAddedEvent(Object source, int index, List values) { super(source, ChangeType.oldValue, ChangeType.newValue, index, ChangeType.MULTI_ADD); if (values != null) { this.values.addAll(values); } } public List getValues() { return Collections.unmodifiableList(values); } } public static class MultiElementRemovedEvent extends ElementEvent { private List values = new ArrayList(); public MultiElementRemovedEvent(Object source, List values) { super(source, ChangeType.oldValue, ChangeType.newValue, 0, ChangeType.MULTI_REMOVE); if (values != null) { this.values.addAll(values); } } public List getValues() { return Collections.unmodifiableList(values); } } } groovy-1.8.6/src/main/groovy/util/ResourceConnector.java0000644001501200150120000000204611627206700022716 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.net.URLConnection; /** * Base interface for customizing where resources can be found for the GroovyScriptEngine. * * @author sam */ public interface ResourceConnector { /** * Retrieve a URLConnection to a script referenced by name. * * @param name * @throws ResourceException */ URLConnection getResourceConnection(String name) throws ResourceException; } groovy-1.8.6/src/main/groovy/util/logging/0000755001501200150120000000000011707612044020036 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/util/logging/Slf4j.java0000644001501200150120000000753311707612044021673 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.logging; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import org.codehaus.groovy.transform.LogASTTransformation; import org.objectweb.asm.Opcodes; /** * This local transform adds a logging ability to your program using * LogBack logging. Every method call on a unbound variable named log * will be mapped to a call to the logger. For this a log field will be * inserted in the class. If the field already exists the usage of this transform * will cause a compilation error. The method name will be used to determine * what to call on the logger. *
     * log.name(exp)
     * 
    is mapped to *
     * if (log.isNameLoggable() {
     *    log.name(exp)
     * }
    * Here name is a place holder for info, debug, warning, error, etc. * If the expression exp is a constant or only a variable access the method call will * not be transformed. But this will still cause a call on the injected logger. * * @author Hamlet D'Arcy * @author Alberto Mijares * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation") public @interface Slf4j { String value() default "log"; Class loggingStrategy() default Slf4jLoggingStrategy.class; public static class Slf4jLoggingStrategy implements LogASTTransformation.LoggingStrategy { public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName) { return classNode.addField(logFieldName, Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT | Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE, new ClassNode("org.slf4j.Logger", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE), new MethodCallExpression( new ClassExpression(new ClassNode("org.slf4j.LoggerFactory", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)), "getLogger", new ClassExpression(classNode))); } public boolean isLoggingMethod(String methodName) { return methodName.matches("error|warn|info|debug|trace"); } public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) { MethodCallExpression condition = new MethodCallExpression( logVariable, "is" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1, methodName.length()) + "Enabled", ArgumentListExpression.EMPTY_ARGUMENTS); return new TernaryExpression( new BooleanExpression(condition), originalExpression, ConstantExpression.NULL); } } } groovy-1.8.6/src/main/groovy/util/logging/Log4j.java0000644001501200150120000001113311707612044021657 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.logging; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import org.codehaus.groovy.transform.LogASTTransformation; import org.objectweb.asm.Opcodes; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This local transform adds a logging ability to your program using * Log4j logging. Every method call on a unbound variable named log * will be mapped to a call to the logger. For this a log field will be * inserted in the class. If the field already exists the usage of this transform * will cause a compilation error. The method name will be used to determine * what to call on the logger. *
     * log.name(exp)
     * 
    is mapped to *
     * if (log.isNameEnabled() {
     *    log.name(exp)
     * }
    * Here name is a place holder for info, debug, warning, error, etc. * If the expression exp is a constant or only a variable access the method call will * not be transformed. But this will still cause a call on the injected logger. * * @author Hamlet D'Arcy * @author Tomek Bujok * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation") public @interface Log4j { String value() default "log"; Class loggingStrategy() default Log4jLoggingStrategy.class; public static class Log4jLoggingStrategy implements LogASTTransformation.LoggingStrategy { public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName) { return classNode.addField(logFieldName, Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT | Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE, new ClassNode("org.apache.log4j.Logger", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE), new MethodCallExpression( new ClassExpression(new ClassNode("org.apache.log4j.Logger", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)), "getLogger", new ClassExpression(classNode))); } public boolean isLoggingMethod(String methodName) { return methodName.matches("fatal|error|warn|info|debug|trace"); } public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) { final MethodCallExpression condition; if (!"trace".equals(methodName)) { ClassNode levelClass = new ClassNode("org.apache.log4j.Priority", 0, ClassHelper.OBJECT_TYPE); AttributeExpression logLevelExpression = new AttributeExpression( new ClassExpression(levelClass), new ConstantExpression(methodName.toUpperCase())); ArgumentListExpression args = new ArgumentListExpression(); args.addExpression(logLevelExpression); condition = new MethodCallExpression(logVariable, "isEnabledFor", args); } else { // log4j api is inconsistent, so trace requires special handling condition = new MethodCallExpression( logVariable, "is" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1, methodName.length()) + "Enabled", ArgumentListExpression.EMPTY_ARGUMENTS); } return new TernaryExpression( new BooleanExpression(condition), originalExpression, ConstantExpression.NULL); } } } groovy-1.8.6/src/main/groovy/util/logging/Commons.java0000644001501200150120000000745411707612044022326 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.logging; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import org.codehaus.groovy.transform.LogASTTransformation; import org.objectweb.asm.Opcodes; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This local transform adds a logging ability to your program using * Apache Commons logging. Every method call on a unbound variable named log * will be mapped to a call to the logger. For this a log field will be * inserted in the class. If the field already exists the usage of this transform * will cause a compilation error. The method name will be used to determine * what to call on the logger. *
     * log.name(exp)
     * 
    is mapped to *
     * if (log.isNameEnabled() {
     *    log.name(exp)
     * }
    * Here name is a place holder for info, debug, warning, error, etc. * If the expression exp is a constant or only a variable access the method call will * not be transformed. But this will still cause a call on the injected logger. * * @author Hamlet D'Arcy * @author Matthias Cullmann * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation") public @interface Commons { String value() default "log"; Class loggingStrategy() default CommonsLoggingStrategy.class; public static class CommonsLoggingStrategy implements LogASTTransformation.LoggingStrategy { public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName) { return classNode.addField(logFieldName, Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT | Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE, new ClassNode("org.apache.commons.logging.Log", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE), new MethodCallExpression( new ClassExpression(new ClassNode("org.apache.commons.logging.LogFactory", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)), "getLog", new ClassExpression(classNode))); } public boolean isLoggingMethod(String methodName) { return methodName.matches("fatal|error|warn|info|debug|trace"); } public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) { MethodCallExpression condition = new MethodCallExpression( logVariable, "is" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1, methodName.length()) + "Enabled", ArgumentListExpression.EMPTY_ARGUMENTS); return new TernaryExpression( new BooleanExpression(condition), originalExpression, ConstantExpression.NULL); } } } groovy-1.8.6/src/main/groovy/util/logging/Log.java0000644001501200150120000001075411707612044021431 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util.logging; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import org.codehaus.groovy.transform.LogASTTransformation.LoggingStrategy; import org.objectweb.asm.Opcodes; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This local transform adds a logging ability to your program using * java.util.logging. Every method call on a unbound variable named log * will be mapped to a call to the logger. For this a log field will be * inserted in the class. If the field already exists the usage of this transform * will cause a compilation error. The method name will be used to determine * what to call on the logger. *
     * log.name(exp)
     * 
    is mapped to *
     * if (log.isLoggable(Level.NAME) {
     *    log.name(exp)
     * }
    * Here name is a place holder for info, fine, finer, finest, config, warning, severe. * NAME is name transformed to upper case. if anything else is used it will result in * an exception at runtime. If the expression exp is a constant or only a variable access * the method call will not be transformed. But this will still cause a call on the injected * logger. * * @author Guillaume Laforge * @author Jochen Theodorou * @author Dinko Srkoc * @author Hamlet D'Arcy * @author Raffaele Cigni * @author Alberto Vilches Raton * @since 1.8.0 */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation") public @interface Log { String value() default "log"; Class loggingStrategy() default JavaUtilLoggingStrategy.class; /** * This class contains the logic of how to weave a Java Util Logging logger into the host class. */ public static class JavaUtilLoggingStrategy implements LoggingStrategy { public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName) { return classNode.addField(logFieldName, Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT | Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE, new ClassNode("java.util.logging.Logger", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE), new MethodCallExpression( new ClassExpression(new ClassNode("java.util.logging.Logger", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)), "getLogger", new ConstantExpression(classNode.getName()))); } public boolean isLoggingMethod(String methodName) { return methodName.matches("severe|warning|info|fine|finer|finest"); } public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) { ClassNode levelClass = new ClassNode("java.util.logging.Level", 0, ClassHelper.OBJECT_TYPE); AttributeExpression logLevelExpression = new AttributeExpression( new ClassExpression(levelClass), new ConstantExpression(methodName.toUpperCase())); ArgumentListExpression args = new ArgumentListExpression(); args.addExpression(logLevelExpression); MethodCallExpression condition = new MethodCallExpression(logVariable, "isLoggable", args); return new TernaryExpression( new BooleanExpression(condition), originalExpression, ConstantExpression.NULL); } } } groovy-1.8.6/src/main/groovy/util/CharsetToolkit.java0000644001501200150120000003555211707612044022224 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.io.*; import java.nio.charset.Charset; import java.util.Collection; /** *

    Utility class to guess the encoding of a given text file.

    * *

    Unicode files encoded in UTF-16 (low or big endian) or UTF-8 files * with a Byte Order Marker are correctly discovered. For UTF-8 files with no BOM, if the buffer * is wide enough, the charset should also be discovered.

    * *

    A byte buffer of 4KB is used to be able to guess the encoding.

    * *

    Usage:

    *
     * CharsetToolkit toolkit = new CharsetToolkit(file);
     *
     * // guess the encoding
     * Charset guessedCharset = toolkit.getCharset();
     *
     * // create a reader with the correct charset
     * BufferedReader reader = toolkit.getReader();
     *
     * // read the file content
     * String line;
     * while ((line = br.readLine())!= null)
     * {
     *     System.out.println(line);
     * }
     * 
    * * @author Guillaume Laforge */ public class CharsetToolkit { private byte[] buffer; private Charset defaultCharset; private Charset charset; private boolean enforce8Bit = true; private final File file; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * Constructor of the CharsetToolkit utility class. * * @param file of which we want to know the encoding. */ public CharsetToolkit(File file) throws IOException { this.file = file; this.defaultCharset = getDefaultSystemCharset(); this.charset = null; InputStream input = new FileInputStream(file); try { byte[] bytes = new byte[4096]; int bytesRead = input.read(bytes); if (bytesRead == -1) { this.buffer = EMPTY_BYTE_ARRAY; } else if (bytesRead < 4096) { byte[] bytesToGuess = new byte[bytesRead]; System.arraycopy(bytes, 0, bytesToGuess, 0, bytesRead); this.buffer = bytesToGuess; } else { this.buffer = bytes; } } finally { try {input.close();} catch (IOException e){ // IGNORE } } } /** * Defines the default Charset used in case the buffer represents * an 8-bit Charset. * * @param defaultCharset the default Charset to be returned * if an 8-bit Charset is encountered. */ public void setDefaultCharset(Charset defaultCharset) { if (defaultCharset != null) this.defaultCharset = defaultCharset; else this.defaultCharset = getDefaultSystemCharset(); } public Charset getCharset() { if (this.charset == null) this.charset = guessEncoding(); return charset; } /** * If US-ASCII is recognized, enforce to return the default encoding, rather than US-ASCII. * It might be a file without any special character in the range 128-255, but that may be or become * a file encoded with the default charset rather than US-ASCII. * * @param enforce a boolean specifying the use or not of US-ASCII. */ public void setEnforce8Bit(boolean enforce) { this.enforce8Bit = enforce; } /** * Gets the enforce8Bit flag, in case we do not want to ever get a US-ASCII encoding. * * @return a boolean representing the flag of use of US-ASCII. */ public boolean getEnforce8Bit() { return this.enforce8Bit; } /** * Retrieves the default Charset */ public Charset getDefaultCharset() { return defaultCharset; } /** *

    Guess the encoding of the provided buffer.

    * If Byte Order Markers are encountered at the beginning of the buffer, we immediately * return the charset implied by this BOM. Otherwise, the file would not be a human * readable text file.

    * *

    If there is no BOM, this method tries to discern whether the file is UTF-8 or not. * If it is not UTF-8, we assume the encoding is the default system encoding * (of course, it might be any 8-bit charset, but usually, an 8-bit charset is the default one).

    * *

    It is possible to discern UTF-8 thanks to the pattern of characters with a multi-byte sequence.

    *
         * UCS-4 range (hex.)        UTF-8 octet sequence (binary)
         * 0000 0000-0000 007F       0xxxxxxx
         * 0000 0080-0000 07FF       110xxxxx 10xxxxxx
         * 0000 0800-0000 FFFF       1110xxxx 10xxxxxx 10xxxxxx
         * 0001 0000-001F FFFF       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
         * 0020 0000-03FF FFFF       111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
         * 0400 0000-7FFF FFFF       1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
         * 
    *

    With UTF-8, 0xFE and 0xFF never appear.

    * * @return the Charset recognized. */ private Charset guessEncoding() { // if the file has a Byte Order Marker, we can assume the file is in UTF-xx // otherwise, the file would not be human readable if (hasUTF8Bom()) return Charset.forName("UTF-8"); if (hasUTF16LEBom()) return Charset.forName("UTF-16LE"); if (hasUTF16BEBom()) return Charset.forName("UTF-16BE"); // if a byte has its most significant bit set, the file is in UTF-8 or in the default encoding // otherwise, the file is in US-ASCII boolean highOrderBit = false; // if the file is in UTF-8, high order bytes must have a certain value, in order to be valid // if it's not the case, we can assume the encoding is the default encoding of the system boolean validU8Char = true; // TODO the buffer is not read up to the end, but up to length - 6 int length = buffer.length; int i = 0; while (i < length - 6) { byte b0 = buffer[i]; byte b1 = buffer[i + 1]; byte b2 = buffer[i + 2]; byte b3 = buffer[i + 3]; byte b4 = buffer[i + 4]; byte b5 = buffer[i + 5]; if (b0 < 0) { // a high order bit was encountered, thus the encoding is not US-ASCII // it may be either an 8-bit encoding or UTF-8 highOrderBit = true; // a two-bytes sequence was encountered if (isTwoBytesSequence(b0)) { // there must be one continuation byte of the form 10xxxxxx, // otherwise the following characteris is not a valid UTF-8 construct if (!isContinuationChar(b1)) validU8Char = false; else i++; } // a three-bytes sequence was encountered else if (isThreeBytesSequence(b0)) { // there must be two continuation bytes of the form 10xxxxxx, // otherwise the following characteris is not a valid UTF-8 construct if (!(isContinuationChar(b1) && isContinuationChar(b2))) validU8Char = false; else i += 2; } // a four-bytes sequence was encountered else if (isFourBytesSequence(b0)) { // there must be three continuation bytes of the form 10xxxxxx, // otherwise the following characteris is not a valid UTF-8 construct if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3))) validU8Char = false; else i += 3; } // a five-bytes sequence was encountered else if (isFiveBytesSequence(b0)) { // there must be four continuation bytes of the form 10xxxxxx, // otherwise the following characteris is not a valid UTF-8 construct if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4))) validU8Char = false; else i += 4; } // a six-bytes sequence was encountered else if (isSixBytesSequence(b0)) { // there must be five continuation bytes of the form 10xxxxxx, // otherwise the following characteris is not a valid UTF-8 construct if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4) && isContinuationChar(b5))) validU8Char = false; else i += 5; } else validU8Char = false; } if (!validU8Char) break; i++; } // if no byte with an high order bit set, the encoding is US-ASCII // (it might have been UTF-7, but this encoding is usually internally used only by mail systems) if (!highOrderBit) { // returns the default charset rather than US-ASCII if the enforce8Bit flag is set. if (this.enforce8Bit) return this.defaultCharset; else return Charset.forName("US-ASCII"); } // if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8, // otherwise the file would not be human readable if (validU8Char) return Charset.forName("UTF-8"); // finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding return this.defaultCharset; } /** * If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character; * * @param b a byte. * @return true if it's a continuation char. */ private static boolean isContinuationChar(byte b) { return -128 <= b && b <= -65; } /** * If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character. * * @param b a byte. * @return true if it's the first byte of a two-bytes sequence. */ private static boolean isTwoBytesSequence(byte b) { return -64 <= b && b <= -33; } /** * If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character. * * @param b a byte. * @return true if it's the first byte of a three-bytes sequence. */ private static boolean isThreeBytesSequence(byte b) { return -32 <= b && b <= -17; } /** * If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character. * * @param b a byte. * @return true if it's the first byte of a four-bytes sequence. */ private static boolean isFourBytesSequence(byte b) { return -16 <= b && b <= -9; } /** * If the byte has the form 11110xx, then it's the first byte of a five-bytes sequence character. * * @param b a byte. * @return true if it's the first byte of a five-bytes sequence. */ private static boolean isFiveBytesSequence(byte b) { return -8 <= b && b <= -5; } /** * If the byte has the form 1110xxx, then it's the first byte of a six-bytes sequence character. * * @param b a byte. * @return true if it's the first byte of a six-bytes sequence. */ private static boolean isSixBytesSequence(byte b) { return -4 <= b && b <= -3; } /** * Retrieve the default charset of the system. * * @return the default Charset. */ public static Charset getDefaultSystemCharset() { return Charset.forName(System.getProperty("file.encoding")); } /** * Has a Byte Order Marker for UTF-8 (Used by Microsoft's Notepad and other editors). * * @return true if the buffer has a BOM for UTF8. */ public boolean hasUTF8Bom() { if (buffer.length >= 3) return (buffer[0] == -17 && buffer[1] == -69 && buffer[2] == -65); else return false; } /** * Has a Byte Order Marker for UTF-16 Low Endian * (ucs-2le, ucs-4le, and ucs-16le). * * @return true if the buffer has a BOM for UTF-16 Low Endian. */ public boolean hasUTF16LEBom() { if (buffer.length >= 2) return (buffer[0] == -1 && buffer[1] == -2); else return false; } /** * Has a Byte Order Marker for UTF-16 Big Endian * (utf-16 and ucs-2). * * @return true if the buffer has a BOM for UTF-16 Big Endian. */ public boolean hasUTF16BEBom() { if (buffer.length >= 2) return (buffer[0] == -2 && buffer[1] == -1); else return false; } /** * Gets a BufferedReader (indeed a LineNumberReader) from the File * specified in the constructor of CharsetToolkit using the charset discovered or the default * charset if an 8-bit Charset is encountered. * * @return a BufferedReader * @throws FileNotFoundException if the file is not found. */ public BufferedReader getReader() throws FileNotFoundException { LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset())); if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) { try { reader.read(); } catch (IOException e) { // should never happen, as a file with no content // but with a BOM has at least one char } } return reader; } /** * Retrieves all the available Charsets on the platform, * among which the default charset. * * @return an array of Charsets. */ public static Charset[] getAvailableCharsets() { Collection collection = Charset.availableCharsets().values(); return (Charset[]) collection.toArray(new Charset[collection.size()]); } } groovy-1.8.6/src/main/groovy/util/GroovyTestSuite.java0000644001501200150120000000574411715031256022423 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.GroovyClassLoader; import groovy.lang.Script; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.codehaus.groovy.runtime.ScriptTestAdapter; import java.io.File; /** * A TestSuite which will run a Groovy unit test case inside any Java IDE * either as a unit test case or as an application. *

    * You can specify the GroovyUnitTest to run by running this class as an application * and specifying the script to run on the command line. *

    * * java groovy.util.GroovyTestSuite src/test/Foo.groovy * *

    * Or to run the test suite as a unit test suite in an IDE you can use * the 'test' system property to define the test script to run. * e.g. pass this into the JVM when the unit test plugin runs... *

    * * -Dtest=src/test/Foo.groovy * * * @author James Strachan * @version $Revision$ */ public class GroovyTestSuite extends TestSuite { protected static String file = null; protected final GroovyClassLoader loader = new GroovyClassLoader(GroovyTestSuite.class.getClassLoader()); public static void main(String[] args) { if (args.length > 0) { file = args[0]; } TestRunner.run(suite()); } public static Test suite() { GroovyTestSuite suite = new GroovyTestSuite(); try { suite.loadTestSuite(); } catch (Exception e) { throw new RuntimeException("Could not create the test suite: " + e, e); } return suite; } public void loadTestSuite() throws Exception { String fileName = System.getProperty("test", file); if (fileName == null) { throw new RuntimeException("No filename given in the 'test' system property so cannot run a Groovy unit test"); } System.out.println("Compiling: " + fileName); Class type = compile(fileName); String[] args = {}; if (!Test.class.isAssignableFrom(type) && Script.class.isAssignableFrom(type)) { // let's treat the script as a Test addTest(new ScriptTestAdapter(type, args)); } else { addTestSuite(type); } } public Class compile(String fileName) throws Exception { return loader.parseClass(new File(fileName)); } } groovy-1.8.6/src/main/groovy/util/GroovyScriptEngine.java0000644001501200150120000005714411715031256023065 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Binding; import groovy.lang.DeprecationException; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyCodeSource; import groovy.lang.GroovyResourceLoader; import groovy.lang.Script; import java.io.*; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.tools.gse.DependencyTracker; import org.codehaus.groovy.tools.gse.StringSetMap; /** * Specific script engine able to reload modified scripts as well as dealing properly * with dependent scripts. * * @author sam * @author Marc Palmer * @author Guillaume Laforge * @author Jochen Theodorou */ public class GroovyScriptEngine implements ResourceConnector { private static final ClassLoader CL_STUB = new ClassLoader() { }; private static WeakReference> dependencyCache = new WeakReference>(null); private static synchronized ThreadLocal getDepCache() { ThreadLocal local = dependencyCache.get(); if (local != null) return local; local = new ThreadLocal() { @Override protected StringSetMap initialValue() { return new StringSetMap(); } }; dependencyCache = new WeakReference>(local); return local; } private static WeakReference> localCu = new WeakReference>(null); private static synchronized ThreadLocal getLocalCompilationUnit() { ThreadLocal local = localCu.get(); if (local != null) return local; local = new ThreadLocal(); localCu = new WeakReference>(local); return local; } private URL[] roots; private ResourceConnector rc; private final ClassLoader parentLoader; private final GroovyClassLoader groovyLoader; private final Map scriptCache = new ConcurrentHashMap(); private CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); //TODO: more finals? private static class ScriptCacheEntry { private final Class scriptClass; private final long lastModified; private final Set dependencies; public ScriptCacheEntry(Class clazz, long modified, Set depend) { this.scriptClass = clazz; this.lastModified = modified; this.dependencies = depend; } } private class ScriptClassLoader extends GroovyClassLoader { public ScriptClassLoader(GroovyClassLoader loader) { super(loader); setResLoader(); } public ScriptClassLoader(ClassLoader loader) { super(loader); setResLoader(); } private void setResLoader() { final GroovyResourceLoader rl = getResourceLoader(); setResourceLoader(new GroovyResourceLoader() { public URL loadGroovySource(String className) throws MalformedURLException { String filename; for (String extension : getConfig().getScriptExtensions()) { filename = className.replace('.', File.separatorChar) + "." + extension; try { URLConnection dependentScriptConn = rc.getResourceConnection(filename); return dependentScriptConn.getURL(); } catch (ResourceException e) { //TODO: maybe do something here? } } return rl.loadGroovySource(className); } }); } @Override protected CompilationUnit createCompilationUnit(CompilerConfiguration configuration, CodeSource source) { CompilationUnit cu = super.createCompilationUnit(configuration, source); getLocalCompilationUnit().set(cu); final StringSetMap cache = getDepCache().get(); // "." is used to transfer compilation dependencies, which will be // recollected later during compilation for (String depSourcePath : cache.get(".")) { try { cu.addSource(getResourceConnection(depSourcePath).getURL()); } catch (ResourceException e) { /* ignore */ } } // remove all old entries including the "." entry cache.clear(); cu.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { @Override public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { // GROOVY-4013: If it is an inner class, tracking its dependencies doesn't really // serve any purpose and also interferes with the caching done to track dependencies if (classNode instanceof InnerClassNode) return; DependencyTracker dt = new DependencyTracker(source, cache); dt.visitClass(classNode); } }, Phases.CLASS_GENERATION); final List customizers = config.getCompilationCustomizers(); if (customizers!=null) { // GROOVY-4813 : apply configuration customizers for (CompilationCustomizer customizer : customizers) { cu.addPhaseOperation(customizer, customizer.getPhase().getPhaseNumber()); } } return cu; } @Override public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource) throws CompilationFailedException { // local is kept as hard reference to avoid garbage collection ThreadLocal localCu = getLocalCompilationUnit(); ThreadLocal localCache = getDepCache(); // we put the old dependencies into local cache so createCompilationUnit // can pick it up. We put that entry under the name "." ScriptCacheEntry origEntry = scriptCache.get(codeSource.getName()); Set origDep = null; if (origEntry != null) origDep = origEntry.dependencies; if (origDep != null) localCache.get().put(".", origDep); Class answer = super.parseClass(codeSource, false); StringSetMap cache = localCache.get(); cache.makeTransitiveHull(); long now = System.currentTimeMillis(); Set entryNames = new HashSet(); for (Map.Entry> entry : cache.entrySet()) { String className = entry.getKey(); Class clazz = getClassCacheEntry(className); if (clazz == null) continue; String entryName = getPath(clazz); if (entryNames.contains(entryName)) continue; entryNames.add(entryName); Set value = convertToPaths(entry.getValue()); ScriptCacheEntry cacheEntry = new ScriptCacheEntry(clazz, now, value); scriptCache.put(entryName, cacheEntry); } cache.clear(); localCu.set(null); return answer; } private String getPath(Class clazz) { ThreadLocal localCu = getLocalCompilationUnit(); String name = clazz.getName(); ClassNode classNode = localCu.get().getClassNode(name); return classNode.getModule().getContext().getName(); } private Set convertToPaths(Set orig) { Set ret = new HashSet(); for (String className : orig) { Class clazz = getClassCacheEntry(className); if (clazz == null) continue; ret.add(getPath(clazz)); } return ret; } } /** * Simple testing harness for the GSE. Enter script roots as arguments and * then input script names to run them. * * @param urls an array of URLs * @throws Exception if something goes wrong */ public static void main(String[] urls) throws Exception { GroovyScriptEngine gse = new GroovyScriptEngine(urls); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while (true) { System.out.print("groovy> "); if ((line = br.readLine()) == null || line.equals("quit")) break; try { System.out.println(gse.run(line, new Binding())); } catch (Exception e) { e.printStackTrace(); } } } /** * Initialize a new GroovyClassLoader with a default or * constructor-supplied parentClassLoader. * * @return the parent classloader used to load scripts */ private GroovyClassLoader initGroovyLoader() { return (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { if (parentLoader instanceof GroovyClassLoader) { return new ScriptClassLoader((GroovyClassLoader) parentLoader); } else { return new ScriptClassLoader(parentLoader); } } }); } /** * Get a resource connection as a URLConnection to retrieve a script * from the ResourceConnector. * * @param resourceName name of the resource to be retrieved * @return a URLConnection to the resource * @throws ResourceException */ public URLConnection getResourceConnection(String resourceName) throws ResourceException { // Get the URLConnection URLConnection groovyScriptConn = null; ResourceException se = null; for (URL root : roots) { URL scriptURL = null; try { scriptURL = new URL(root, resourceName); groovyScriptConn = scriptURL.openConnection(); // Make sure we can open it, if we can't it doesn't exist. // Could be very slow if there are any non-file:// URLs in there groovyScriptConn.getInputStream(); break; // Now this is a bit unusual } catch (MalformedURLException e) { String message = "Malformed URL: " + root + ", " + resourceName; if (se == null) { se = new ResourceException(message); } else { se = new ResourceException(message, se); } } catch (IOException e1) { groovyScriptConn = null; String message = "Cannot open URL: " + scriptURL; groovyScriptConn = null; if (se == null) { se = new ResourceException(message); } else { se = new ResourceException(message, se); } } } if (se == null) se = new ResourceException("No resource for " + resourceName + " was found"); // If we didn't find anything, report on all the exceptions that occurred. if (groovyScriptConn == null) throw se; return groovyScriptConn; } /** * This method closes a {@link URLConnection} by getting its {@link InputStream} and calling the * {@link InputStream#close()} method on it. The {@link URLConnection} doesn't have a close() method * and relies on garbage collection to close the underlying connection to the file. * Relying on garbage collection could lead to the application exhausting the number of files the * user is allowed to have open at any one point in time and cause the application to crash * ({@link FileNotFoundException} (Too many open files)). * Hence the need for this method to explicitly close the underlying connection to the file. * * @param urlConnection the {@link URLConnection} to be "closed" to close the underlying file descriptors. */ private void forceClose(URLConnection urlConnection) { if (urlConnection != null) { // We need to get the input stream and close it to force the open // file descriptor to be released. Otherwise, we will reach the limit // for number of files open at one time. InputStream in = null; try { in = urlConnection.getInputStream(); } catch (Exception e) { // Do nothing: We were not going to use it anyway. } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Do nothing: Just want to make sure it is closed. } } } } } /** * The groovy script engine will run groovy scripts and reload them and * their dependencies when they are modified. This is useful for embedding * groovy in other containers like games and application servers. * * @param roots This an array of URLs where Groovy scripts will be stored. They should * be laid out using their package structure like Java classes */ private GroovyScriptEngine(URL[] roots, ClassLoader parent, ResourceConnector rc) { if (roots == null) roots = new URL[0]; this.roots = roots; if (rc == null) rc = this; this.rc = rc; if (parent == CL_STUB) parent = this.getClass().getClassLoader(); this.parentLoader = parent; this.groovyLoader = initGroovyLoader(); for (URL root : roots) this.groovyLoader.addURL(root); } public GroovyScriptEngine(URL[] roots) { this(roots, CL_STUB, null); } public GroovyScriptEngine(URL[] roots, ClassLoader parentClassLoader) { this(roots, parentClassLoader, null); } public GroovyScriptEngine(String[] urls) throws IOException { this(createRoots(urls), CL_STUB, null); } private static URL[] createRoots(String[] urls) throws MalformedURLException { if (urls == null) return null; URL[] roots = new URL[urls.length]; for (int i = 0; i < roots.length; i++) { if (urls[i].indexOf("://") != -1) { roots[i] = new URL(urls[i]); } else { roots[i] = new File(urls[i]).toURI().toURL(); } } return roots; } public GroovyScriptEngine(String[] urls, ClassLoader parentClassLoader) throws IOException { this(createRoots(urls), parentClassLoader, null); } public GroovyScriptEngine(String url) throws IOException { this(new String[]{url}); } public GroovyScriptEngine(String url, ClassLoader parentClassLoader) throws IOException { this(new String[]{url}, parentClassLoader); } public GroovyScriptEngine(ResourceConnector rc) { this(null, CL_STUB, rc); } public GroovyScriptEngine(ResourceConnector rc, ClassLoader parentClassLoader) { this(null, parentClassLoader, rc); } /** * Get the ClassLoader that will serve as the parent ClassLoader of the * {@link GroovyClassLoader} in which scripts will be executed. By default, this is the * ClassLoader that loaded the GroovyScriptEngine class. * * @return the parent classloader used to load scripts */ public ClassLoader getParentClassLoader() { return parentLoader; } /** * @param parentClassLoader ClassLoader to be used as the parent ClassLoader * for scripts executed by the engine * @deprecated */ public void setParentClassLoader(ClassLoader parentClassLoader) { throw new DeprecationException( "The method GroovyScriptEngine#setParentClassLoader(ClassLoader) " + "is no longer supported. Specify a parentLoader in the constructor instead." ); } /** * Get the class of the scriptName in question, so that you can instantiate * Groovy objects with caching and reloading. * * @param scriptName resource name pointing to the script * @return the loaded scriptName as a compiled class * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script */ public Class loadScriptByName(String scriptName) throws ResourceException, ScriptException { URLConnection conn = rc.getResourceConnection(scriptName); String path = conn.getURL().getPath(); ScriptCacheEntry entry = scriptCache.get(path); Class clazz = null; if (entry != null) clazz = entry.scriptClass; try { if (isSourceNewer(entry)) { try { String encoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : "UTF-8"; clazz = groovyLoader.parseClass(DefaultGroovyMethods.getText(conn.getInputStream(), encoding), path); } catch (IOException e) { throw new ResourceException(e); } } } finally { forceClose(conn); } return clazz; } /** * Get the class of the scriptName in question, so that you can instantiate * Groovy objects with caching and reloading. * * @param scriptName resource name pointing to the script * @param parentClassLoader the class loader to use when loading the script * @return the loaded scriptName as a compiled class * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script * @deprecated */ public Class loadScriptByName(String scriptName, ClassLoader parentClassLoader) throws ResourceException, ScriptException { throw new DeprecationException( "The method GroovyScriptEngine#loadScriptByName(String,ClassLoader) " + "is no longer supported. Use GroovyScriptEngine#loadScriptByName(String) instead." ); } /** * Run a script identified by name with a single argument. * * @param scriptName name of the script to run * @param argument a single argument passed as a variable named arg in the binding * @return a toString() representation of the result of the execution of the script * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script */ public String run(String scriptName, String argument) throws ResourceException, ScriptException { Binding binding = new Binding(); binding.setVariable("arg", argument); Object result = run(scriptName, binding); return result == null ? "" : result.toString(); } /** * Run a script identified by name with a given binding. * * @param scriptName name of the script to run * @param binding the binding to pass to the script * @return an object * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script */ public Object run(String scriptName, Binding binding) throws ResourceException, ScriptException { return createScript(scriptName, binding).run(); } /** * Creates a Script with a given scriptName and binding. * * @param scriptName name of the script to run * @param binding the binding to pass to the script * @return the script object * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script */ public Script createScript(String scriptName, Binding binding) throws ResourceException, ScriptException { return InvokerHelper.createScript(loadScriptByName(scriptName), binding); } protected boolean isSourceNewer(ScriptCacheEntry entry) throws ResourceException { if (entry == null) return true; long now = System.currentTimeMillis(); for (String scriptName : entry.dependencies) { ScriptCacheEntry depEntry = scriptCache.get(scriptName); long nextPossibleRecompilationTime = depEntry.lastModified + config.getMinimumRecompilationInterval(); if (nextPossibleRecompilationTime > now) continue; URLConnection conn = rc.getResourceConnection(scriptName); // getLastModified() truncates up to 999 ms from the true modification time, let's fix that long lastMod = ((conn.getLastModified() / 1000) + 1) * 1000 - 1; // getResourceConnection() opening the inputstream, let's ensure all streams are closed forceClose(conn); if (depEntry.lastModified < lastMod) { ScriptCacheEntry newEntry = new ScriptCacheEntry(depEntry.scriptClass, lastMod, depEntry.dependencies); scriptCache.put(scriptName, newEntry); return true; } } return false; } /** * Returns the GroovyClassLoader associated with this script engine instance. * Useful if you need to pass the class loader to another library. * * @return the GroovyClassLoader */ public GroovyClassLoader getGroovyClassLoader() { return groovyLoader; } /** * @return a non null compiler configuration */ public CompilerConfiguration getConfig() { return config; } /** * sets a compiler configuration * * @param config - the compiler configuration * @throws NullPointerException if config is null */ public void setConfig(CompilerConfiguration config) { if (config == null) throw new NullPointerException("configuration cannot be null"); this.config = config; } } groovy-1.8.6/src/main/groovy/util/Node.java0000644001501200150120000003526311713765676020172 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import groovy.xml.QName; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.PrintWriter; import java.io.Serializable; import java.util.*; /** * Represents an arbitrary tree node which can be used for structured metadata or any arbitrary XML-like tree. * A node can have a name, a value and an optional Map of attributes. * Typically the name is a String and a value is either a String or a List of other Nodes, * though the types are extensible to provide a flexible structure, e.g. you could use a * QName as the name which includes a namespace URI and a local name. Or a JMX ObjectName etc. * So this class can represent metadata like {foo a=1 b="abc"} or nested * metadata like {foo a=1 b="123" { bar x=12 text="hello" }} * * @author James Strachan * @author Paul King * @version $Revision$ */ public class Node implements Serializable { static { // wrap the standard MetaClass with the delegate setMetaClass(GroovySystem.getMetaClassRegistry().getMetaClass(Node.class), Node.class); } private static final long serialVersionUID = 4121134753270542643L; private Node parent; private Object name; private Map attributes; private Object value; /** * Creates a new Node named name and if a parent is supplied, adds * the newly created node as a child of the parent. * * @param parent the parent node or null if no parent * @param name the name of the node */ public Node(Node parent, Object name) { this(parent, name, new NodeList()); } /** * Creates a new Node named name with value value and * if a parent is supplied, adds the newly created node as a child of the parent. * * @param parent the parent node or null if no parent * @param name the name of the node * @param value the Node value, e.g. some text but in general any Object */ public Node(Node parent, Object name, Object value) { this(parent, name, new HashMap(), value); } /** * Creates a new Node named name with * attributes specified in the attributes Map. If a parent is supplied, * the newly created node is added as a child of the parent. * * @param parent the parent node or null if no parent * @param name the name of the node * @param attributes a Map of name-value pairs */ public Node(Node parent, Object name, Map attributes) { this(parent, name, attributes, new NodeList()); } /** * Creates a new Node named name with value value and * with attributes specified in the attributes Map. If a parent is supplied, * the newly created node is added as a child of the parent. * * @param parent the parent node or null if no parent * @param name the name of the node * @param attributes a Map of name-value pairs * @param value the Node value, e.g. some text but in general any Object */ public Node(Node parent, Object name, Map attributes, Object value) { this.parent = parent; this.name = name; this.attributes = attributes; this.value = value; if (parent != null) { getParentList(parent).add(this); } } private List getParentList(Node parent) { Object parentValue = parent.value(); List parentList; if (parentValue instanceof List) { parentList = (List) parentValue; } else { parentList = new NodeList(); parentList.add(parentValue); parent.setValue(parentList); } return parentList; } public boolean append(Node child) { child.setParent(this); return getParentList(this).add(child); } public boolean remove(Node child) { child.setParent(null); return getParentList(this).remove(child); } public Node appendNode(Object name, Map attributes) { return new Node(this, name, attributes); } public Node appendNode(Object name) { return new Node(this, name); } public Node appendNode(Object name, Object value) { return new Node(this, name, value); } public Node appendNode(Object name, Map attributes, Object value) { return new Node(this, name, attributes, value); } // TODO return replaced node rather than last appended? // * @return the original now replaced node /** * Replaces the current node with nodes defined using builder-style notation via a Closure. * * @param c A Closure defining the new nodes using builder-style notation. * @return the last appended node */ public Node replaceNode(Closure c) { if (parent() == null) { throw new UnsupportedOperationException("Replacing the root node is not supported"); } Node result = appendNodes(c); getParentList(parent()).remove(this); // this.setParent(null); // return this; return result; } /** * Adds sibling nodes (defined using builder-style notation via a Closure) after the current node. * * @param c A Closure defining the new sibling nodes to add using builder-style notation. */ public void plus(Closure c) { if (parent() == null) { throw new UnsupportedOperationException("Adding sibling nodes to the root node is not supported"); } appendNodes(c); } private Node appendNodes(Closure c) { List list = parent().children(); int afterIndex = list.indexOf(this); List leftOvers = new ArrayList(list.subList(afterIndex + 1, list.size())); list.subList(afterIndex + 1, list.size()).clear(); Node lastAppended = null; for (Node child : buildChildrenFromClosure(c)) { lastAppended = parent().appendNode(child.name(), child.attributes(), child.value()); } parent().children().addAll(leftOvers); return lastAppended; } private List buildChildrenFromClosure(Closure c) { NodeBuilder b = new NodeBuilder(); Node newNode = (Node) b.invokeMethod("dummyNode", c); return newNode.children(); } protected static void setMetaClass(final MetaClass metaClass, Class nodeClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { @Override public Object getAttribute(final Object object, final String attribute) { Node n = (Node) object; return n.get("@" + attribute); } @Override public void setAttribute(final Object object, final String attribute, final Object newValue) { Node n = (Node) object; n.attributes().put(attribute, newValue); } @Override public Object getProperty(Object object, String property) { if (object instanceof Node) { Node n = (Node) object; return n.get(property); } return super.getProperty(object, property); } @Override public void setProperty(Object object, String property, Object newValue) { if (property.startsWith("@")) { String attribute = property.substring(1); Node n = (Node) object; n.attributes().put(attribute, newValue); return; } delegate.setProperty(object, property, newValue); } }; GroovySystem.getMetaClassRegistry().setMetaClass(nodeClass, newMetaClass); } public String text() { if (value instanceof String) { return (String) value; } if (value instanceof Collection) { Collection coll = (Collection) value; String previousText = null; StringBuilder sb = null; for (Object child : coll) { if (child instanceof String) { String childText = (String) child; if (previousText == null) { previousText = childText; } else { if (sb == null) { sb = new StringBuilder(); sb.append(previousText); } sb.append(childText); } } } if (sb != null) { return sb.toString(); } else { if (previousText != null) { return previousText; } return ""; } } return "" + value; } public Iterator iterator() { return children().iterator(); } public List children() { if (value == null) { return new NodeList(); } if (value instanceof List) { return (List) value; } // we're probably just a String List result = new NodeList(); result.add(value); return result; } public Map attributes() { return attributes; } public Object attribute(Object key) { return (attributes != null) ? attributes.get(key) : null; } public Object name() { return name; } public Object value() { return value; } public void setValue(Object value) { this.value = value; } public Node parent() { return parent; } protected void setParent(Node parent) { this.parent = parent; } /** * Provides lookup of elements by non-namespaced name * * @param key the name (or shortcut key) of the node(s) of interest * @return the nodes which match key */ public Object get(String key) { if (key != null && key.charAt(0) == '@') { String attributeName = key.substring(1); return attributes().get(attributeName); } if ("..".equals(key)) { return parent(); } if ("*".equals(key)) { return children(); } if ("**".equals(key)) { return depthFirst(); } return getByName(key); } /** * Provides lookup of elements by QName. * * @param name the QName of interest * @return the nodes matching name */ public NodeList getAt(QName name) { NodeList answer = new NodeList(); for (Object child : children()) { if (child instanceof Node) { Node childNode = (Node) child; Object childNodeName = childNode.name(); if (name.matches(childNodeName)) { answer.add(childNode); } } } return answer; } /** * Provides lookup of elements by name. * * @param name the name of interest * @return the nodes matching name */ private NodeList getByName(String name) { NodeList answer = new NodeList(); for (Object child : children()) { if (child instanceof Node) { Node childNode = (Node) child; Object childNodeName = childNode.name(); if (childNodeName instanceof QName) { QName qn = (QName) childNodeName; if (qn.matches(name)) { answer.add(childNode); } } else if (name.equals(childNodeName)) { answer.add(childNode); } } } return answer; } /** * Provide a collection of all the nodes in the tree * using a depth first traversal. * * @return the list of (depth-first) ordered nodes */ public List depthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(depthFirstRest()); return answer; } private List depthFirstRest() { List answer = new NodeList(); for (Iterator iter = InvokerHelper.asIterator(value); iter.hasNext(); ) { Object child = iter.next(); if (child instanceof Node) { Node childNode = (Node) child; List children = childNode.depthFirstRest(); answer.add(childNode); answer.addAll(children); } } return answer; } /** * Provide a collection of all the nodes in the tree * using a breadth-first traversal. * * @return the list of (breadth-first) ordered nodes */ public List breadthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(breadthFirstRest()); return answer; } private List breadthFirstRest() { List answer = new NodeList(); List nextLevelChildren = getDirectChildren(); while (!nextLevelChildren.isEmpty()) { List working = new NodeList(nextLevelChildren); nextLevelChildren = new NodeList(); for (Node childNode : working) { answer.add(childNode); List children = childNode.getDirectChildren(); nextLevelChildren.addAll(children); } } return answer; } private List getDirectChildren() { List answer = new NodeList(); for (Iterator iter = InvokerHelper.asIterator(value); iter.hasNext(); ) { Object child = iter.next(); if (child instanceof Node) { Node childNode = (Node) child; answer.add(childNode); } } return answer; } public String toString() { return name + "[attributes=" + attributes + "; value=" + value + "]"; } public void print(PrintWriter out) { new NodePrinter(out).print(this); } } groovy-1.8.6/src/main/groovy/util/IFileNameFinder.java0000644001501200150120000000150611715031256022175 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import java.util.List; public interface IFileNameFinder { List getFileNames(String basedir, String pattern); List getFileNames(String basedir, String pattern, String excludesPattern); } groovy-1.8.6/src/main/groovy/util/ClosureComparator.java0000644001501200150120000000243111627206700022716 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.util; import groovy.lang.Closure; import java.util.Comparator; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * A Comparator which uses a closure to compare 2 values being equal * * @author James Strachan * @version $Revision$ */ public class ClosureComparator implements Comparator { Closure closure; public ClosureComparator(Closure closure) { this.closure = closure; } public int compare(T object1, T object2) { Object value = closure.call(new Object[] {object1, object2}); return DefaultTypeTransformation.intUnbox(value); } } groovy-1.8.6/src/main/groovy/security/0000755001501200150120000000000011627206700017301 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/security/package.html0000644001501200150120000000022211627206700021556 0ustar miguelmiguel package groovy.security.*

    Security-related classes

    groovy-1.8.6/src/main/groovy/security/GroovyCodeSourcePermission.java0000644001501200150120000000233711627206700025463 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.security; import java.security.BasicPermission; /** * Permission required to explicitly specify a codebase for a groovy script whose * codebase cannot be determined. Typically this permission is only * required by clients that want to associate a code source with a script which * is a String or an InputStream. * * @author Steve Goetze */ public final class GroovyCodeSourcePermission extends BasicPermission { public GroovyCodeSourcePermission(String name) { super(name); } public GroovyCodeSourcePermission(String name, String actions) { super(name, actions); } } groovy-1.8.6/src/main/groovy/xml/0000755001501200150120000000000011715031256016232 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/xml/MarkupBuilder.java0000644001501200150120000004473311715031256021656 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.util.BuilderSupport; import groovy.util.IndentPrinter; import java.io.PrintWriter; import java.io.Writer; import java.util.Map; import java.util.Iterator; /** *

    A helper class for creating XML or HTML markup. * The builder supports various 'pretty printed' formats.

    *

    *

    Example:

    *
    new MarkupBuilder().root {
     *   a( a1:'one' ) {
     *     b { mkp.yield( '3 < 5' ) }
     *     c( a2:'two', 'blah' )
     *   }
     * }
    * Will print the following to System.out: *
    <root>
     *   <a a1='one'>
     *     <b>3 &lt; 5</b>
     *     <c a2='two'>blah</c>
     *   </a>
     * </root>
    * Notes: *
      *
    • mkp is a special namespace used to escape * away from the normal building mode of the builder and get access * to helper markup methods such as 'yield' and 'yieldUnescaped'. * See the javadoc for {@link #getMkp()} for further details.
    • *
    • Note that tab, newline and carriage return characters are escaped within attributes, i.e. will become , and respectively
    • *
    * @author James Strachan * @author Stefan Matthias Aust * @author Scott Stirling * @author Paul King * @version $Revision$ */ public class MarkupBuilder extends BuilderSupport { private IndentPrinter out; private boolean nospace; private int state; private boolean nodeIsEmpty = true; private boolean useDoubleQuotes = false; private boolean omitNullAttributes = false; private boolean omitEmptyAttributes = false; private boolean expandEmptyElements = false; /** * Prints markup to System.out * * @see IndentPrinter#IndentPrinter() */ public MarkupBuilder() { this(new IndentPrinter()); } /** * Sends markup to the given PrintWriter * * @param pw the PrintWriter to use * @see IndentPrinter#IndentPrinter(Writer) */ public MarkupBuilder(PrintWriter pw) { this(new IndentPrinter(pw)); } /** * Sends markup to the given Writer but first wrapping it in a PrintWriter * * @param writer the writer to use * @see IndentPrinter#IndentPrinter(Writer) */ public MarkupBuilder(Writer writer) { this(new IndentPrinter(new PrintWriter(writer))); } /** * Sends markup to the given IndentPrinter. Use this option if you want * to customize the indent used or provide your own IndentPrinter. * * @param out the IndentPrinter to use */ public MarkupBuilder(IndentPrinter out) { this.out = out; } /** * Returns true if attribute values are output with * double quotes; false if single quotes are used. * By default, single quotes are used. * * @return true if double quotes are used for attributes */ public boolean getDoubleQuotes() { return this.useDoubleQuotes; } /** * Sets whether the builder outputs attribute values in double * quotes or single quotes. * * @param useDoubleQuotes If this parameter is true, * double quotes are used; otherwise, single quotes are. */ public void setDoubleQuotes(boolean useDoubleQuotes) { this.useDoubleQuotes = useDoubleQuotes; } /** * Determine whether null attributes will appear in the produced markup. * * @return true, if null attributes will be * removed from the resulting markup. */ public boolean isOmitNullAttributes() { return omitNullAttributes; } /** * Allows null attributes to be removed from the generated markup. * * @param omitNullAttributes if true, null * attributes will not be included in the resulting markup. * If false null attributes will be included in the * markup as empty strings regardless of the omitEmptyAttribute * setting. Defaults to false. */ public void setOmitNullAttributes(boolean omitNullAttributes) { this.omitNullAttributes = omitNullAttributes; } /** * Determine whether empty attributes will appear in the produced markup. * * @return true, if empty attributes will be * removed from the resulting markup. */ public boolean isOmitEmptyAttributes() { return omitEmptyAttributes; } /** * Allows empty attributes to be removed from the generated markup. * * @param omitEmptyAttributes if true, empty * attributes will not be included in the resulting markup. * Defaults to false. */ public void setOmitEmptyAttributes(boolean omitEmptyAttributes) { this.omitEmptyAttributes = omitEmptyAttributes; } /** * Whether empty elements are expanded from <tagName/> to <tagName></tagName>. * * @return true, if empty elements will be represented by an opening tag * followed immediately by a closing tag. */ public boolean isExpandEmptyElements() { return expandEmptyElements; } /** * Whether empty elements are expanded from to . * * @param expandEmptyElements if true, empty * elements will be represented by an opening tag * followed immediately by a closing tag. * Defaults to false. */ public void setExpandEmptyElements(boolean expandEmptyElements) { this.expandEmptyElements = expandEmptyElements; } protected IndentPrinter getPrinter() { return this.out; } protected void setParent(Object parent, Object child) { } /** * Property that may be called from within your builder closure to access * helper methods, namely {@link MarkupBuilderHelper#yield(String)}, * {@link MarkupBuilderHelper#yieldUnescaped(String)}, * {@link MarkupBuilderHelper#pi(Map)}, * {@link MarkupBuilderHelper#xmlDeclaration(Map)} and * {@link MarkupBuilderHelper#comment(String)}. * * @return this MarkupBuilder */ public Object getMkp() { return new MarkupBuilderHelper(this); } /** * Produce an XML processing instruction in the output. * For example: *
         * mkp.pi("xml-stylesheet":[href:"mystyle.css", type:"text/css"])
         * 
    * * @param args a map with a single entry whose key is the name of the * processing instruction and whose value is the attributes * for the processing instruction. */ void pi(Map> args) { Iterator>> iterator = args.entrySet().iterator(); if (iterator.hasNext()) { Map.Entry> mapEntry = iterator.next(); createNode("?" + mapEntry.getKey(), mapEntry.getValue()); state = 2; out.println("?>"); } } void yield(String value, boolean escaping) { if (state == 1) { state = 2; this.nodeIsEmpty = false; out.print(">"); } if (state == 2 || state == 3) { out.print(escaping ? escapeElementContent(value) : value); } } protected Object createNode(Object name) { Object theName = getName(name); toState(1, theName); this.nodeIsEmpty = true; return theName; } protected Object createNode(Object name, Object value) { Object theName = getName(name); if (value == null) { return createNode(theName); } else { toState(2, theName); this.nodeIsEmpty = false; out.print(">"); out.print(escapeElementContent(value.toString())); return theName; } } protected Object createNode(Object name, Map attributes, Object value) { Object theName = getName(name); toState(1, theName); for (Object p : attributes.entrySet()) { Map.Entry entry = (Map.Entry) p; Object attributeValue = entry.getValue(); boolean skipNull = attributeValue == null && omitNullAttributes; boolean skipEmpty = attributeValue != null && omitEmptyAttributes && attributeValue.toString().length() == 0; if (!skipNull && !skipEmpty) { out.print(" "); // Output the attribute name, print(entry.getKey().toString()); // Output the attribute value within quotes. Use whichever // type of quotes are currently configured. out.print(useDoubleQuotes ? "=\"" : "='"); print(attributeValue == null ? "" : escapeAttributeValue(attributeValue.toString())); out.print(useDoubleQuotes ? "\"" : "'"); } } if (value != null) { yield(value.toString(), true); } else { nodeIsEmpty = true; } return theName; } protected Object createNode(Object name, Map attributes) { return createNode(name, attributes, null); } protected void nodeCompleted(Object parent, Object node) { toState(3, node); out.flush(); } protected void print(Object node) { out.print(node == null ? "null" : node.toString()); } protected Object getName(String methodName) { return super.getName(methodName); } /** * Returns a String with special XML characters escaped as entities so that * output XML is valid. Escapes the following characters as corresponding * entities: *
      *
    • \' as &apos;
    • *
    • & as &amp;
    • *
    • < as &lt;
    • *
    • > as &gt;
    • *
    * * @param value to be searched and replaced for XML special characters. * @return value with XML characters escaped * @see #escapeXmlValue(String, boolean) * @deprecated */ protected String transformValue(String value) { // & has to be checked and replaced before others if (value.matches(".*&.*")) { value = value.replaceAll("&", "&"); } if (value.matches(".*\\'.*")) { value = value.replaceAll("\'", "'"); } if (value.matches(".*<.*")) { value = value.replaceAll("<", "<"); } if (value.matches(".*>.*")) { value = value.replaceAll(">", ">"); } return value; } /** * Escapes a string so that it can be used directly as an XML * attribute value. * * @param value The string to escape. * @return A new string in which all characters that require escaping * have been replaced with the corresponding XML entities. * @see #escapeXmlValue(String, boolean) */ private String escapeAttributeValue(String value) { return escapeXmlValue(value, true); } /** * Escapes a string so that it can be used directly in XML element * content. * * @param value The string to escape. * @return A new string in which all characters that require escaping * have been replaced with the corresponding XML entities. * @see #escapeXmlValue(String, boolean) */ private String escapeElementContent(String value) { return escapeXmlValue(value, false); } /** * Escapes a string so that it can be used in XML text successfully. * It replaces the following characters with the corresponding XML * entities: *
      *
    • & as &amp;
    • *
    • < as &lt;
    • *
    • > as &gt;
    • *
    * If the string is to be added as an attribute value, these * characters are also escaped: *
      *
    • ' as &apos;
    • *
    * * @param value The string to escape. * @param isAttrValue true if the string is to be used * as an attribute value, otherwise false. * @return A new string in which all characters that require escaping * have been replaced with the corresponding XML entities. */ private String escapeXmlValue(String value, boolean isAttrValue) { if (value == null) throw new IllegalArgumentException(); StringBuilder sb = null; // lazy create for edge-case efficiency for (int i = 0, len = value.length(); i < len; i++) { final char ch = value.charAt(i); final String replacement = checkForReplacement(isAttrValue, ch); if (replacement != null) { // output differs from input; we write to our local buffer if (sb == null) { sb = new StringBuilder((int) (1.1 * len)); sb.append(value.substring(0, i)); } sb.append(replacement); } else if (sb != null) { // earlier output differs from input; we write to our local buffer sb.append(ch); } } return sb == null ? value : sb.toString(); } private String checkForReplacement(boolean isAttrValue, char ch) { switch (ch) { case '&': return "&"; case '<': return "<"; case '>': return ">"; case '\n': if (isAttrValue) return " "; break; case '\r': if (isAttrValue) return " "; break; case '\t': if (isAttrValue) return " "; break; case '"': // The double quote is only escaped if the value is for // an attribute and the builder is configured to output // attribute values inside double quotes. if (isAttrValue && useDoubleQuotes) return """; break; case '\'': // The apostrophe is only escaped if the value is for an // attribute, as opposed to element content, and if the // builder is configured to surround attribute values with // single quotes. if (isAttrValue && !useDoubleQuotes) return "'"; break; } return null; } private void toState(int next, Object name) { switch (state) { case 0: switch (next) { case 1: case 2: out.print("<"); print(name); break; case 3: throw new Error(); } break; case 1: switch (next) { case 1: case 2: out.print(">"); if (nospace) { nospace = false; } else { out.println(); out.incrementIndent(); out.printIndent(); } out.print("<"); print(name); break; case 3: if (nodeIsEmpty) { if (expandEmptyElements) { out.print(">"); } else { out.print(" />"); } } break; } break; case 2: switch (next) { case 1: case 2: if (!nodeIsEmpty) { out.println(); out.incrementIndent(); out.printIndent(); } out.print("<"); print(name); break; case 3: out.print(""); break; } break; case 3: switch (next) { case 1: case 2: if (nospace) { nospace = false; } else { out.println(); out.printIndent(); } out.print("<"); print(name); break; case 3: if (nospace) { nospace = false; } else { out.println(); out.decrementIndent(); out.printIndent(); } out.print(""); break; } break; } state = next; } private Object getName(Object name) { if (name instanceof QName) { return ((QName) name).getQualifiedName(); } return name; } } groovy-1.8.6/src/main/groovy/xml/QName.java0000644001501200150120000002451611627206700020106 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * QName class represents the value of a qualified name * as specified in XML * Schema Part2: Datatypes specification. *

    * The value of a QName contains a namespaceURI, a localPart and a prefix. * The localPart provides the local part of the qualified name. The * namespaceURI is a URI reference identifying the namespace. * * @version 1.1 */ public class QName implements Serializable { /** comment/shared empty string */ private static final String EMPTY_STRING = "".intern(); /** Field namespaceURI */ private String namespaceURI; /** Field localPart */ private String localPart; /** Field prefix */ private String prefix; /** * Constructor for the QName. * * @param localPart Local part of the QName */ public QName(String localPart) { this(EMPTY_STRING, localPart, EMPTY_STRING); } /** * Constructor for the QName. * * @param namespaceURI Namespace URI for the QName * @param localPart Local part of the QName. */ public QName(String namespaceURI, String localPart) { this(namespaceURI, localPart, EMPTY_STRING); } /** * Constructor for the QName. * * @param namespaceURI Namespace URI for the QName * @param localPart Local part of the QName. * @param prefix Prefix of the QName. */ public QName(String namespaceURI, String localPart, String prefix) { this.namespaceURI = (namespaceURI == null) ? EMPTY_STRING : namespaceURI.trim().intern(); if (localPart == null) { throw new IllegalArgumentException("invalid QName local part"); } else { this.localPart = localPart.trim().intern(); } if (prefix == null) { throw new IllegalArgumentException("invalid QName prefix"); } else { this.prefix = prefix.trim().intern(); } } /** * Gets the Namespace URI for this QName * * @return Namespace URI */ public String getNamespaceURI() { return namespaceURI; } /** * Gets the Local part for this QName * * @return Local part */ public String getLocalPart() { return localPart; } /** * Gets the Prefix for this QName * * @return Prefix */ public String getPrefix() { return prefix; } /** * Returns the fully qualified name of this QName * * @return a string representation of the QName */ public String getQualifiedName() { return ((prefix.equals(EMPTY_STRING)) ? localPart : prefix + ':' + localPart); } /** * Returns a string representation of this QName * * @return a string representation of the QName */ public String toString() { return ((namespaceURI.equals(EMPTY_STRING)) ? localPart : '{' + namespaceURI + '}' + localPart); } /** * Tests this QName for equality with another object. *

    * If the given object is not a QName or String equivalent or is null then this method * returns false. *

    * For two QNames to be considered equal requires that both * localPart and namespaceURI must be equal. This method uses * String.equals to check equality of localPart * and namespaceURI. Any class that extends QName is required * to satisfy this equality contract. * * If the supplied object is a String, then it is split in two on the last colon * and the first half is compared against the prefix || namespaceURI * and the second half is compared against the localPart * * i.e. assert new QName("namespace","localPart").equals("namespace:localPart") * * Intended Usage: for gpath accessors, e.g. root.'urn:mynamespace:node' * * Warning: this equivalence is not commutative, * i.e. qname.equals(string) may be true/false but string.equals(qname) is always false * *

    * This method satisfies the general contract of the Object.equals method. * * @param o the reference object with which to compare * * @return true if the given object is identical to this * QName: false otherwise. */ public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (o instanceof QName) { final QName qName = (QName) o; if (!namespaceURI.equals(qName.namespaceURI)) return false; return localPart.equals(qName.localPart); } else if (o instanceof String) { final String string = (String)o; if (string.length() == 0) return false; int lastColonIndex = string.lastIndexOf(":"); if (lastColonIndex < 0 || lastColonIndex == string.length() - 1) return false; final String stringPrefix = string.substring(0,lastColonIndex); final String stringLocalPart = string.substring(lastColonIndex + 1); if (stringPrefix.equals(prefix) || stringPrefix.equals(namespaceURI)) { return localPart.equals(stringLocalPart); } return false; } return false; } /** * Tests if this QName matches another object. *

    * If the given object is not a QName or String equivalent or is null then this method * returns false. *

    * For two QNames to be considered matching requires that both * localPart and namespaceURI must be equal or one of them is a wildcard. * * If the supplied object is a String, then it is split in two on the last colon * and the first half is matched against the prefix || namespaceURI * and the second half is matched against the localPart * * @param o the reference object with which to compare * * @return true if the given object matches * this QName: false otherwise. */ public boolean matches(Object o) { if (this == o) return true; if (o == null) return false; if (o instanceof QName) { final QName qName = (QName) o; if (!namespaceURI.equals(qName.namespaceURI) && !namespaceURI.equals("*") && !qName.namespaceURI.equals("*")) return false; return localPart.equals(qName.localPart) || localPart.equals("*") || qName.localPart.equals("*"); } else if (o instanceof String) { final String string = (String)o; if (string.length() == 0) return false; // try matching against 'prefix:localname' int lastColonIndex = string.lastIndexOf(":"); if (lastColonIndex < 0 && prefix.length() == 0) return string.equals(localPart); if (lastColonIndex < 0 || lastColonIndex == string.length() - 1) return false; final String stringPrefix = string.substring(0,lastColonIndex); final String stringLocalPart = string.substring(lastColonIndex + 1); if (stringPrefix.equals(prefix) || stringPrefix.equals(namespaceURI) || stringPrefix.equals("*")) { return localPart.equals(stringLocalPart) || stringLocalPart.equals("*"); } } return false; } /** * Returns a QName holding the value of the specified String. *

    * The string must be in the form returned by the QName.toString() * method, i.e. "{namespaceURI}localPart", with the "{namespaceURI}" * part being optional. *

    * This method doesn't do a full validation of the resulting QName. * In particular, it doesn't check that the resulting namespace URI * is a legal URI (per RFC 2396 and RFC 2732), nor that the resulting * local part is a legal NCName per the XML Namespaces specification. * * @param s the string to be parsed * @throws java.lang.IllegalArgumentException If the specified String cannot be parsed as a QName * @return QName corresponding to the given String */ public static QName valueOf(String s) { if ((s == null) || s.equals("")) { throw new IllegalArgumentException("invalid QName literal"); } if (s.charAt(0) == '{') { int i = s.indexOf('}'); if (i == -1) { throw new IllegalArgumentException("invalid QName literal"); } if (i == s.length() - 1) { throw new IllegalArgumentException("invalid QName literal"); } else { return new QName(s.substring(1, i), s.substring(i + 1)); } } else { return new QName(s); } } /** * Returns a hash code value for this QName object. The hash code * is based on both the localPart and namespaceURI parts of the * QName. This method satisfies the general contract of the * Object.hashCode method. * * @return a hash code value for this Qname object */ public int hashCode() { int result; result = namespaceURI.hashCode(); result = 29 * result + localPart.hashCode(); return result; } /** * Ensure that deserialization properly interns the results. * @param in the ObjectInputStream to be read */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); namespaceURI = namespaceURI.intern(); localPart = localPart.intern(); prefix = prefix.intern(); } } groovy-1.8.6/src/main/groovy/xml/SAXBuilder.java0000644001501200150120000001124011627206700021035 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.util.BuilderSupport; import java.util.Iterator; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * A builder for generating W3C SAX events. Use similar to MarkupBuilder. * * @author James Strachan * @version $Revision$ */ public class SAXBuilder extends BuilderSupport { private ContentHandler handler; private Attributes emptyAttributes = new AttributesImpl(); public SAXBuilder(ContentHandler handler) { this.handler = handler; } protected void setParent(Object parent, Object child) { } protected Object createNode(Object name) { doStartElement(name, emptyAttributes); return name; } protected Object createNode(Object name, Object value) { doStartElement(name, emptyAttributes); doText(value); return name; } /** * @param value */ private void doText(Object value) { try { char[] text = value.toString().toCharArray(); handler.characters(text, 0, text.length); } catch (SAXException e) { handleException(e); } } protected Object createNode(Object name, Map attributeMap, Object text) { AttributesImpl attributes = new AttributesImpl(); for (Iterator iter = attributeMap.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object value = entry.getValue(); String uri = ""; String localName = null; String qualifiedName = ""; String valueText = (value != null) ? value.toString() : ""; if (key instanceof QName) { QName qname = (QName) key; uri = qname.getNamespaceURI(); localName = qname.getLocalPart(); qualifiedName = qname.getQualifiedName(); } else { localName = key.toString(); qualifiedName = localName; } attributes.addAttribute(uri, localName, qualifiedName, "CDATA", valueText); } doStartElement(name, attributes); if (text != null) { doText(text); } return name; } protected void doStartElement(Object name, Attributes attributes) { String uri = ""; String localName = null; String qualifiedName = ""; if (name instanceof QName) { QName qname = (QName) name; uri = qname.getNamespaceURI(); localName = qname.getLocalPart(); qualifiedName = qname.getQualifiedName(); } else { localName = name.toString(); qualifiedName = localName; } try { handler.startElement(uri, localName, qualifiedName, attributes); } catch (SAXException e) { handleException(e); } } protected void nodeCompleted(Object parent, Object name) { String uri = ""; String localName = null; String qualifiedName = ""; if (name instanceof QName) { QName qname = (QName) name; uri = qname.getNamespaceURI(); localName = qname.getLocalPart(); qualifiedName = qname.getQualifiedName(); } else { localName = name.toString(); qualifiedName = localName; } try { handler.endElement(uri, localName, qualifiedName); } catch (SAXException e) { handleException(e); } } protected void handleException(SAXException e) { throw new RuntimeException(e); } /* (non-Javadoc) * @see groovy.util.BuilderSupport#createNode(java.lang.Object, java.util.Map, java.lang.Object) */ protected Object createNode(Object name, Map attributes) { return createNode(name, attributes, null); } } groovy-1.8.6/src/main/groovy/xml/XmlUtil.java0000644001501200150120000002107711713765676020524 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.lang.GroovyRuntimeException; import groovy.lang.Writable; import groovy.util.Node; import groovy.util.XmlNodePrinter; import groovy.util.slurpersupport.GPathResult; import org.codehaus.groovy.runtime.InvokerHelper; import org.w3c.dom.Element; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; /** * Used for pretty printing XML content. * * @author Paul King */ public class XmlUtil { /** * Return a pretty String version of the Element. * * @param element the Element to serialize * @return the pretty String representation of the Element */ public static String serialize(Element element) { StringWriter sw = new StringWriter(); serialize(new DOMSource(element), sw); return sw.toString(); } /** * Write a pretty version of the Element to the OutputStream. * * @param element the Element to serialize * @param os the OutputStream to write to */ public static void serialize(Element element, OutputStream os) { Source source = new DOMSource(element); serialize(source, os); } /** * Write a pretty version of the Element to the Writer. * * @param element the Element to serialize * @param w the Writer to write to */ public static void serialize(Element element, Writer w) { Source source = new DOMSource(element); serialize(source, w); } /** * Return a pretty String version of the Node. * * @param node the Node to serialize * @return the pretty String representation of the Node */ public static String serialize(Node node) { return serialize(asString(node)); } /** * Write a pretty version of the Node to the OutputStream. * * @param node the Node to serialize * @param os the OutputStream to write to */ public static void serialize(Node node, OutputStream os) { serialize(asString(node), os); } /** * Write a pretty version of the Node to the Writer. * * @param node the Node to serialize * @param w the Writer to write to */ public static void serialize(Node node, Writer w) { serialize(asString(node), w); } /** * Return a pretty version of the GPathResult. * * @param node a GPathResult to serialize to a String * @return the pretty String representation of the GPathResult */ public static String serialize(GPathResult node) { return serialize(asString(node)); } /** * Write a pretty version of the GPathResult to the OutputStream. * * @param node a GPathResult to serialize * @param os the OutputStream to write to */ public static void serialize(GPathResult node, OutputStream os) { serialize(asString(node), os); } /** * Write a pretty version of the GPathResult to the Writer. * * @param node a GPathResult to serialize * @param w the Writer to write to */ public static void serialize(GPathResult node, Writer w) { serialize(asString(node), w); } /** * Return a pretty String version of the XML content produced by the Writable. * * @param writable the Writable to serialize * @return the pretty String representation of the content from the Writable */ public static String serialize(Writable writable) { return serialize(asString(writable)); } /** * Write a pretty version of the XML content produced by the Writable to the OutputStream. * * @param writable the Writable to serialize * @param os the OutputStream to write to */ public static void serialize(Writable writable, OutputStream os) { serialize(asString(writable), os); } /** * Write a pretty version of the XML content produced by the Writable to the Writer. * * @param writable the Writable to serialize * @param w the Writer to write to */ public static void serialize(Writable writable, Writer w) { serialize(asString(writable), w); } /** * Return a pretty version of the XML content contained in the given String. * * @param xmlString the String to serialize * @return the pretty String representation of the original content */ public static String serialize(String xmlString) { StringWriter sw = new StringWriter(); serialize(asStreamSource(xmlString), sw); return sw.toString(); } /** * Write a pretty version of the given XML string to the OutputStream. * * @param xmlString the String to serialize * @param os the OutputStream to write to */ public static void serialize(String xmlString, OutputStream os) { serialize(asStreamSource(xmlString), os); } /** * Write a pretty version of the given XML string to the Writer. * * @param xmlString the String to serialize * @param w the Writer to write to */ public static void serialize(String xmlString, Writer w) { serialize(asStreamSource(xmlString), w); } private static String asString(Node node) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); XmlNodePrinter nodePrinter = new XmlNodePrinter(pw); nodePrinter.setPreserveWhitespace(true); nodePrinter.print(node); return sw.toString(); } private static String asString(GPathResult node) { // little bit of hackery to avoid Groovy dependency in this file try { Object builder = ((Class) Class.forName("groovy.xml.StreamingMarkupBuilder")).newInstance(); Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node); return "\n" + w.toString(); } catch (Exception e) { return "Couldn't convert node to string because: " + e.getMessage(); } } // TODO: replace with stream-based version private static String asString(Writable writable) { if (writable instanceof GPathResult) { return asString((GPathResult) writable); //GROOVY-4285 } Writer sw = new StringWriter(); try { writable.writeTo(sw); } catch (IOException e) { // ignore } return sw.toString(); } private static StreamSource asStreamSource(String xmlString) { return new StreamSource(new StringReader(xmlString)); } private static void serialize(Source source, OutputStream os) { try { serialize(source, new StreamResult(new OutputStreamWriter(os, "UTF-8"))); } catch (UnsupportedEncodingException e) { // ignore } } private static void serialize(Source source, Writer w) { serialize(source, new StreamResult(w)); } private static void serialize(Source source, StreamResult target) { TransformerFactory factory = TransformerFactory.newInstance(); setIndent(factory, 2); try { Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); transformer.transform(source, target); } catch (TransformerException e) { throw new GroovyRuntimeException(e.getMessage()); } } private static void setIndent(TransformerFactory factory, int indent) { // TODO: support older parser attribute values as well try { factory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { // ignore for factories that don't support this } } }groovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/0000755001501200150120000000000011715031256023100 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/AbstractStreamingBuilder.groovy0000644001501200150120000000562511627206700031303 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml.streamingmarkupsupport class AbstractStreamingBuilder { def badTagClosure = {tag, doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, Object[] rest -> def uri = pendingNamespaces[prefix] if (uri == null) { uri = namespaces[prefix] } throw new GroovyRuntimeException("Tag ${tag} is not allowed in namespace ${uri}") } def namespaceSetupClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, Object[] rest -> attrs.each { key, value -> if ( key == "") { key = ":" // marker for default namespace } value = value.toString() // in case it's not a string if (namespaces[key] != value) { pendingNamespaces[key] = value } if (!namespaceSpecificTags.containsKey(value)) { def baseEntry = namespaceSpecificTags[':'] namespaceSpecificTags[value] = [baseEntry[0], baseEntry[1], [:]].toArray() } } } def aliasSetupClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, Object[] rest -> attrs.each { key, value -> if (value instanceof Map) { // key is a namespace prefix value is the mapping def info = null if (namespaces.containsKey(key)) { info = namespaceSpecificTags[namespaces[key]] } else if (pendingNamespaces.containsKey(key)) { info = namespaceSpecificTags[pendingNamespaces[key]] } else { throw new GroovyRuntimeException("namespace prefix ${key} has not been declared") } value.each { to, from -> info[2][to] = info[1].curry(from) } } else { def info = namespaceSpecificTags[':'] info[2][key] = info[1].curry(value) } } } def getNamespaceClosure = {doc, pendingNamespaces, namespaces, Object[] rest -> [namespaces, pendingNamespaces]} def specialTags = ['declareNamespace':namespaceSetupClosure, 'declareAlias':aliasSetupClosure, 'getNamespaces':getNamespaceClosure] def builder = null } groovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/Builder.java0000644001501200150120000000466511627206700025344 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml.streamingmarkupsupport; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public abstract class Builder extends GroovyObjectSupport { protected final Map namespaceMethodMap = new HashMap(); public Builder(final Map namespaceMethodMap) { final Iterator keyIterator = namespaceMethodMap.keySet().iterator(); while (keyIterator.hasNext()) { final Object key = keyIterator.next(); final List value = (List)namespaceMethodMap.get(key); final Closure dg = ((Closure)value.get(1)).asWritable(); this.namespaceMethodMap.put(key, new Object[]{value.get(0), dg, fettleMethodMap(dg, (Map)value.get(2))}); } } private static Map fettleMethodMap(final Closure defaultGenerator, final Map methodMap) { final Map newMethodMap = new HashMap(); for (Object o : methodMap.keySet()) { final Object key = o; final Object value = methodMap.get(key); if ((value instanceof Closure)) { newMethodMap.put(key, value); } else { newMethodMap.put(key, defaultGenerator.curry((Object[]) value)); } } return newMethodMap; } public abstract Object bind(Closure root); protected abstract static class Built extends GroovyObjectSupport { protected final Closure root; protected final Map namespaceSpecificTags = new HashMap(); public Built(final Closure root, final Map namespaceTagMap) { this.namespaceSpecificTags.putAll(namespaceTagMap); this.root = (Closure)root.clone(); this.root.setDelegate(this); } } } groovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/package.html0000644001501200150120000000026411627206700025363 0ustar miguelmiguel package groovy.xml.streamingmarkupsupport.*

    XmlBuilder related classes to support streaming XML.

    groovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/BaseMarkupBuilder.java0000644001501200150120000001465311627206700027315 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml.streamingmarkupsupport; import groovy.lang.Closure; import groovy.lang.GroovyInterceptable; import groovy.lang.GroovyObjectSupport; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class BaseMarkupBuilder extends Builder { public BaseMarkupBuilder(final Map namespaceMethodMap) { super(namespaceMethodMap); } public Object bind(final Closure root) { return new Document(root, this.namespaceMethodMap); } private static class Document extends Built implements GroovyInterceptable { private Object out; private final Map pendingNamespaces = new HashMap(); private final Map namespaces = new HashMap(); private final Map specialProperties = new HashMap(); private String prefix = ""; { namespaces.put("xml", "http://www.w3.org/XML/1998/namespace"); // built in namespace namespaces.put("mkp", "http://www.codehaus.org/Groovy/markup/keywords"); // pseudo namespace for markup keywords specialProperties.put("out", new OutputSink("out") { public Object leftShift(final Object value) { return leftShift("yield", value); } }); specialProperties.put("unescaped", new OutputSink("unescaped") { public Object leftShift(final Object value) { return leftShift("yieldUnescaped", value); } }); specialProperties.put("namespaces", new OutputSink("namespaces") { public Object leftShift(final Object value) { return leftShift("declareNamespace", value); } }); specialProperties.put("pi", new OutputSink("pi") { public Object leftShift(final Object value) { return leftShift("pi", value); } }); specialProperties.put("comment", new OutputSink("comment") { public Object leftShift(final Object value) { return leftShift("comment", value); } }); } private abstract class OutputSink extends GroovyObjectSupport { private final String name; public OutputSink(final String name) { this.name = name; } public Object invokeMethod(final String name, final Object args) { Document.this.prefix = this.name; return Document.this.invokeMethod(name, args); } public abstract Object leftShift(Object item); protected Object leftShift(final String command, final Object value) { Document.this.getProperty("mkp"); Document.this.invokeMethod(command, new Object[]{value}); return this; } } public Document(final Closure root, final Map namespaceMethodMap) { super(root, namespaceMethodMap); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object) */ public Object invokeMethod(final String name, final Object args) { final Object[] arguments = (Object[]) args; Map attrs = Collections.EMPTY_MAP; Object body = null; // // Sort the parameters out // for (int i = 0; i != arguments.length; i++) { final Object arg = arguments[i]; if (arg instanceof Map) { attrs = (Map) arg; } else if (arg instanceof Closure) { final Closure c = ((Closure) arg); c.setDelegate(this); body = c.asWritable(); } else { body = arg; } } // // call the closure corresponding to the tag // final Object uri; if (this.pendingNamespaces.containsKey(this.prefix)) { uri = this.pendingNamespaces.get(this.prefix); } else if (this.namespaces.containsKey(this.prefix)) { uri = this.namespaces.get(this.prefix); } else { uri = ":"; } final Object[] info = (Object[]) this.namespaceSpecificTags.get(uri); final Map tagMap = (Map) info[2]; final Closure defaultTagClosure = (Closure) info[0]; final String prefix = this.prefix; this.prefix = ""; if (tagMap.containsKey(name)) { return ((Closure) tagMap.get(name)).call(new Object[]{this, this.pendingNamespaces, this.namespaces, this.namespaceSpecificTags, prefix, attrs, body, this.out}); } else { return defaultTagClosure.call(new Object[]{name, this, this.pendingNamespaces, this.namespaces, this.namespaceSpecificTags, prefix, attrs, body, this.out}); } } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getProperty(java.lang.String) */ public Object getProperty(final String property) { final Object special = this.specialProperties.get(property); if (special == null) { this.prefix = property; return this; } else { return special; } } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(String property, Object newValue) { if ("trigger".equals(property)) { this.out = newValue; this.root.call(this); } else { super.setProperty(property, newValue); } } } } groovy-1.8.6/src/main/groovy/xml/streamingmarkupsupport/StreamingMarkupWriter.java0000644001501200150120000001551411715031256030257 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml.streamingmarkupsupport; import groovy.io.EncodingAwareBufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; public class StreamingMarkupWriter extends Writer { protected final Writer writer; protected final String encoding; protected boolean encodingKnown; protected final CharsetEncoder encoder; protected boolean writingAttribute = false; protected boolean haveHighSurrogate = false; protected StringBuffer surrogatePair = new StringBuffer(2); private boolean useDoubleQuotes; private final Writer escapedWriter = new Writer() { /* (non-Javadoc) * @see java.io.Writer#close() */ public void close() throws IOException { StreamingMarkupWriter.this.close(); } /* (non-Javadoc) * @see java.io.Writer#flush() */ public void flush() throws IOException { StreamingMarkupWriter.this.flush(); } /* (non-Javadoc) * @see java.io.Writer#write(int) */ public void write(final int c) throws IOException { if (c == '<') { StreamingMarkupWriter.this.writer.write("<"); } else if (c == '>') { StreamingMarkupWriter.this.writer.write(">"); } else if (c == '&') { StreamingMarkupWriter.this.writer.write("&"); } else { StreamingMarkupWriter.this.write(c); } } /* (non-Javadoc) * @see java.io.Writer#write(char[], int, int) */ public void write(final char[] cbuf, int off, int len) throws IOException { while (len-- > 0) { write(cbuf[off++]); } } public void setWritingAttribute(final boolean writingAttribute) { StreamingMarkupWriter.this.writingAttribute = writingAttribute; } public Writer excaped() { return escapedWriter; } public Writer unescaped() { return StreamingMarkupWriter.this; } }; public StreamingMarkupWriter(final Writer writer, final String encoding) { this(writer, encoding, false); } public StreamingMarkupWriter(final Writer writer, final String encoding, boolean useDoubleQuotes) { this.useDoubleQuotes = useDoubleQuotes; this.writer = writer; if (encoding != null) { this.encoding = encoding; this.encodingKnown = true; } else if (writer instanceof OutputStreamWriter) { this.encoding = getNormalizedEncoding(((OutputStreamWriter) writer).getEncoding()); this.encodingKnown = true; } else if (writer instanceof EncodingAwareBufferedWriter) { this.encoding = getNormalizedEncoding(((EncodingAwareBufferedWriter) writer).getEncoding()); this.encodingKnown = true; } else { this.encoding = "US-ASCII"; this.encodingKnown = false; } this.encoder = Charset.forName(this.encoding).newEncoder(); } private String getNormalizedEncoding(String unnormalized) { return Charset.forName(unnormalized).name(); } public StreamingMarkupWriter(final Writer writer) { this(writer, null); } /* (non-Javadoc) * @see java.io.Writer#close() */ public void close() throws IOException { this.writer.close(); } /* (non-Javadoc) * @see java.io.Writer#flush() */ public void flush() throws IOException { this.writer.flush(); } /* (non-Javadoc) * @see java.io.Writer#write(int) */ public void write(final int c) throws IOException { if (c >= 0XDC00 && c <= 0XDFFF) { // Low surrogate this.surrogatePair.append((char) c); if (this.encoder.canEncode(this.surrogatePair)) { this.writer.write(this.surrogatePair.toString()); } else { this.writer.write("&#x"); this.writer.write(Integer.toHexString(0X10000 + ((this.surrogatePair.charAt(0) & 0X3FF) << 10) + (c & 0X3FF))); this.writer.write(';'); } this.haveHighSurrogate = false; this.surrogatePair.setLength(0); } else { if (this.haveHighSurrogate) { this.haveHighSurrogate = false; this.surrogatePair.setLength(0); throw new IOException("High Surrogate not followed by Low Surrogate"); } if (c >= 0XD800 && c <= 0XDBFF) { // High surrogate this.surrogatePair.append((char) c); this.haveHighSurrogate = true; } else if (!this.encoder.canEncode((char) c)) { this.writer.write("&#x"); this.writer.write(Integer.toHexString(c)); this.writer.write(';'); } else if (c == '\'' && this.writingAttribute && !useDoubleQuotes) { this.writer.write("'"); } else if (c == '"' && this.writingAttribute && useDoubleQuotes) { this.writer.write("""); } else if (c == '\n' && this.writingAttribute) { this.writer.write(" "); } else if (c == '\r' && this.writingAttribute) { this.writer.write(" "); } else if (c == '\t' && this.writingAttribute) { this.writer.write(" "); } else { this.writer.write(c); } } } /* (non-Javadoc) * @see java.io.Writer#write(char[], int, int) */ public void write(final char[] cbuf, int off, int len) throws IOException { while (len-- > 0) { write(cbuf[off++]); } } public void setWritingAttribute(final boolean writingAttribute) { this.writingAttribute = writingAttribute; } public Writer escaped() { return this.escapedWriter; } public Writer unescaped() { return this; } public String getEncoding() { return this.encoding; } public boolean getEncodingKnown() { return this.encodingKnown; } } groovy-1.8.6/src/main/groovy/xml/FactorySupport.java0000644001501200150120000000432611627206700022106 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import java.security.PrivilegedExceptionAction; import java.security.AccessController; import java.security.PrivilegedActionException; /** * Support class for creating XML Factories */ public class FactorySupport { static Object createFactory(PrivilegedExceptionAction action) throws ParserConfigurationException { Object factory; try { factory = AccessController.doPrivileged(action); } catch (PrivilegedActionException pae) { Exception e = pae.getException(); if (e instanceof ParserConfigurationException) { throw(ParserConfigurationException) e; } else { throw new RuntimeException(e); } } return factory; } public static DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException { return (DocumentBuilderFactory) createFactory(new PrivilegedExceptionAction() { public Object run() throws ParserConfigurationException { return DocumentBuilderFactory.newInstance(); } }); } public static SAXParserFactory createSaxParserFactory() throws ParserConfigurationException { return (SAXParserFactory) createFactory(new PrivilegedExceptionAction() { public Object run() throws ParserConfigurationException { return SAXParserFactory.newInstance(); } }); } } groovy-1.8.6/src/main/groovy/xml/dom/0000755001501200150120000000000011713766062017021 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/xml/dom/package.html0000644001501200150120000000021711627206700021272 0ustar miguelmiguel package groovy.xml.dom.*

    Groovy XML Dom processing classes.

    groovy-1.8.6/src/main/groovy/xml/dom/DOMCategory.java0000644001501200150120000004165311713766062022012 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml.dom; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import groovy.lang.IntRange; import groovy.xml.DOMBuilder; import groovy.xml.QName; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.XmlGroovyMethods; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Category class which adds GPath style operations to Java's DOM classes. * * @author sam * @author paulk */ public class DOMCategory { private static boolean trimWhitespace = true; public static Object get(Element element, String elementName) { return xgetAt(element, elementName); } public static Object get(NodeList nodeList, String elementName) { if (nodeList instanceof Element) { // things like com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl // do implement Element, NodeList and Node. But here we prefer element, // so we force the usage of Element. Without this DOMCategoryTest may fail // in strange ways return xgetAt((Element)nodeList, elementName); } else { return xgetAt(nodeList, elementName); } } public static Object get(NamedNodeMap nodeMap, String elementName) { return xgetAt(nodeMap, elementName); } private static Object xgetAt(Element element, String elementName) { if ("..".equals(elementName)) { return parent(element); } if ("**".equals(elementName)) { return depthFirst(element); } if (elementName.startsWith("@")) { return element.getAttribute(elementName.substring(1)); } return getChildElements(element, elementName); } private static Object xgetAt(NodeList nodeList, String elementName) { List results = new ArrayList(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { addResult(results, get((Element)node, elementName)); } } if (elementName.startsWith("@")) { return results; } return new NodeListsHolder(results); } public static NamedNodeMap attributes(Element element) { return element.getAttributes(); } private static String xgetAt(NamedNodeMap namedNodeMap, String elementName) { Attr a = (Attr) namedNodeMap.getNamedItem(elementName); return a.getValue(); } public static int size(NamedNodeMap namedNodeMap) { return namedNodeMap.getLength(); } public static Node getAt(Node o, int i) { return nodeGetAt(o, i); } public static Node getAt(NodeListsHolder o, int i) { return nodeGetAt(o, i); } public static Node getAt(NodesHolder o, int i) { return nodeGetAt(o, i); } public static NodeList getAt(Node o, IntRange r) { return nodesGetAt(o, r); } public static NodeList getAt(NodeListsHolder o, IntRange r) { return nodesGetAt(o, r); } public static NodeList getAt(NodesHolder o, IntRange r) { return nodesGetAt(o, r); } private static Node nodeGetAt(Object o, int i) { if (o instanceof Element) { Node n = xgetAt((Element)o, i); if (n != null) return n; } if (o instanceof NodeList) { return xgetAt((NodeList)o, i); } return null; } private static NodeList nodesGetAt(Object o, IntRange r) { if (o instanceof Element) { NodeList n = xgetAt((Element)o, r); if (n != null) return n; } if (o instanceof NodeList) { return xgetAt((NodeList)o, r); } return null; } private static Node xgetAt(Element element, int i) { if (hasChildElements(element, "*")) { NodeList nodeList = getChildElements(element, "*"); return xgetAt(nodeList, i); } return null; } private static Node xgetAt(NodeList nodeList, int i) { if (i < 0) { i += nodeList.getLength(); } if (i >= 0 && i < nodeList.getLength()) { return nodeList.item(i); } return null; } private static NodeList xgetAt(Element element, IntRange r) { if (hasChildElements(element, "*")) { NodeList nodeList = getChildElements(element, "*"); return xgetAt(nodeList, r); } return null; } private static NodeList xgetAt(NodeList nodeList, IntRange r) { int from = r.getFromInt(); int to = r.getToInt(); // If the range is of size 1, then we can use the existing // xgetAt() that takes an integer index. if (from == to) return new NodesHolder(Arrays.asList(xgetAt(nodeList, from))); // Normalise negative indices. if (from < 0) from = from + nodeList.getLength(); if (to < 0) to = to + nodeList.getLength(); // After normalisation, 'from' may be greater than 'to'. In that // case, we need to reverse them and make sure the range's 'reverse' // property is correct. // TODO We should probably use DefaultGroovyMethodsSupport.subListBorders(), // but that's protected and unavailable to us. if (from > to) { r = r.isReverse() ? new IntRange(to, from) : new IntRange(from, to); from = r.getFromInt(); to = r.getToInt(); } // Copy the required nodes into a new list. List nodes = new ArrayList(to - from + 1); if (r.isReverse()) { for (int i = to; i >= from; i--) nodes.add(nodeList.item(i)); } else { for (int i = from; i <= to; i++) nodes.add(nodeList.item(i)); } return new NodesHolder(nodes); } public static String name(Element element) { return element.getNodeName(); } public static Node parent(Node node) { return node.getParentNode(); } public static String text(Node node) { if (node.getNodeType() == Node.TEXT_NODE) { return node.getNodeValue(); } if (node.hasChildNodes()) { return text(node.getChildNodes()); } return ""; } public static String text(NodeList nodeList) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < nodeList.getLength(); i++) { sb.append(text(nodeList.item(i))); } return sb.toString(); } public static List list(NodeList self) { List answer = new ArrayList(); Iterator it = XmlGroovyMethods.iterator(self); while (it.hasNext()) { answer.add(it.next()); } return answer; } public static NodeList depthFirst(Element self) { List result = new ArrayList(); result.add(createNodeList(self)); result.add(self.getElementsByTagName("*")); return new NodeListsHolder(result); } public static void setValue(Element self, String value) { Node firstChild = self.getFirstChild(); if (firstChild == null) { firstChild = self.getOwnerDocument().createTextNode(value); self.appendChild(firstChild); } firstChild.setNodeValue(value); } public static void putAt(Element self, String property, Object value) { if (property.startsWith("@")) { String attributeName = property.substring(1); Document doc = self.getOwnerDocument(); Attr newAttr = doc.createAttribute(attributeName); newAttr.setValue(value.toString()); self.setAttributeNode(newAttr); return; } InvokerHelper.setProperty(self, property, value); } public static Element appendNode(Element self, Object name) { return appendNode(self, name, (String)null); } public static Element appendNode(Element self, Object name, Map attributes) { return appendNode(self, name, attributes, null); } public static Element appendNode(Element self, Object name, String value) { Document doc = self.getOwnerDocument(); Element newChild; if (name instanceof QName) { QName qn = (QName) name; newChild = doc.createElementNS(qn.getNamespaceURI(), qn.getQualifiedName()); } else { newChild = doc.createElement(name.toString()); } if (value != null) { Text text = doc.createTextNode(value); newChild.appendChild(text); } self.appendChild(newChild); return newChild; } public static Element appendNode(Element self, Object name, Map attributes, String value) { Element result = appendNode(self, name, value); for (Object o : attributes.entrySet()) { Map.Entry e = (Map.Entry) o; putAt(result, "@" + e.getKey().toString(), e.getValue()); } return result; } public static Node replaceNode(NodesHolder self, Closure c) { if (self.getLength() <= 0 || self.getLength() > 1) { throw new GroovyRuntimeException("replaceNode() can only be used to replace a single element."); } return replaceNode(self.item(0), c); } // TODO return replaced node rather than last appended? public static Node replaceNode(Node self, Closure c) { if (self.getParentNode() instanceof Document) { throw new UnsupportedOperationException("Replacing the root node is not supported"); } Node result = appendNodes(self, c); self.getParentNode().removeChild(self); return result; // return self; } public static void plus(Element self, Closure c) { if (self.getParentNode() instanceof Document) { throw new UnsupportedOperationException("Adding sibling nodes to the root node is not supported"); } appendNodes(self, c); } private static Node appendNodes(Node self, Closure c) { Node parent = self.getParentNode(); Node beforeNode = self.getNextSibling(); DOMBuilder b = new DOMBuilder(self.getOwnerDocument()); Element newNodes = (Element) b.invokeMethod("rootNode", c); Iterator iter = XmlGroovyMethods.iterator(children(newNodes)); Node lastAppended = null; while (iter.hasNext()) { lastAppended = parent.insertBefore(iter.next(), beforeNode); } return lastAppended; } public static void plus(NodeList self, Closure c) { for (int i = 0; i < self.getLength(); i++) { plus((Element) self.item(i), c); } } private static NodeList createNodeList(Element self) { List first = new ArrayList(); first.add(self); return new NodesHolder(first); } public static NodeList breadthFirst(Element self) { List result = new ArrayList(); NodeList thisLevel = createNodeList(self); while (thisLevel.getLength() > 0) { result.add(thisLevel); thisLevel = getNextLevel(thisLevel); } return new NodeListsHolder(result); } private static NodeList getNextLevel(NodeList thisLevel) { List result = new ArrayList(); for (int i = 0; i < thisLevel.getLength(); i++) { Node n = thisLevel.item(i); if (n instanceof Element) { result.add(getChildElements((Element) n, "*")); } } return new NodeListsHolder(result); } public static NodeList children(Element self) { return getChildElements(self, "*"); } private static boolean hasChildElements(Element self, String elementName) { return getChildElements(self, elementName).getLength() > 0; } private static NodeList getChildElements(Element self, String elementName) { List result = new ArrayList(); NodeList nodeList = self.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if ("*".equals(elementName) || child.getTagName().equals(elementName)) { result.add(child); } } else if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue(); if (trimWhitespace) { value = value.trim(); } if ("*".equals(elementName) && value.length() > 0) { node.setNodeValue(value); result.add(node); } } } return new NodesHolder(result); } public static String toString(Object o) { if (o instanceof Node) { if (((Node) o).getNodeType() == Node.TEXT_NODE) { return ((Node) o).getNodeValue(); } } if (o instanceof NodeList) { return toString((NodeList) o); } return o.toString(); } public static Object xpath(Node self, String expression, javax.xml.namespace.QName returnType) { final XPath xpath = XPathFactory.newInstance().newXPath(); try { return xpath.evaluate(expression, self, returnType); } catch (XPathExpressionException e) { throw new GroovyRuntimeException(e); } } public static String xpath(Node self, String expression) { final XPath xpath = XPathFactory.newInstance().newXPath(); try { return xpath.evaluate(expression, self); } catch (XPathExpressionException e) { throw new GroovyRuntimeException(e); } } private static String toString(NodeList self) { StringBuilder sb = new StringBuilder(); sb.append("["); Iterator it = XmlGroovyMethods.iterator(self); while (it.hasNext()) { if (sb.length() > 1) sb.append(", "); sb.append(it.next().toString()); } sb.append("]"); return sb.toString(); } public static int size(NodeList self) { return self.getLength(); } public static boolean isEmpty(NodeList self) { return size(self) == 0; } @SuppressWarnings("unchecked") private static void addResult(List results, Object result) { if (result != null) { if (result instanceof Collection) { results.addAll((Collection) result); } else { results.add(result); } } } private static final class NodeListsHolder implements NodeList { private List nodeLists; private NodeListsHolder(List nodeLists) { this.nodeLists = nodeLists; } public int getLength() { int length = 0; for (NodeList nl : nodeLists) { length += nl.getLength(); } return length; } public Node item(int index) { int relativeIndex = index; for (NodeList nl : nodeLists) { if (relativeIndex < nl.getLength()) { return nl.item(relativeIndex); } relativeIndex -= nl.getLength(); } return null; } public String toString() { return DOMCategory.toString(this); } } private static final class NodesHolder implements NodeList { private List nodes; private NodesHolder(List nodes) { this.nodes = nodes; } public int getLength() { return nodes.size(); } public Node item(int index) { if (index < 0 || index >= getLength()) { return null; } return nodes.get(index); } } }groovy-1.8.6/src/main/groovy/xml/package.html0000644001501200150120000000027211627206700020514 0ustar miguelmiguel package groovy.xml.*

    Groovy markup builder classes for working with SAX and W3C DOM and Groovy markup.

    groovy-1.8.6/src/main/groovy/xml/StaxBuilder.groovy0000644001501200150120000000553411627206700021736 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml /** * A Groovy builder that works with Stax processors. * Using Java 6, typical usage is as follows: *
     * def factory = XMLOutputFactory.newInstance()
     * def writer = new StringWriter()
     * def builder = new StaxBuilder(factory.createXMLStreamWriter(writer))
     * builder.root1(a:5, b:7) {
     *     elem1('hello1')
     *     elem2('hello2')
     *     elem3(x:7)
     * }
     * assert writer == """hello1hello2"""
     * 
    * Or an external library such as Jettison can be used as follows: *
     * @Grab('org.codehaus.jettison:jettison:1.2')
     * import org.codehaus.jettison.mapped.*
     * import javax.xml.stream.XMLStreamException
     *
     * def conv = new MappedNamespaceConvention()
     * def writer = new StringWriter()
     * def mappedWriter = new MappedXMLStreamWriter(conv, writer)
     * def builder = new groovy.xml.StaxBuilder(mappedWriter)
     * builder.root1(a:5, b:7) {
     *     elem1('hello1')
     *     elem2('hello2')
     *     elem3(x:7)
     * }
     * assert writer.toString() == '''{"root1":{"@a":"5","@b":"7","elem1":"hello1","elem2":"hello2","elem3":{"@x":"7"}}}'''
     * 
    * * @author Dejan Bosanac * @author Paul King */ public class StaxBuilder extends BuilderSupport { def writer public StaxBuilder(xmlStreamWriter) { writer = xmlStreamWriter writer.writeStartDocument() } protected createNode(name) { createNode(name, null, null) } protected createNode(name, value) { createNode(name, null, value) } protected createNode(name, Map attributes) { createNode(name, attributes, null) } protected createNode(name, Map attributes, value) { writer.writeStartElement(name.toString()) if (attributes) { attributes.each { k, v -> writer.writeAttribute(k.toString(), v.toString()) } } if (value) { writer.writeCharacters(value.toString()) } name } protected void nodeCompleted(parent, node) { writer.writeEndElement() if (!parent) { writer.writeEndDocument() writer.flush() } } protected void setParent(parent, child) { } } groovy-1.8.6/src/main/groovy/xml/Namespace.java0000644001501200150120000000366011627206700020776 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; /** * A simple helper class which acts as a factory of {@link QName} instances. * * @version $Revision$ */ public class Namespace { private String uri; private String prefix; public Namespace() { } public Namespace(String uri) { this.uri = uri.trim(); } public Namespace(String uri, String prefix) { this.uri = uri.trim(); this.prefix = prefix.trim(); } /** * Returns the QName for the given localName. * * @param localName * the local name within this */ public QName get(String localName) { if (uri != null && uri.length() > 0) { if (prefix != null) { return new QName(uri, localName, prefix); } else { return new QName(uri, localName); } } else { return new QName(localName); } } /** * Returns the prefix mapped to this namespace * * @return the prefix assigned to this namespace or null if no namespace is * mapped. */ public String getPrefix() { return prefix; } /** * Returns the URI of this namespace * * @return the URI of this namespace */ public String getUri() { return uri; } } groovy-1.8.6/src/main/groovy/xml/Entity.groovy0000644001501200150120000003666611627206700020776 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml class Entity implements Buildable { /* * XML-compatible ISO Latin 1 Character Entity Set for XHTML */ public static final Entity nbsp = new Entity("nbsp") // no-break space = non-breaking space, U+00A0 ISOnum public static final Entity iexcl = new Entity("iexcl") // inverted exclamation mark, U+00A1 ISOnum public static final Entity cent = new Entity("cent") // cent sign, U+00A2 ISOnum public static final Entity pound = new Entity("pound") // pound sign, U+00A3 ISOnum public static final Entity curren = new Entity("curren") // currency sign, U+00A4 ISOnum public static final Entity yen = new Entity("yen") // yen sign = yuan sign, U+00A5 ISOnum public static final Entity brvbar = new Entity("brvbar") // broken bar = broken vertical bar, U+00A6 ISOnum public static final Entity sect = new Entity("sect") // section sign, U+00A7 ISOnum public static final Entity uml = new Entity("uml") // diaeresis = spacing diaeresis, U+00A8 ISOdia public static final Entity copy = new Entity("copy") // copyright sign, U+00A9 ISOnum public static final Entity ordf = new Entity("ordf") // feminine ordinal indicator, U+00AA ISOnum public static final Entity laquo = new Entity("laquo") // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum public static final Entity not = new Entity("not") // not sign, U+00AC ISOnum public static final Entity shy = new Entity("shy") // soft hyphen = discretionary hyphen, U+00AD ISOnum public static final Entity reg = new Entity("reg") // registered sign = registered trade mark sign, U+00AE ISOnum public static final Entity macr = new Entity("macr") // macron = spacing macron = overline = APL overbar, U+00AF ISOdia public static final Entity deg = new Entity("deg") // degree sign, U+00B0 ISOnum public static final Entity plusmn = new Entity("plusmn") // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum public static final Entity sup2 = new Entity("sup2") // superscript two = superscript digit two = squared, U+00B2 ISOnum public static final Entity sup3 = new Entity("sup3") // superscript three = superscript digit three = cubed, U+00B3 ISOnum public static final Entity acute = new Entity("acute") // acute accent = spacing acute, U+00B4 ISOdia public static final Entity micro = new Entity("micro") // micro sign, U+00B5 ISOnum public static final Entity para = new Entity("para") // pilcrow sign = paragraph sign, U+00B6 ISOnum public static final Entity middot = new Entity("middot") // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum public static final Entity cedil = new Entity("cedil") // cedilla = spacing cedilla, U+00B8 ISOdia public static final Entity sup1 = new Entity("sup1") // superscript one = superscript digit one, U+00B9 ISOnum public static final Entity ordm = new Entity("ordm") // masculine ordinal indicator, U+00BA ISOnum public static final Entity raquo = new Entity("raquo") // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum public static final Entity frac14 = new Entity("frac14") // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum public static final Entity frac12 = new Entity("frac12") // vulgar fraction one half = fraction one half, U+00BD ISOnum public static final Entity frac34 = new Entity("frac34") // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum public static final Entity iquest = new Entity("iquest") // inverted question mark = turned question mark, U+00BF ISOnum public static final Entity Agrave = new Entity("Agrave") // latin capital A with grave = latin capital A grave, U+00C0 ISOlat1 public static final Entity Aacute = new Entity("Aacute") // latin capital A with acute, U+00C1 ISOlat1 public static final Entity Acirc = new Entity("Acirc") // latin capital A with circumflex, U+00C2 ISOlat1 public static final Entity Atilde = new Entity("Atilde") // latin capital A with tilde, U+00C3 ISOlat1 public static final Entity Auml = new Entity("Auml") // latin capital A with diaeresis, U+00C4 ISOlat1 public static final Entity Aring = new Entity("Aring") // latin capital A with ring above = latin capital A ring, U+00C5 ISOlat1 public static final Entity AElig = new Entity("AElig") // latin capital AE = latin capital ligature AE, U+00C6 ISOlat1 public static final Entity Ccedil = new Entity("Ccedil") // latin capital C with cedilla, U+00C7 ISOlat1 public static final Entity Egrave = new Entity("Egrave") // latin capital E with grave, U+00C8 ISOlat1 public static final Entity Eacute = new Entity("Eacute") // latin capital E with acute, U+00C9 ISOlat1 public static final Entity Ecirc = new Entity("Ecirc") // latin capital E with circumflex, U+00CA ISOlat1 public static final Entity Euml = new Entity("Euml") // latin capital E with diaeresis, U+00CB ISOlat1 public static final Entity Igrave = new Entity("Igrave") // latin capital I with grave, U+00CC ISOlat1 public static final Entity Iacute = new Entity("Iacute") // latin capital I with acute, U+00CD ISOlat1 public static final Entity Icirc = new Entity("Icirc") // latin capital I with circumflex, U+00CE ISOlat1 public static final Entity Iuml = new Entity("Iuml") // latin capital I with diaeresis, U+00CF ISOlat1 public static final Entity ETH = new Entity("ETH") // latin capital ETH, U+00D0 ISOlat1 public static final Entity Ntilde = new Entity("Ntilde") // latin capital N with tilde, U+00D1 ISOlat1 public static final Entity Ograve = new Entity("Ograve") // latin capital O with grave, U+00D2 ISOlat1 public static final Entity Oacute = new Entity("Oacute") // latin capital O with acute, U+00D3 ISOlat1 public static final Entity Ocirc = new Entity("Ocirc") // latin capital O with circumflex, U+00D4 ISOlat1 public static final Entity Otilde = new Entity("Otilde") // latin capital O with tilde, U+00D5 ISOlat1 public static final Entity Ouml = new Entity("Ouml") // latin capital O with diaeresis, U+00D6 ISOlat1 public static final Entity times = new Entity("times") // multiplication sign, U+00D7 ISOnum public static final Entity Oslash = new Entity("Oslash") // latin capital O with stroke = latin capital O slash, U+00D8 ISOlat1 public static final Entity Ugrave = new Entity("Ugrave") // latin capital U with grave, U+00D9 ISOlat1 public static final Entity Uacute = new Entity("Uacute") // latin capital U with acute, U+00DA ISOlat1 public static final Entity Ucirc = new Entity("Ucirc") // latin capital U with circumflex, U+00DB ISOlat1 public static final Entity Uuml = new Entity("Uuml") // latin capital U with diaeresis, U+00DC ISOlat1 public static final Entity Yacute = new Entity("Yacute") // latin capital Y with acute, U+00DD ISOlat1 public static final Entity THORN = new Entity("THORN") // latin capital THORN, U+00DE ISOlat1 public static final Entity szlig = new Entity("szlig") // latin small sharp s = ess-zed, U+00DF ISOlat1 public static final Entity agrave = new Entity("agrave") // latin small a with grave = latin small a grave, U+00E0 ISOlat1 public static final Entity aacute = new Entity("aacute") // latin small a with acute, U+00E1 ISOlat1 public static final Entity acirc = new Entity("acirc") // latin small a with circumflex, U+00E2 ISOlat1 public static final Entity atilde = new Entity("atilde") // latin small a with tilde, U+00E3 ISOlat1 public static final Entity auml = new Entity("auml") // latin small a with diaeresis, U+00E4 ISOlat1 public static final Entity aring = new Entity("aring") // latin small a with ring above = latin small a ring, U+00E5 ISOlat1 public static final Entity aelig = new Entity("aelig") // latin small ae = latin small ligature ae, U+00E6 ISOlat1 public static final Entity ccedil = new Entity("ccedil") // latin small c with cedilla, U+00E7 ISOlat1 public static final Entity egrave = new Entity("egrave") // latin small e with grave, U+00E8 ISOlat1 public static final Entity eacute = new Entity("eacute") // latin small e with acute, U+00E9 ISOlat1 public static final Entity ecirc = new Entity("ecirc") // latin small e with circumflex, U+00EA ISOlat1 public static final Entity euml = new Entity("euml") // latin small e with diaeresis, U+00EB ISOlat1 public static final Entity igrave = new Entity("igrave") // latin small i with grave, U+00EC ISOlat1 public static final Entity iacute = new Entity("iacute") // latin small i with acute, U+00ED ISOlat1 public static final Entity icirc = new Entity("icirc") // latin small i with circumflex, U+00EE ISOlat1 public static final Entity iuml = new Entity("iuml") // latin small i with diaeresis, U+00EF ISOlat1 public static final Entity eth = new Entity("eth") // latin small eth, U+00F0 ISOlat1 public static final Entity ntilde = new Entity("ntilde") // latin small n with tilde, U+00F1 ISOlat1 public static final Entity ograve = new Entity("ograve") // latin small o with grave, U+00F2 ISOlat1 public static final Entity oacute = new Entity("oacute") // latin small o with acute, U+00F3 ISOlat1 public static final Entity ocirc = new Entity("ocirc") // latin small o with circumflex, U+00F4 ISOlat1 public static final Entity otilde = new Entity("otilde") // latin small o with tilde, U+00F5 ISOlat1 public static final Entity ouml = new Entity("ouml") // latin small o with diaeresis, U+00F6 ISOlat1 public static final Entity divide = new Entity("divide") // division sign, U+00F7 ISOnum public static final Entity oslash = new Entity("oslash") // latin small o with stroke, = latin small o slash, U+00F8 ISOlat1 public static final Entity ugrave = new Entity("ugrave") // latin small u with grave, U+00F9 ISOlat1 public static final Entity uacute = new Entity("uacute") // latin small u with acute, U+00FA ISOlat1 public static final Entity ucirc = new Entity("ucirc") // latin small u with circumflex, U+00FB ISOlat1 public static final Entity uuml = new Entity("uuml") // latin small u with diaeresis, U+00FC ISOlat1 public static final Entity yacute = new Entity("yacute") // latin small y with acute, U+00FD ISOlat1 public static final Entity thorn = new Entity("thorn") // latin small thorn with, U+00FE ISOlat1 public static final Entity yuml = new Entity("yuml") // latin small y with diaeresis, U+00FF ISOlat1 /* * XML-compatible ISO Special Character Entity Set for XHTML */ // C0 Controls and Basic Latin public static final Entity lt = new Entity("lt") //less-than sign, U+003C ISOnum public static final Entity gt = new Entity("gt") //greater-than sign, U+003E ISOnum public static final Entity amp = new Entity("amp") //ampersand, U+0026 ISOnum public static final Entity apos = new Entity("apos") //The Apostrophe (Apostrophe Quote, APL Quote), U+0027 ISOnum public static final Entity quot = new Entity("quot") //quotation mark (Quote Double), U+0022 ISOnum // Latin Extended-A public static final Entity OElig = new Entity("OElig") //latin capital ligature OE, U+0152 ISOlat2 public static final Entity oelig = new Entity("oelig") //latin small ligature oe, U+0153 ISOlat2 // ligature is a misnomer, this is a separate character in some languages public static final Entity Scaron = new Entity("Scaron") //latin capital letter S with caron, U+0160 ISOlat2 public static final Entity scaron = new Entity("scaron") //latin small letter s with caron, U+0161 ISOlat2 public static final Entity Yuml = new Entity("Yuml") //latin capital letter Y with diaeresis, U+0178 ISOlat2 // Spacing Modifier Letters public static final Entity circ = new Entity("circ") //modifier letter circumflex accent, U+02C6 ISOpub public static final Entity tilde = new Entity("tilde") //small tilde, U+02DC ISOdia // General Punctuation public static final Entity ensp = new Entity("ensp") //en space, U+2002 ISOpub public static final Entity emsp = new Entity("emsp") //em space, U+2003 ISOpub public static final Entity thinsp = new Entity("thinsp") //thin space, U+2009 ISOpub public static final Entity zwnj = new Entity("zwnj") //zero width non-joiner, U+200C NEW RFC 2070 public static final Entity zwj = new Entity("zwj") //zero width joiner, U+200D NEW RFC 2070 public static final Entity lrm = new Entity("lrm") //left-to-right mark, U+200E NEW RFC 2070 public static final Entity rlm = new Entity("rlm") //right-to-left mark, U+200F NEW RFC 2070 public static final Entity ndash = new Entity("ndash") //en dash, U+2013 ISOpub public static final Entity mdash = new Entity("mdash") //em dash, U+2014 ISOpub public static final Entity lsquo = new Entity("lsquo") //left single quotation mark, U+2018 ISOnum public static final Entity rsquo = new Entity("rsquo") //right single quotation mark, U+2019 ISOnum public static final Entity sbquo = new Entity("sbquo") //single low-9 quotation mark, U+201A NEW public static final Entity ldquo = new Entity("ldquo") //left double quotation mark, U+201C ISOnum public static final Entity rdquo = new Entity("rdquo") //right double quotation mark, U+201D ISOnum public static final Entity bdquo = new Entity("bdquo") //double low-9 quotation mark, U+201E NEW public static final Entity dagger = new Entity("dagger") //dagger, U+2020 ISOpub public static final Entity Dagger = new Entity("Dagger") //double dagger, U+2021 ISOpub public static final Entity permil = new Entity("permil") //per mille sign, U+2030 ISOtech // lsaquo is proposed but not yet ISO standardized public static final Entity lsaquo = new Entity("lsaquo") //single left-pointing angle quotation mark, U+2039 ISO proposed // rsaquo is proposed but not yet ISO standardized public static final Entity rsaquo = new Entity("rsaquo") //single right-pointing angle quotation mark, U+203A ISO proposed public static final Entity euro = new Entity("euro") //euro sign, U+20AC NEW private final entity; Entity(String name) { this.entity = "&$name;" } Entity(int name) { this.entity = "&#$name;" } void build(GroovyObject builder) { builder.unescaped << entity } } groovy-1.8.6/src/main/groovy/xml/StreamingMarkupBuilder.groovy0000644001501200150120000002153011707612044024123 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml import groovy.xml.streamingmarkupsupport.AbstractStreamingBuilder import groovy.xml.streamingmarkupsupport.StreamingMarkupWriter import groovy.xml.streamingmarkupsupport.BaseMarkupBuilder /** *

    A builder class for creating XML markup. This implementation uses a * {@link StreamingMarkupWriter} to handle output.

    * *

    Example:

    *
    System.out << new StreamingMarkupBuilder().bind {
     *   root {
     *     a( a1:'one' ) {
     *       b { mkp.yield( '3 < 5' ) }
     *       c( a2:'two', 'blah' )
     *     }
     *   }
     * }
    * Will output the following String, without newlines or indentation: *
    <root>
     *   <a a1='one'>
     *     <b>3 &lt; 5</b>
     *     <c a2='two'>blah</c>
     *   </a>
     * </root>
    * Notes: *
      *
    • that mkp is a special namespace used to escape * away from the normal building mode of the builder and get access * to helper markup methods 'yield', 'pi', 'comment', 'out', * 'namespaces', 'xmlDeclaration' and 'yieldUnescaped'. *
    • *
    • Note that tab, newline and carriage return characters are escaped within attributes, i.e. will become , and respectively
    • *
    */ class StreamingMarkupBuilder extends AbstractStreamingBuilder { boolean useDoubleQuotes = false boolean expandEmptyElements = false def getQt() { useDoubleQuotes ? '"' : "'" } def pendingStack = [] /** * Invoked by calling mkp.comment */ def commentClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> out.unescaped() << "" } /** * Invoked by calling mkp.pi */ def piClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> attrs.each {target, instruction -> out.unescaped() << " if (value.toString().contains('\'') || (useDoubleQuotes && !value.toString().contains('"'))) { out.unescaped() << " $name=\"$value\"" } else { out.unescaped() << " $name='$value'" } } } else { out.unescaped() << "$target $instruction" } out.unescaped() << "?>" } } /** * Invoked by calling mkp.xmlDeclaration */ def declarationClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> out.unescaped() << '\n' } /** * Invoked by calling mkp.yield. Used to render text to the * output stream. Any XML reserved characters will be escaped to ensure * well-formedness. */ def noopClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> body.each { if (it instanceof Closure) { def body1 = it.clone() body1.delegate = doc body1(doc) } else if (it instanceof Buildable) { it.build(doc) } else { out.escaped() << it } } } /** * Invoked by calling mkp.yieldUnescaped. Used to render * literal text or markup to the output stream. No escaping is done on the * output. */ def unescapedClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> out.unescaped() << body } def tagClosure = {tag, doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, out -> if (prefix != "") { if (!(namespaces.containsKey(prefix) || pendingNamespaces.containsKey(prefix))) { throw new GroovyRuntimeException("Namespace prefix: ${prefix} is not bound to a URI") } if (prefix != ":") tag = prefix + ":" + tag } out = out.unescaped() << "<${tag}" attrs.each {key, value -> if (key.contains('$')) { def parts = key.tokenize('$') if (namespaces.containsKey(parts[0]) || pendingNamespaces.containsKey(parts[0])) { key = parts[0] + ":" + parts[1] } else { throw new GroovyRuntimeException("bad attribute namespace tag: ${parts[0]} in ${key}") } } out << " ${key}=" + qt out.writingAttribute = true "${value}".build(doc) out.writingAttribute = false out << qt } def hiddenNamespaces = [:] pendingNamespaces.each {key, value -> hiddenNamespaces[key] = namespaces[key] namespaces[key] = value out << ((key == ":") ? " xmlns=" + qt : " xmlns:${key}=" + qt) out.writingAttribute = true "${value}".build(doc) out.writingAttribute = false out << qt } if (body == null && !expandEmptyElements) { out << "/>" } else { out << ">" pendingStack.add pendingNamespaces.clone() pendingNamespaces.clear() body.each { if (it instanceof Closure) { def body1 = it.clone() body1.delegate = doc body1(doc) } else if (it instanceof Buildable) { it.build(doc) } else { out.escaped() << it } } pendingNamespaces.clear() pendingNamespaces.putAll pendingStack.pop() out << "" } hiddenNamespaces.each {key, value -> if (value == null) { namespaces.remove key } else { namespaces[key] = value } } } def builder = null StreamingMarkupBuilder() { specialTags.putAll( ['yield': noopClosure, 'yieldUnescaped': unescapedClosure, 'xmlDeclaration': declarationClosure, 'comment': commentClosure, 'pi': piClosure]) def nsSpecificTags = [':': [tagClosure, tagClosure, [:]], // the default namespace 'http://www.w3.org/XML/1998/namespace': [tagClosure, tagClosure, [:]], 'http://www.codehaus.org/Groovy/markup/keywords': [badTagClosure, tagClosure, specialTags]] this.builder = new BaseMarkupBuilder(nsSpecificTags) } def encoding = null /** *

    Returns a {@link Writable} object, which may be used to render * the markup directly to a String, or send the output to a stream.

    *

    Examples:

    *
         * // get the markup as a string:
         * new StreamingMarkupBuilder().bind { div { out << "hello world" } }.toString()
         * 
         * // send the output directly to a file:
         * new StreamingMarkupBuilder().bind { div { out << "hello world" } } \
         *      .writeTo( new File('myFile.xml').newWriter() )
         * 
    * @return a {@link Writable} to render the markup */ public bind(closure) { def boundClosure = this.builder.bind(closure); def enc = encoding; // take a snapshot of the encoding when the closure is bound to the builder {out -> out = new StreamingMarkupWriter(out, enc, useDoubleQuotes) boundClosure.trigger = out out.flush() }.asWritable() } /** * Convenience method for binding a single node. * The call bindNode(node) is equivalent to bind{ out << node }. *

    Returns a {@link Writable} object, which may be used to render * the markup directly to a String, or send the output to a stream.

    * @see #bind(Closure) * @return a {@link Writable} to render the markup */ public bindNode(node) { bind { out << node } } } groovy-1.8.6/src/main/groovy/xml/StreamingSAXBuilder.groovy0000644001501200150120000001416411627206700023323 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml import groovy.xml.streamingmarkupsupport.AbstractStreamingBuilder import groovy.xml.streamingmarkupsupport.BaseMarkupBuilder import org.xml.sax.helpers.AttributesImpl import org.xml.sax.ext.LexicalHandler class StreamingSAXBuilder extends AbstractStreamingBuilder { def pendingStack = [] def commentClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, contentHandler -> if (contentHandler instanceof LexicalHandler) { contentHandler.comment(body.toCharArray(), 0, body.size()) } } def piClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, contentHandler -> attrs.each {target, instruction -> if (instruction instanceof Map) { def buf = new StringBuffer() instruction.each {name, value -> if (value.toString().contains('"')) buf.append(" $name='$value'") else buf.append(" $name=\"$value\"") } contentHandler.processingInstruction(target, buf.toString()) } else { contentHandler.processingInstruction(target, instruction) } } } def noopClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, contentHandler -> if (body != null) { processBody(body, doc, contentHandler) } } def tagClosure = {tag, doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, contentHandler -> def attributes = new AttributesImpl() attrs.each {key, value -> addAttributes(attributes, key, value, namespaces) } def hiddenNamespaces = [:] pendingNamespaces.each {key, value -> def k = (key == ':' ? '' : key) hiddenNamespaces[k] = namespaces[key] namespaces[k] = value attributes.addAttribute("http://www.w3.org/2000/xmlns/", k, "xmlns${k == '' ? '' : ":$k"}", "CDATA", "$value") contentHandler.startPrefixMapping(k, value) } // set up the tag info def uri = "" def qualifiedName = tag if (prefix != "") { if (namespaces.containsKey(prefix)) { uri = namespaces[prefix] } else if (pendingNamespaces.containsKey(prefix)) { uri = pendingNamespaces[prefix] } else { throw new GroovyRuntimeException("Namespace prefix: ${prefix} is not bound to a URI") } if (prefix != ":") { qualifiedName = prefix + ":" + tag } } contentHandler.startElement(uri, tag, qualifiedName, attributes) if (body != null) { pendingStack.add pendingNamespaces.clone() pendingNamespaces.clear() processBody(body, doc, contentHandler) pendingNamespaces.clear() pendingNamespaces.putAll pendingStack.pop() } contentHandler.endElement(uri, tag, qualifiedName) hiddenNamespaces.each {key, value -> contentHandler.endPrefixMapping(key) if (value == null) namespaces.remove key else namespaces[key] = value } } private addAttributes(AttributesImpl attributes, key, value, namespaces) { if (key.contains('$')) { def parts = key.tokenize('$') if (namespaces.containsKey(parts[0])) { def namespaceUri = namespaces[parts[0]] attributes.addAttribute(namespaceUri, parts[1], "${parts[0]}:${parts[1]}", "CDATA", "$value") } else { throw new GroovyRuntimeException("bad attribute namespace tag in ${key}") } } else { attributes.addAttribute("", key, key, "CDATA", "$value") } } private processBody(body, doc, contentHandler) { if (body instanceof Closure) { def body1 = body.clone() body1.delegate = doc body1(doc) } else if (body instanceof Buildable) { body.build(doc) } else { body.each { processBodyPart(it, doc, contentHandler) } } } private processBodyPart(part, doc, contentHandler) { if (part instanceof Closure) { def body1 = part.clone() body1.delegate = doc body1(doc) } else if (part instanceof Buildable) { part.build(doc) } else { def chars = part.toCharArray() contentHandler.characters(chars, 0, chars.size()) } } def builder = null StreamingSAXBuilder() { specialTags.putAll(['yield': noopClosure, 'yieldUnescaped': noopClosure, 'comment': commentClosure, 'pi': piClosure]) def nsSpecificTags = [':': [tagClosure, tagClosure, [:]], // the default namespace 'http://www.w3.org/XML/1998/namespace': [tagClosure, tagClosure, [:]], 'http://www.codehaus.org/Groovy/markup/keywords': [badTagClosure, tagClosure, specialTags]] this.builder = new BaseMarkupBuilder(nsSpecificTags) } public bind(closure) { def boundClosure = this.builder.bind(closure) return {contentHandler -> contentHandler.startDocument() boundClosure.trigger = contentHandler contentHandler.endDocument() } } } groovy-1.8.6/src/main/groovy/xml/NamespaceBuilderSupport.java0000644001501200150120000000753711627206700023711 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.util.BuilderSupport; import groovy.util.NodeBuilder; import org.codehaus.groovy.runtime.InvokerHelper; import java.util.HashMap; import java.util.Map; /** * A helper class for creating namespaced GroovyMarkup * * @author James Strachan * @author Paul King * @author Denver Dino */ public class NamespaceBuilderSupport extends BuilderSupport { private boolean autoPrefix; private Map nsMap = new HashMap(); private BuilderSupport builder; public NamespaceBuilderSupport(BuilderSupport builder) { super(builder); this.builder = builder; } public NamespaceBuilderSupport(BuilderSupport builder, String uri) { this(builder, uri, ""); } public NamespaceBuilderSupport(BuilderSupport builder, String uri, String prefix) { this(builder, uri, prefix, true); } public NamespaceBuilderSupport(BuilderSupport builder, String uri, String prefix, boolean autoPrefix) { this(builder); nsMap.put(prefix, uri); this.autoPrefix = autoPrefix; } public NamespaceBuilderSupport(BuilderSupport builder, Map nsMap) { this(builder); this.nsMap = nsMap; } public NamespaceBuilderSupport namespace(String namespaceURI) { nsMap.put("", namespaceURI); return this; } public NamespaceBuilderSupport namespace(String namespaceURI, String prefix) { nsMap.put(prefix, namespaceURI); return this; } public NamespaceBuilderSupport declareNamespace(Map nsMap) { this.nsMap = nsMap; return this; } @Override protected Object getCurrent() { // TODO a better way to do this? if (builder instanceof NodeBuilder) return InvokerHelper.invokeMethod(builder, "getCurrent", null); else return super.getCurrent(); } @Override protected void setCurrent(Object current) { // TODO a better way to do this? if (builder instanceof NodeBuilder) InvokerHelper.invokeMethod(builder, "setCurrent", current); else super.setCurrent(current); } @Override protected void setParent(Object parent, Object child) { } @Override protected Object getName(String methodName) { String prefix = autoPrefix ? nsMap.keySet().iterator().next() : ""; String localPart = methodName; int idx = methodName.indexOf(':'); if (idx > 0 ) { prefix = methodName.substring(0, idx); localPart = methodName.substring(idx + 1); } String namespaceURI = nsMap.get(prefix); if (namespaceURI == null) { namespaceURI = ""; prefix = ""; } return new QName(namespaceURI, localPart, prefix); } @Override protected Object createNode(Object name) { return name; } @Override protected Object createNode(Object name, Object value) { return name; } @Override protected Object createNode(Object name, Map attributes) { return name; } @Override protected Object createNode(Object name, Map attributes, Object value) { return name; } } groovy-1.8.6/src/main/groovy/xml/MarkupBuilderHelper.java0000644001501200150120000000761511627206700023014 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import java.util.HashMap; import java.util.Map; /** * A helper class for MarkupBuilder. * * @author Paul King */ public class MarkupBuilderHelper { private MarkupBuilder builder; /** * @param builder the builder to delegate to */ public MarkupBuilderHelper(MarkupBuilder builder) { this.builder = builder; } /** * Prints data in the body of the current tag, escaping XML entities. * For example: mkp.yield('5 < 7') * * @param value an Object whose toString() representation is to be printed */ public void yield(Object value) { yield(value.toString()); } /** * Prints data in the body of the current tag, escaping XML entities. * For example: mkp.yield('5 < 7') * * @param value text to print */ public void yield(String value) { builder.yield(value, true); } /** * Print data in the body of the current tag. Does not escape XML entities. * For example: mkp.yieldUnescaped('I am <i>happy</i>!'). * * @param value an Object whose toString() representation is to be printed */ public void yieldUnescaped(Object value) { yieldUnescaped(value.toString()); } /** * Print data in the body of the current tag. Does not escape XML entities. * For example: mkp.yieldUnescaped('I am <i>happy</i>!'). * * @param value the text or markup to print. */ public void yieldUnescaped(String value) { builder.yield(value, false); } /** * Produce a comment in the output. *

    * mkp.comment 'string' is equivalent to * mkp.yieldUnescaped '<!-- string -->'. * To create an element with the name 'comment', you need * to supply empty attributes, e.g.: *

         * comment('hello1')
         * 
    * or *
         * mkp.comment('hello1')
         * 
    * will produce: *
         * <!-- hello1 -->
         * 
    * while: *
         * comment('hello2', [:])
         * 
    * will produce: *
         * <comment>hello2</comment>
         * 
    * * @param value the text within the comment. */ public void comment(String value) { yieldUnescaped(""); } /** * Produce an XML declaration in the output. * For example: *
         * mkp.xmlDeclaration(version:'1.0')
         * 
    * * @param args the attributes for the declaration */ public void xmlDeclaration(Map args) { Map> map = new HashMap>(); map.put("xml", args); pi(map); } /** * Produce an XML processing instruction in the output. * For example: *
         * mkp.pi("xml-stylesheet":[href:"mystyle.css", type:"text/css"])
         * 
    * * @param args a map with a single entry whose key is the name of the * processing instruction and whose value is the attributes * for the processing instruction. */ public void pi(Map> args) { builder.pi(args); } }groovy-1.8.6/src/main/groovy/xml/NamespaceBuilder.java0000644001501200150120000000401311627206700022276 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.util.BuilderSupport; import java.util.Map; /** * A helper class for creating namespaces for GroovyMarkup * * @author James Strachan * @version $Revision$ */ public class NamespaceBuilder { private BuilderSupport builder; public static NamespaceBuilderSupport newInstance(BuilderSupport builder, String uri) { return new NamespaceBuilder(builder).namespace(uri); } public static NamespaceBuilderSupport newInstance(BuilderSupport builder) { return new NamespaceBuilderSupport(builder); } public static NamespaceBuilderSupport newInstance(BuilderSupport builder, String uri, String prefix) { return new NamespaceBuilder(builder).namespace(uri, prefix); } public static NamespaceBuilderSupport newInstance(Map nsMap, BuilderSupport builder) { return new NamespaceBuilder(builder).declareNamespace(nsMap); } public NamespaceBuilder(BuilderSupport builder) { this.builder = builder; } public NamespaceBuilderSupport namespace(String uri) { return namespace(uri, ""); } public NamespaceBuilderSupport namespace(String uri, String prefix) { return new NamespaceBuilderSupport(builder, uri, prefix); } public NamespaceBuilderSupport declareNamespace(Map ns) { return new NamespaceBuilderSupport(builder, ns); } } groovy-1.8.6/src/main/groovy/xml/StreamingDOMBuilder.groovy0000644001501200150120000001700011627206700023277 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml import javax.xml.parsers.DocumentBuilderFactory import org.w3c.dom.Node import groovy.xml.streamingmarkupsupport.AbstractStreamingBuilder import groovy.xml.streamingmarkupsupport.BaseMarkupBuilder class StreamingDOMBuilder extends AbstractStreamingBuilder { def pendingStack = [] def defaultNamespaceStack = [""] def commentClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, dom -> def comment = dom.document.createComment(body) if (comment != null) { dom.element.appendChild(comment) } } def piClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, dom -> attrs.each {target, instruction -> def pi = null if (instruction instanceof Map) { def buf = new StringBuffer() instruction.each { name, value -> if (value.toString().contains('"')) { buf.append(" $name='$value'") } else { buf.append(" $name=\"$value\"" ) } } pi = dom.document.createProcessingInstruction(target, buf.toString()) } else { pi = dom.document.createProcessingInstruction(target, instruction) } if (pi != null) { dom.element.appendChild(pi) } } } def noopClosure = {doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, dom -> if (body instanceof Closure) { def body1 = body.clone() body1.delegate = doc body1(doc) } else if (body instanceof Buildable) { body.build(doc) } else if (body != null) { body.each { if (it instanceof Closure) { def body1 = it.clone() body1.delegate = doc body1(doc) } else if (it instanceof Buildable) { it.build(doc) } else { dom.element.appendChild(dom.document.createTextNode(it)) } } } } def tagClosure = {tag, doc, pendingNamespaces, namespaces, namespaceSpecificTags, prefix, attrs, body, dom -> def attributes = [] def nsAttributes = [] def defaultNamespace = defaultNamespaceStack.last() attrs.each {key, value -> if (key.contains('$')) { def parts = key.tokenize('$') def namespaceUri = null if (namespaces.containsKey(parts[0])) { namespaceUri = namespaces[parts[0]] nsAttributes.add([namespaceUri, "${parts[0]}:${parts[1]}", "$value"]) } else { throw new GroovyRuntimeException("bad attribute namespace tag in ${key}") } } else { attributes.add([key, value]) } } def hiddenNamespaces = [:] pendingNamespaces.each {key, value -> if (key == ':') { defaultNamespace = "$value" nsAttributes.add(["http://www.w3.org/2000/xmlns/", "xmlns", defaultNamespace]) } else { hiddenNamespaces[key] = namespaces[key] namespaces[key] = value nsAttributes.add(["http://www.w3.org/2000/xmlns/", "xmlns:${key}", "$value"]) } } // setup the tag info def uri = defaultNamespace def qualifiedName = tag if (prefix != "") { if (namespaces.containsKey(prefix)) { uri = namespaces[prefix] } else if (pendingNamespaces.containsKey(prefix)) { uri = pendingNamespaces[prefix] } else { throw new GroovyRuntimeException("Namespace prefix: ${prefix} is not bound to a URI") } if (prefix != ":") { qualifiedName = prefix + ":" + tag } } def element = dom.document.createElementNS(uri, qualifiedName) nsAttributes.each { element.setAttributeNS(it[0], it[1], it[2]) } attributes.each { element.setAttribute(it[0], it[1]) } dom.element.appendChild(element) dom.element = element if (body != null) { defaultNamespaceStack.push defaultNamespace pendingStack.add pendingNamespaces.clone() pendingNamespaces.clear() if (body instanceof Closure) { def body1 = body.clone() body1.delegate = doc body1(doc) } else if (body instanceof Buildable) { body.build(doc) } else { body.each { if (it instanceof Closure) { def body1 = it.clone() body1.delegate = doc body1(doc) } else if (it instanceof Buildable) { it.build(doc) } else { dom.element.appendChild(dom.document.createTextNode(it)) } } } pendingNamespaces.clear() pendingNamespaces.putAll pendingStack.pop() defaultNamespaceStack.pop() } dom.element = dom.element.getParentNode() hiddenNamespaces.each { key, value -> if (value == null) namespaces.remove key else namespaces[key] = value } } def builder = null StreamingDOMBuilder() { specialTags.putAll(['yield':noopClosure, 'yieldUnescaped':noopClosure, 'comment':commentClosure, 'pi':piClosure]) def nsSpecificTags = [':' : [tagClosure, tagClosure, [:]], // the default namespace 'http://www.w3.org/2000/xmlns/' : [tagClosure, tagClosure, [:]], 'http://www.codehaus.org/Groovy/markup/keywords' : [badTagClosure, tagClosure, specialTags]] this.builder = new BaseMarkupBuilder(nsSpecificTags) } def bind(closure) { def boundClosure = this.builder.bind(closure) return { if (it instanceof Node) { def document = it.getOwnerDocument() boundClosure.trigger = ['document' : document, 'element' : it] return document } else { def dBuilder = DocumentBuilderFactory.newInstance() dBuilder.namespaceAware = true def newDocument = dBuilder.newDocumentBuilder().newDocument() boundClosure.trigger = ['document' : newDocument, 'element' : newDocument] return newDocument } } } } groovy-1.8.6/src/main/groovy/xml/DOMBuilder.java0000644001501200150120000002122111627206700021021 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.xml; import groovy.util.BuilderSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Iterator; import java.util.Map; /** * A helper class for creating a W3C DOM tree * * @author James Strachan * @version $Revision$ */ public class DOMBuilder extends BuilderSupport { Document document; DocumentBuilder documentBuilder; public static DOMBuilder newInstance() throws ParserConfigurationException { return newInstance(false, true); } public static DOMBuilder newInstance(boolean validating, boolean namespaceAware) throws ParserConfigurationException { DocumentBuilderFactory factory = FactorySupport.createDocumentBuilderFactory(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); return new DOMBuilder(factory.newDocumentBuilder()); } /** * Creates a DocumentBuilder and uses it to parse the XML text read from the given reader. * A non-validating, namespace aware parser is used. * * @param reader the reader to read the XML text from * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte * stream or character stream supplied by the application. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies * the configuration requested. * @see #parse(Reader, boolean, boolean) */ public static Document parse(Reader reader) throws SAXException, IOException, ParserConfigurationException { return parse(reader, false, true); } /** * Creates a DocumentBuilder and uses it to parse the XML text read from the given reader, allowing * parser validation and namespace awareness to be controlled. * * @param reader the reader to read the XML text from * @param validating whether to validate the XML * @param namespaceAware whether the parser should be namespace aware * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte * stream or character stream supplied by the application. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies * the configuration requested. */ public static Document parse(Reader reader, boolean validating, boolean namespaceAware) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory = FactorySupport.createDocumentBuilderFactory(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); return documentBuilder.parse(new InputSource(reader)); } /** * A helper method to parse the given text as XML. * * @param text the XML text to parse * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte * stream or character stream supplied by the application. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies * the configuration requested. * @see #parse(Reader) */ public Document parseText(String text) throws SAXException, IOException, ParserConfigurationException { return parse(new StringReader(text)); } public DOMBuilder(Document document) { this.document = document; } public DOMBuilder(DocumentBuilder documentBuilder) { this.documentBuilder = documentBuilder; } protected void setParent(Object parent, Object child) { Node current = (Node) parent; Node node = (Node) child; current.appendChild(node); } protected Object createNode(Object name) { if (document == null) { document = createDocument(); } if (name instanceof QName) { QName qname = (QName) name; return document.createElementNS(qname.getNamespaceURI(), qname.getQualifiedName()); } else { return document.createElement(name.toString()); } } protected Document createDocument() { if (documentBuilder == null) { throw new IllegalArgumentException("No Document or DOMImplementation available so cannot create Document"); } else { return documentBuilder.newDocument(); } } protected Object createNode(Object name, Object value) { Element element = (Element) createNode(name); element.appendChild(document.createTextNode(value.toString())); return element; } protected Object createNode(Object name, Map attributes, Object value) { Element element = (Element) createNode(name, attributes); element.appendChild(document.createTextNode(value.toString())); return element; } protected Object createNode(Object name, Map attributes) { Element element = (Element) createNode(name); for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String attrName = entry.getKey().toString(); Object value = entry.getValue(); if ("xmlns".equals(attrName)) { if (value instanceof Map) { appendNamespaceAttributes(element, (Map) value); } else if (value instanceof String) { setStringNS(element, "", value); } else { throw new IllegalArgumentException("The value of the xmlns attribute must be a Map of QNames to String URIs"); } } else if (attrName.startsWith("xmlns:") && value instanceof String) { setStringNS(element, attrName.substring(6), value); } else { String valueText = (value != null) ? value.toString() : ""; element.setAttribute(attrName, valueText); } } return element; } protected void appendNamespaceAttributes(Element element, Map attributes) { for (Map.Entry entry : attributes.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (value == null) { throw new IllegalArgumentException("The value of key: " + key + " cannot be null"); } if (key instanceof String) { setStringNS(element, key, value); } else if (key instanceof QName) { QName qname = (QName) key; element.setAttributeNS(qname.getNamespaceURI(), qname.getQualifiedName(), value.toString()); } else { throw new IllegalArgumentException("The key: " + key + " should be an instanceof of " + QName.class); } } } private void setStringNS(Element element, Object key, Object value) { String prefix = (String) key; element.setAttributeNS("http://www.w3.org/2000/xmlns/", "".equals(prefix) ? "xmlns" : "xmlns:" + prefix, value.toString()); } } groovy-1.8.6/src/main/groovy/lang/0000755001501200150120000000000011715031256016353 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/lang/DeprecationException.java0000644001501200150120000000274211627206700023337 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Use this exception to mark a method implementation as being deprecated. * * Use the message to indicate the recommended way of calling the desired functionality. * Make throwing this exception the only line in the method implementation, i.e. unlike * the JavaDoc deprecated feature there is no relay to the new implementation but an early * and deliberate halt of execution ("fail early"). * * This exception is supposed to be used in the SNAPSHOT releases only. Before release, all * references to this exception should be resolved and the according methods removed. * * @author Dierk Koenig */ public class DeprecationException extends RuntimeException { public DeprecationException(String message) { super(message); } public DeprecationException(String message, Throwable cause) { super(message, cause); } } groovy-1.8.6/src/main/groovy/lang/ClosureInvokingMethod.java0000644001501200150120000000225111627206700023500 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * An interface for MetaMethods that invoke closures to implements. Used by ExpandoMetaClass * * @see groovy.lang.ExpandoMetaClass * * @author Graeme Rocher * @since 1.5 */ public interface ClosureInvokingMethod { /** * Returns the original closure that this method invokes * @return The closure */ Closure getClosure(); /** * Is it a static method? * @return True if it is */ boolean isStatic(); /** * The method name * @return The method name */ String getName(); } groovy-1.8.6/src/main/groovy/lang/MetaClassRegistryChangeEventListener.java0000644001501200150120000000261111627206700026441 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.EventListener; /** * A listener called whenever a constant MetaClass is set, removed or replaced. * * @see groovy.lang.MetaClassRegistry * @see groovy.lang.MetaClassRegistryChangeEvent * * @author Jochen Theodorou * */ public interface MetaClassRegistryChangeEventListener extends EventListener{ /** * Called when the a constant MetaClass is updated. If the new MetaClass is null, then the MetaClass * is removed. Be careful, while this method is executed other updates may happen. If you want this * method thread safe, you have to take care of that by yourself. * * @param cmcu - the change event */ void updateConstantMetaClass(MetaClassRegistryChangeEvent cmcu); } groovy-1.8.6/src/main/groovy/lang/StringWriterIOException.java0000644001501200150120000000211511627206700023767 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.io.IOException; /** * An IO exception occurred trying to append to a StringWriter which should never happen. * * @author James Strachan * @version $Revision$ */ public class StringWriterIOException extends RuntimeException { public StringWriterIOException(IOException e) { super(e); } public IOException getIOException() { return (IOException) getCause(); } } groovy-1.8.6/src/main/groovy/lang/MissingMethodException.java0000644001501200150120000000524711645141222023654 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MethodRankHelper; /** * An exception occurred if a dynamic method dispatch fails with an unknown method. *

    * Note that the Missing*Exception classes were named for consistency and * to avoid conflicts with JDK exceptions of the same name. * * @author James Strachan * @version $Revision$ */ public class MissingMethodException extends GroovyRuntimeException { private final String method; private final Class type; private final boolean isStatic; public Object[] getArguments() { return arguments; } private final Object arguments[]; public MissingMethodException(String method, Class type, Object[] arguments) { this(method, type, arguments, false); } public MissingMethodException(String method, Class type, Object[] arguments, boolean isStatic) { super(); this.method = method; this.type = type; this.isStatic = isStatic; this.arguments = arguments; } public String getMessage() { return "No signature of method: " + (isStatic ? "static " : "") + type.getName() + "." + method + "() is applicable for argument types: (" + InvokerHelper.toTypeString(arguments) + ") values: " + InvokerHelper.format(arguments, false, 40) + MethodRankHelper.getMethodSuggestionString(method, type, arguments); } /** * @return the name of the method that could not be found */ public String getMethod() { return method; } /** * @return The type on which the method was attempted to be called */ public Class getType() { return type; } /** * @return Whether the method was called in a static way, * i.e. on a class rather than an object. */ public boolean isStatic() { return isStatic; } } groovy-1.8.6/src/main/groovy/lang/Newify.java0000644001501200150120000001014211707612044020456 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation that supports writing constructor call expressions without the 'new' * keyword. Instead they can be written "Ruby-style" as a method call to a 'new' * method or "Python-style" by just omitting the keyword missing. *

    * It allows you to write code snippets like this ("Python-style"): *
     * {@code @Newify([Tree,Leaf])} class MyTreeProcessor {
     *     def myTree = Tree(Tree(Leaf("A"), Leaf("B")), Leaf("C"))
     *     def process() { ... }
     * }
     * 
    * or this ("Ruby-style"): *
     * {@code @Newify} class MyTreeProcessor {
     *     def myTree = Tree.new(Tree.new(Leaf.new("A"), Leaf.new("B")), Leaf.new("C"))
     *     def process() { ... }
     * }
     * 
    * * After the AST transformation, the following code is passed on for further compilation: *
     * class MyTreeProcessor {
     *     def myTree = new Tree(new Tree(new Leaf("A"), new Leaf("B")), new Leaf("C"))
     *     def process() { ... }
     * }
     * 
    * The annotation can be used on a whole class as shown above or selectively on a particular * method, constructor or field. * * The "Ruby-style" new conversions occur automatically unless the 'auto=false' * flag is given when using the annotation. You might do this if you create a new method * using meta programming. * * The "Python-style" conversions require you to specify each class on which you want them * to apply. The transformation then works by matching the basename of the provided classes to any * similarly named instance method calls not specifically bound to an object, i.e. associated * with the 'this' object. In other words Leaf("A") would be transformed to * new Leaf("A") but x.Leaf("A") would not be touched. * * An example showing how to use the annotation at different levels: *
     * {@code @Newify(auto=false, value=Foo)}
     * class Main {
     *     {@code @Newify} // turn auto on for field
     *     def field1 = java.math.BigInteger.new(42)
     *     def field2, field3, field4
     *
     *     {@code @Newify(Bar)}
     *     def process() {
     *         field2 = Bar("my bar")
     *     }
     *
     *     {@code @Newify(Baz)}
     *     Main() {
     *         field3 = Foo("my foo")
     *         field4 = Baz("my baz")
     *     }
     * }
     * 
    * * The annotation is intended to be used sparingly; perhaps in DSL scenarios or when * using deeply nested structural types. In particular, there is no support for using * the facility with two similarly named classes from different packages at the same time. * Though it is OK to have different packages in different contexts. Also, there is * no support for turning "Ruby-style" conversions off at the method, constructor or * field level if already turned on at the class level. * * @author Paul King */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE, ElementType.FIELD, ElementType.LOCAL_VARIABLE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.NewifyASTTransformation") public @interface Newify { Class[] value(); /** * @return if automatic conversion of "Ruby-style" new method calls should occur */ boolean auto() default true; } groovy-1.8.6/src/main/groovy/lang/ExpandoMetaClass.java0000644001501200150120000016473611707612044022433 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.MixinInMetaClass; import org.codehaus.groovy.runtime.DefaultCachedMethodKey; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.MethodKey; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.ConstructorMetaMethodSite; import org.codehaus.groovy.runtime.callsite.PogoMetaClassSite; import org.codehaus.groovy.runtime.callsite.PojoMetaClassSite; import org.codehaus.groovy.runtime.callsite.StaticMetaClassSite; import org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod; import org.codehaus.groovy.runtime.metaclass.ClosureStaticMetaMethod; import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo; import org.codehaus.groovy.runtime.metaclass.MethodSelectionException; import org.codehaus.groovy.runtime.metaclass.MixedInMetaClass; import org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaMethod; import org.codehaus.groovy.runtime.metaclass.OwnedMetaClass; import org.codehaus.groovy.runtime.metaclass.ThreadManagedMetaBeanProperty; import org.codehaus.groovy.util.FastArray; /** * ExpandoMetaClass is a MetaClass that behaves like an Expando, allowing the addition or replacement * of methods, properties and constructors on the fly. *

    * Some examples of usage: *

     * // defines or replaces instance method:
     * metaClass.myMethod = { args -> }
     * 

    * // defines a new instance method * metaClass.myMethod << { args -> } *

    * // creates multiple overloaded methods of the same name * metaClass.myMethod << { String s -> } << { Integer i -> } *

    * // defines or replaces a static method with the 'static' qualifier * metaClass.'static'.myMethod = { args -> } *

    * // defines a new static method with the 'static' qualifier * metaClass.'static'.myMethod << { args -> } *

    * // defines a new constructor * metaClass.constructor << { String arg -> } *

    * // defines or replaces a constructor * metaClass.constructor = { String arg -> } *

    * // defines a new property with an initial value of "blah" * metaClass.myProperty = "blah" *

    *

    * ExpandoMetaClass also supports a DSL/builder like notation to combine multiple definitions together. So instead of this: *

     * Number.metaClass.multiply = { Amount amount -> amount.times(delegate) }
     * Number.metaClass.div =      { Amount amount -> amount.inverse().times(delegate) }
     * 
    * You can also now do this: *
     * Number.metaClass {
     *     multiply { Amount amount -> amount.times(delegate) }
     *     div      { Amount amount -> amount.inverse().times(delegate) }
     * }
     * 
    *

    * ExpandoMetaClass also supports runtime mixins. While {@code @Mixin} allows you to mix in new behavior * to classes you own and are designing, you can not easily mixin anything to types you didn't own, e.g. * from third party libraries or from JDK library classes. * Runtime mixins let you add a mixin on any type at runtime. *

     * interface Vehicle {
     *     String getName()
     * }
     * 

    * // Category annotation style * {@code @Category}(Vehicle) class FlyingAbility { * def fly() { "I'm the ${name} and I fly!" } * } *

    * // traditional category style * class DivingAbility { * static dive(Vehicle self) { "I'm the ${self.name} and I dive!" } * } *

    * // provided by a third-party, so can't augment using Mixin annotation * class JamesBondVehicle implements Vehicle { * String getName() { "James Bond's vehicle" } * } *

    * // Can be added via metaClass, e.g.: * // JamesBondVehicle.metaClass.mixin DivingAbility, FlyingAbility * // Or using shorthand through DGM method on Class * JamesBondVehicle.mixin DivingAbility, FlyingAbility *

    * assert new JamesBondVehicle().fly() == * "I'm the James Bond's vehicle and I fly!" * assert new JamesBondVehicle().dive() == * "I'm the James Bond's vehicle and I dive!" *

    * As another example, consider the following class definitions: *
     * class Student {
     *     List schedule = []
     *     def addLecture(String lecture) { schedule << lecture }
     * }
     * 

    * class Worker { * List schedule = [] * def addMeeting(String meeting) { schedule << meeting } * } *

    * We can mimic a form of multiple inheritance as follows: *
     * class CollegeStudent {
     *     static { mixin Student, Worker }
     * }
     * new CollegeStudent().with {
     *     addMeeting('Performance review with Boss')
     *     addLecture('Learn about Groovy Mixins')
     *     println schedule
     *     println mixedIn[Student].schedule
     *     println mixedIn[Worker].schedule
     * }
     * 
    * Which outputs these lines when run: *
     * [Performance review with Boss]
     * [Learn about Groovy Mixins]
     * [Performance review with Boss]
     * 
    * Perhaps some explanation is required here. The methods and properties of Student and Worker are * added to CollegeStudent. Worker is added last, so for overlapping methods, its methods will * be used, e.g. when calling schedule, it will be the schedule property (getSchedule method) * from Worker that is used. The schedule property from Student will be shadowed but the mixedIn * notation allows us to get to that too if we need as the last two lines show. *

    * We can also be a little more dynamic and not require the CollegeStudent class to * be defined at all, e.g.: *

     * def cs = new Object()
     * cs.metaClass {
     *     mixin Student, Worker
     *     getSchedule {
     *         mixedIn[Student].schedule + mixedIn[Worker].schedule
     *     }
     * }
     * cs.with {
     *     addMeeting('Performance review with Boss')
     *     addLecture('Learn about Groovy Mixins')
     *     println schedule
     * }
     * 
    * Which outputs this line when run: *
     * [Learn about Groovy Mixins, Performance review with Boss]
     * 
    * As another example, we can also define a no dup queue by mixing in some * Queue and Set functionality as follows: *
     * def ndq = new Object()
     * ndq.metaClass {
     *     mixin ArrayDeque
     *     mixin HashSet
     *     leftShift = { Object o ->
     *         if (!mixedIn[Set].contains(o)) {
     *             mixedIn[Queue].push(o)
     *             mixedIn[Set].add(o)
     *         }
     *     }
     * }
     * ndq << 1
     * ndq << 2
     * ndq << 1
     * assert ndq.size() == 2
     * 
    * As a final example, we sometimes need to pass such mixed in classes or objects * into Java methods which require a given static type but the ExpandoMetaClass mixin approach uses a very dynamic * approach based on duck typing rather than static interface definitions, so doesn't by default * produce objects matching the required static type. Luckily, there is a mixins capability * within ExpandoMetaClass which supports the use of Groovy's common 'as StaticType' notation to produce an object * having the correct static type so that it can be passed to the Java method call in question. * A slightly contrived example illustrating this feature: *
     * class CustomComparator implements Comparator {
     *     int compare(Object a, b) { return a.size() - b.size() }
     * }
     * 

    * class CustomCloseable implements Closeable { * void close() { println 'Lights out - I am closing' } * } *

    * import static mypackage.IOUtils.closeQuietly * import static java.util.Collections.sort * def o = new Object() * o.metaClass.mixin CustomComparator, CustomCloseable * def items = ['a', 'bbb', 'cc'] * sort(items, o as Comparator) * println items // => [a, cc, bbb] * closeQuietly(o as Closeable) // => Lights out - I am closing *

    *

    * Further details *

    * When using the default implementations of MetaClass, methods are only allowed to be added before initialize() is called. * In other words you create a new MetaClass, add some methods and then call initialize(). If you attempt to add new methods * after initialize() has been called, an error will be thrown. This is to ensure that the MetaClass can operate appropriately * in multi-threaded environments as it forces you to do all method additions at the beginning, before using the MetaClass. *

    * ExpandoMetaClass differs here from the default in that it allows you to add methods after initialize has been called. * This is done by setting the initialize flag internally to false and then add the methods. Since this is not thread * safe it has to be done in a synchronized block. The methods to check for modification and initialization are * therefore synchronized as well. Any method call done through this meta class will first check if the it is * synchronized. Should this happen during a modification, then the method cannot be selected or called unless the * modification is completed. *

    * WARNING: This MetaClass uses a thread-bound ThreadLocal instance to store and retrieve properties. * In addition properties stored use soft references so they are both bound by the life of the Thread and by the soft * references. The implication here is you should NEVER use dynamic properties if you want their values to stick around * for long periods because as soon as the JVM is running low on memory or the thread dies they will be garbage collected. * * @author Graeme Rocher * @since 1.5 */ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject { private static final String META_CLASS = "metaClass"; private static final String CLASS = "class"; private static final String META_METHODS = "metaMethods"; private static final String METHODS = "methods"; private static final String PROPERTIES = "properties"; public static final String STATIC_QUALIFIER = "static"; public static final String CONSTRUCTOR = "constructor"; private static final String CLASS_PROPERTY = "class"; private static final String META_CLASS_PROPERTY = "metaClass"; private static final String GROOVY_CONSTRUCTOR = ""; // These two properties are used when no ExpandoMetaClassCreationHandle is present private MetaClass myMetaClass; private boolean initialized; private volatile boolean modified; private boolean initCalled; private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock readLock = rwl.readLock(); private final Lock writeLock = rwl.writeLock(); final private boolean allowChangesAfterInit; public boolean inRegistry; private final Set inheritedMetaMethods = new HashSet(); private final Map beanPropertyCache = new ConcurrentHashMap(); private final Map staticBeanPropertyCache = new ConcurrentHashMap(); private final Map expandoMethods = new ConcurrentHashMap(); public Collection getExpandoSubclassMethods() { return expandoSubclassMethods.values(); } private final ConcurrentHashMap expandoSubclassMethods = new ConcurrentHashMap(); private final Map expandoProperties = new ConcurrentHashMap(); private ClosureStaticMetaMethod invokeStaticMethodMethod; private final Set mixinClasses = new LinkedHashSet(); private ExpandoMetaClass(Class theClass, boolean register, boolean allowChangesAfterInit, MetaMethod[] add) { super(GroovySystem.getMetaClassRegistry(), theClass, add); this.myMetaClass = InvokerHelper.getMetaClass(getClass()); this.inRegistry = register; this.allowChangesAfterInit = allowChangesAfterInit; } /** * Constructs a new ExpandoMetaClass instance for the given class * * @param theClass The class that the MetaClass applies to */ public ExpandoMetaClass(Class theClass) { this(theClass,false,false,null); } public ExpandoMetaClass(Class theClass, MetaMethod [] add) { this(theClass,false,false,add); } /** * Constructs a new ExpandoMetaClass instance for the given class optionally placing the MetaClass * in the MetaClassRegistry automatically * * @param theClass The class that the MetaClass applies to * @param register True if the MetaClass should be registered inside the MetaClassRegistry. This defaults to true and ExpandoMetaClass will effect all instances if changed */ public ExpandoMetaClass(Class theClass, boolean register) { this(theClass,register,false,null); } public ExpandoMetaClass(Class theClass, boolean register, MetaMethod [] add) { this(theClass, register, false, add); } /** * Constructs a new ExpandoMetaClass instance for the given class optionally placing the MetaClass * in the MetaClassRegistry automatically * * @param theClass The class that the MetaClass applies to * @param register True if the MetaClass should be registered inside the MetaClassRegistry. This defaults to true and ExpandoMetaClass will effect all instances if changed * @param allowChangesAfterInit Should the meta class be modifiable after initialization. Default is false. */ public ExpandoMetaClass(Class theClass, boolean register, boolean allowChangesAfterInit) { this(theClass, register, allowChangesAfterInit, null); } public MetaMethod findMixinMethod(String methodName, Class[] arguments) { for (MixinInMetaClass mixin : mixinClasses) { final CachedClass mixinClass = mixin.getMixinClass(); MetaClass metaClass = mixinClass.classInfo.getMetaClassForClass(); if (metaClass == null) { metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(mixinClass.getTheClass()); } MetaMethod metaMethod = metaClass.pickMethod(methodName, arguments); if (metaMethod == null && metaClass instanceof MetaClassImpl) { MetaClassImpl mc = (MetaClassImpl) metaClass; for (CachedClass cl = mc.getTheCachedClass().getCachedSuperClass(); cl != null; cl = cl.getCachedSuperClass()) { metaMethod = mc.getMethodWithoutCaching(cl.getTheClass(), methodName, arguments, false); if (metaMethod != null) break; } } if (metaMethod != null) { MetaMethod method = new MixinInstanceMetaMethod(metaMethod, mixin); if (method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].isPrimitive) { MetaMethod noParam = pickMethod(methodName, new Class[0]); // if the current call itself is with empty arg class array, no need to recurse with 'new Class[0]' if (noParam == null && arguments.length != 0) { try { findMixinMethod(methodName, new Class[0]); } catch (MethodSelectionException msex) { /* * Here we just additionally tried to find another no-arg mixin method of the same name and register that as well, if found. * Safe to ignore a MethodSelectionException in this additional exercise. (GROOVY-4999) */ } } } registerInstanceMethod(method); return method; } } return null; } protected void onInvokeMethodFoundInHierarchy(MetaMethod method) { this.invokeMethodMethod = method; } protected void onSuperMethodFoundInHierarchy(MetaMethod method) { addSuperMethodIfNotOverridden(method); } protected void onSuperPropertyFoundInHierarchy(MetaBeanProperty property) { addMetaBeanProperty(property); } protected void onSetPropertyFoundInHierarchy(MetaMethod method) { this.setPropertyMethod = method; } protected void onGetPropertyFoundInHierarchy(MetaMethod method) { this.getPropertyMethod = method; } public boolean isModified() { return this.modified; } public void registerSubclassInstanceMethod(String name, Class klazz, Closure closure) { final List list = ClosureMetaMethod.createMethodList(name, klazz, closure); for (MetaMethod metaMethod : list) { registerSubclassInstanceMethod(metaMethod); } } public void registerSubclassInstanceMethod(MetaMethod metaMethod) { modified = true; final String name = metaMethod.getName(); Object methodOrList = expandoSubclassMethods.get(name); if (methodOrList == null) { expandoSubclassMethods.put(name, metaMethod); } else { if (methodOrList instanceof MetaMethod) { FastArray arr = new FastArray(2); arr.add(methodOrList); arr.add(metaMethod); expandoSubclassMethods.put(name, arr); } else { ((FastArray) methodOrList).add(metaMethod); } } } public void addMixinClass(MixinInMetaClass mixin) { mixinClasses.add(mixin); } public Object castToMixedType(Object obj, Class type) { for (MixinInMetaClass mixin : mixinClasses) { if (type.isAssignableFrom(mixin.getMixinClass().getTheClass())) return mixin.getMixinInstance(obj); } return null; } /** * For simulating closures in Java */ private interface Callable { void call(); } /** * Call to enable global use of global use of ExpandoMetaClass within the registry. This has the advantage that * inheritance will function correctly, but has a higher memory usage on the JVM than normal Groovy */ public static void enableGlobally() { DefaultMetaClassInfo.setWithoutCustomMetaclassCreationHandle(false); ExpandoMetaClassCreationHandle.enable(); } /** * Call to disable the global use of ExpandoMetaClass */ public static void disableGlobally() { DefaultMetaClassInfo.setWithoutCustomMetaclassCreationHandle(true); ExpandoMetaClassCreationHandle.disable(); } /* (non-Javadoc) * @see groovy.lang.MetaClassImpl#initialize() */ public void initialize() { try { writeLock.lock(); if (!isInitialized()) { super.initialize(); setInitialized(true); this.initCalled = true; } } finally { // downgrade to readlock before releasing just in case readLock.lock(); writeLock.unlock(); readLock.unlock(); } } /** * Checks if the meta class is initialized. * @see groovy.lang.MetaClassImpl#isInitialized() */ protected boolean isInitialized() { try { readLock.lock(); return this.initialized; } finally { readLock.unlock(); } } protected void setInitialized(boolean b) { this.initialized = b; } private void addSuperMethodIfNotOverridden(final MetaMethod metaMethodFromSuper) { performOperationOnMetaClass(new Callable() { public void call() { MetaMethod existing = null; try { existing = pickMethod(metaMethodFromSuper.getName(), metaMethodFromSuper.getNativeParameterTypes()); } catch ( GroovyRuntimeException e) { // ignore, this happens with overlapping method definitions } if (existing == null) { addMethodWithKey(metaMethodFromSuper); } else { boolean isGroovyMethod = getMetaMethods().contains(existing); if (isGroovyMethod) { addMethodWithKey(metaMethodFromSuper); } else if (inheritedMetaMethods.contains(existing)) { inheritedMetaMethods.remove(existing); addMethodWithKey(metaMethodFromSuper); } } } private void addMethodWithKey(final MetaMethod metaMethodFromSuper) { inheritedMetaMethods.add(metaMethodFromSuper); if (metaMethodFromSuper instanceof ClosureMetaMethod) { ClosureMetaMethod closureMethod = (ClosureMetaMethod)metaMethodFromSuper; String name = metaMethodFromSuper.getName(); final Class declaringClass = metaMethodFromSuper.getDeclaringClass().getTheClass(); ClosureMetaMethod localMethod = ClosureMetaMethod.copy(closureMethod); addMetaMethod(localMethod); MethodKey key = new DefaultCachedMethodKey(declaringClass, name, localMethod.getParameterTypes(), false); checkIfGroovyObjectMethod(localMethod); expandoMethods.put(key, localMethod); } } }); } /** * Instances of this class are returned when using the << left shift operator. *

    * Example: *

    * metaClass.myMethod << { String args -> } *

    * This allows callbacks to the ExpandoMetaClass for registering appending methods * * @author Graeme Rocher */ protected class ExpandoMetaProperty extends GroovyObjectSupport { protected String propertyName; protected boolean isStatic; protected ExpandoMetaProperty(String name) { this(name, false); } protected ExpandoMetaProperty(String name, boolean isStatic) { this.propertyName = name; this.isStatic = isStatic; } public String getPropertyName() { return this.propertyName; } public boolean isStatic() { return this.isStatic; } public Object leftShift(Object arg) { registerIfClosure(arg, false); return this; } private void registerIfClosure(Object arg, boolean replace) { if (arg instanceof Closure) { Closure callable = (Closure) arg; final List list = ClosureMetaMethod.createMethodList(propertyName, theClass, callable); if (list.isEmpty() && this.isStatic) { Class[] paramTypes = callable.getParameterTypes(); registerStatic(callable, replace, paramTypes); return; } for (MetaMethod method : list) { Class[] paramTypes = method.getNativeParameterTypes(); if (this.isStatic) { registerStatic(callable, replace, paramTypes); } else { registerInstance(method, replace, paramTypes); } } } } private void registerStatic(Closure callable, boolean replace, Class[] paramTypes) { Method foundMethod = checkIfMethodExists(theClass, propertyName, paramTypes, true); if (foundMethod != null && !replace) throw new GroovyRuntimeException("Cannot add new static method [" + propertyName + "] for arguments [" + DefaultGroovyMethods.inspect(paramTypes) + "]. It already exists!"); registerStaticMethod(propertyName, callable, paramTypes); } private void registerInstance(MetaMethod method, boolean replace, Class[] paramTypes) { Method foundMethod = checkIfMethodExists(theClass, propertyName, paramTypes, false); if (foundMethod != null && !replace) throw new GroovyRuntimeException("Cannot add new method [" + propertyName + "] for arguments [" + DefaultGroovyMethods.inspect(paramTypes) + "]. It already exists!"); registerInstanceMethod(method); } private Method checkIfMethodExists(Class methodClass, String methodName, Class[] paramTypes, boolean staticMethod) { Method foundMethod = null; Method[] methods = methodClass.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) && Modifier.isStatic(method.getModifiers()) == staticMethod) { if (MetaClassHelper.parametersAreCompatible(paramTypes, method.getParameterTypes())) { foundMethod = method; break; } } } return foundMethod; } /* (non-Javadoc) * @see groovy.lang.GroovyObjectSupport#getProperty(java.lang.String) */ public Object getProperty(String property) { this.propertyName = property; return this; } /* (non-Javadoc) * @see groovy.lang.GroovyObjectSupport#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(String property, Object newValue) { this.propertyName = property; registerIfClosure(newValue, true); } } /* (non-Javadoc) * @see groovy.lang.MetaClassImpl#invokeConstructor(java.lang.Object[]) */ public Object invokeConstructor(Object[] arguments) { // TODO This is the only area where this MetaClass needs to do some interception because Groovy's current // MetaClass uses hard coded references to the java.lang.reflect.Constructor class so you can't simply // inject Constructor like you can do properties, methods and fields. When Groovy's MetaClassImpl is // refactored we can fix this Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); MetaMethod method = pickMethod(GROOVY_CONSTRUCTOR, argClasses); if (method != null && method.getParameterTypes().length == arguments.length) { return method.invoke(theClass, arguments); } return super.invokeConstructor(arguments); } /** * Handles the ability to use the left shift operator to append new constructors * * @author Graeme Rocher */ protected class ExpandoMetaConstructor extends GroovyObjectSupport { public Object leftShift(Closure c) { if (c != null) { final List list = ClosureMetaMethod.createMethodList(GROOVY_CONSTRUCTOR, theClass, c); for (MetaMethod method : list) { Class[] paramTypes = method.getNativeParameterTypes(); Constructor ctor = retrieveConstructor(paramTypes); if (ctor != null) throw new GroovyRuntimeException("Cannot add new constructor for arguments [" + DefaultGroovyMethods.inspect(paramTypes) + "]. It already exists!"); registerInstanceMethod(method); } } return this; } } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getMetaClass() */ public MetaClass getMetaClass() { return myMetaClass; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getProperty(java.lang.String) */ public Object getProperty(String property) { if (isValidExpandoProperty(property)) { if (property.equals(STATIC_QUALIFIER)) { return new ExpandoMetaProperty(property, true); } else if (property.equals(CONSTRUCTOR)) { return new ExpandoMetaConstructor(); } else { if (myMetaClass.hasProperty(this, property) == null) return new ExpandoMetaProperty(property); else return myMetaClass.getProperty(this, property); } } else { return myMetaClass.getProperty(this, property); } } public static boolean isValidExpandoProperty(String property) { return !(property.equals(META_CLASS) || property.equals(CLASS) || property.equals(META_METHODS) || property.equals(METHODS) || property.equals(PROPERTIES)); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object) */ public Object invokeMethod(String name, Object args) { final Object[] argsArr = args instanceof Object[] ? (Object[]) args : new Object[]{args}; MetaMethod metaMethod = myMetaClass.getMetaMethod(name, argsArr); if (metaMethod != null) { // we have to use doMethodInvoke here instead of simply invoke, // because getMetaMethod may provide a method that can not be called // without further argument transformation, which is done only in // doMethodInvoke return metaMethod.doMethodInvoke(this, argsArr); } if (argsArr.length == 2 && argsArr[0] instanceof Class && argsArr[1] instanceof Closure) { if (argsArr[0] == theClass) registerInstanceMethod(name, (Closure) argsArr[1]); else { registerSubclassInstanceMethod(name, (Class) argsArr[0], (Closure) argsArr[1]); } return null; } if (argsArr.length == 1 && argsArr[0] instanceof Closure) { registerInstanceMethod(name, (Closure) argsArr[0]); return null; } throw new MissingMethodException(name, getClass(), argsArr); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setMetaClass(groovy.lang.MetaClass) */ public void setMetaClass(MetaClass metaClass) { this.myMetaClass = metaClass; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(String property, Object newValue) { if (newValue instanceof Closure) { if (property.equals(CONSTRUCTOR)) { property = GROOVY_CONSTRUCTOR; } Closure callable = (Closure) newValue; final List list = ClosureMetaMethod.createMethodList(property, theClass, callable); for (MetaMethod method : list) { // here we don't care if the method exists or not we assume the // developer is responsible and wants to override methods where necessary registerInstanceMethod(method); } } else { registerBeanProperty(property, newValue); } } public ExpandoMetaClass define(Closure closure) { final DefiningClosure definer = new DefiningClosure(); Object delegate = closure.getDelegate(); closure.setDelegate(definer); closure.setResolveStrategy(Closure.DELEGATE_ONLY); closure.call((Object)null); closure.setDelegate(delegate); closure.setResolveStrategy(Closure.DELEGATE_FIRST); definer.definition = false; return this; } protected synchronized void performOperationOnMetaClass(Callable c) { try { writeLock.lock(); if (allowChangesAfterInit) { setInitialized(false); } c.call(); } finally { if (initCalled) { setInitialized(true); } // downgrade to readlock before releasing just in case readLock.lock(); writeLock.unlock(); readLock.unlock(); } } protected void checkInitalised() { try { readLock.lock(); super.checkInitalised(); } finally { readLock.unlock(); } } /** * Registers a new bean property * * @param property The property name * @param newValue The properties initial value */ public void registerBeanProperty(final String property, final Object newValue) { performOperationOnMetaClass(new Callable() { public void call() { Class type = newValue == null ? Object.class : newValue.getClass(); MetaBeanProperty mbp = newValue instanceof MetaBeanProperty ? (MetaBeanProperty) newValue : new ThreadManagedMetaBeanProperty(theClass, property, type, newValue); final MetaMethod getter = mbp.getGetter(); final MethodKey getterKey = new DefaultCachedMethodKey(theClass, getter.getName(), CachedClass.EMPTY_ARRAY, false); final MetaMethod setter = mbp.getSetter(); final MethodKey setterKey = new DefaultCachedMethodKey(theClass, setter.getName(), setter.getParameterTypes(), false); addMetaMethod(getter); addMetaMethod(setter); expandoMethods.put(setterKey, setter); expandoMethods.put(getterKey, getter); expandoProperties.put(mbp.getName(), mbp); addMetaBeanProperty(mbp); performRegistryCallbacks(); } }); } /** * Registers a new instance method for the given method name and closure on this MetaClass * * @param metaMethod */ public void registerInstanceMethod(final MetaMethod metaMethod) { final boolean inited = this.initCalled; performOperationOnMetaClass(new Callable() { public void call() { String methodName = metaMethod.getName(); checkIfGroovyObjectMethod(metaMethod); MethodKey key = new DefaultCachedMethodKey(theClass, methodName, metaMethod.getParameterTypes(), false); if (isInitialized()) { throw new RuntimeException("Already initialized, cannot add new method: " + metaMethod); } // we always adds meta methods to class itself addMetaMethodToIndex(metaMethod, metaMethodIndex.getHeader(theClass)); dropMethodCache(methodName); expandoMethods.put(key, metaMethod); if (inited && isGetter(methodName, metaMethod.getParameterTypes())) { String propertyName = getPropertyForGetter(methodName); registerBeanPropertyForMethod(metaMethod, propertyName, true, false); } else if (inited && isSetter(methodName, metaMethod.getParameterTypes())) { String propertyName = getPropertyForSetter(methodName); registerBeanPropertyForMethod(metaMethod, propertyName, false, false); } performRegistryCallbacks(); } }); } public void registerInstanceMethod(String name, Closure closure) { final List list = ClosureMetaMethod.createMethodList(name, theClass, closure); for (MetaMethod method : list) { registerInstanceMethod(method); } } /** * Overrides the behavior of parent getMethods() method to make MetaClass aware of added Expando methods * * @return A list of MetaMethods * @see MetaObjectProtocol#getMethods() */ public List getMethods() { List methodList = new ArrayList(); methodList.addAll(this.expandoMethods.values()); methodList.addAll(super.getMethods()); return methodList; } public List getProperties() { List propertyList = new ArrayList(); propertyList.addAll(super.getProperties()); return propertyList; } private void performRegistryCallbacks() { MetaClassRegistry registry = GroovySystem.getMetaClassRegistry(); incVersion(); if (!modified) { modified = true; // Implementation note: By default Groovy uses soft references to store MetaClass // this insures the registry doesn't grow and get out of hand. By doing this we're // saying this this EMC will be a hard reference in the registry. As we're only // going have a small number of classes that have modified EMC this is ok if (inRegistry) { MetaClass currMetaClass = registry.getMetaClass(theClass); if (!(currMetaClass instanceof ExpandoMetaClass) && currMetaClass instanceof AdaptingMetaClass) { ((AdaptingMetaClass) currMetaClass).setAdaptee(this); } else { registry.setMetaClass(theClass, this); } } } } private void registerBeanPropertyForMethod(MetaMethod metaMethod, String propertyName, boolean getter, boolean isStatic) { Map propertyCache = isStatic ? staticBeanPropertyCache : beanPropertyCache; MetaBeanProperty beanProperty = (MetaBeanProperty) propertyCache.get(propertyName); if (beanProperty == null) { if (getter) beanProperty = new MetaBeanProperty(propertyName, Object.class, metaMethod, null); else beanProperty = new MetaBeanProperty(propertyName, Object.class, null, metaMethod); propertyCache.put(propertyName, beanProperty); } else { if (getter) { MetaMethod setterMethod = beanProperty.getSetter(); Class type = setterMethod != null ? setterMethod.getParameterTypes()[0].getTheClass() : Object.class; beanProperty = new MetaBeanProperty(propertyName, type, metaMethod, setterMethod); propertyCache.put(propertyName, beanProperty); } else { MetaMethod getterMethod = beanProperty.getGetter(); beanProperty = new MetaBeanProperty(propertyName, metaMethod.getParameterTypes()[0].getTheClass(), getterMethod, metaMethod); propertyCache.put(propertyName, beanProperty); } } expandoProperties.put(beanProperty.getName(), beanProperty); addMetaBeanProperty(beanProperty); } protected void registerStaticMethod(final String name, final Closure callable) { registerStaticMethod(name, callable, null); } /** * Registers a new static method for the given method name and closure on this MetaClass * * @param name The method name * @param callable The callable Closure */ protected void registerStaticMethod(final String name, final Closure callable, final Class[] paramTypes) { performOperationOnMetaClass(new Callable() { public void call() { String methodName; if (name.equals(METHOD_MISSING)) methodName = STATIC_METHOD_MISSING; else if (name.equals(PROPERTY_MISSING)) methodName = STATIC_PROPERTY_MISSING; else methodName = name; ClosureStaticMetaMethod metaMethod = null; if (paramTypes != null) { metaMethod = new ClosureStaticMetaMethod(methodName, theClass, callable, paramTypes); } else { metaMethod = new ClosureStaticMetaMethod(methodName, theClass, callable); } if (methodName.equals(INVOKE_METHOD_METHOD) && callable.getParameterTypes().length == 2) { invokeStaticMethodMethod = metaMethod; } else { if (methodName.equals(METHOD_MISSING)) { methodName = STATIC_METHOD_MISSING; } MethodKey key = new DefaultCachedMethodKey(theClass, methodName, metaMethod.getParameterTypes(), false); addMetaMethod(metaMethod); dropStaticMethodCache(methodName); // cacheStaticMethod(key,metaMethod); if (isGetter(methodName, metaMethod.getParameterTypes())) { String propertyName = getPropertyForGetter(methodName); registerBeanPropertyForMethod(metaMethod, propertyName, true, true); } else if (isSetter(methodName, metaMethod.getParameterTypes())) { String propertyName = getPropertyForSetter(methodName); registerBeanPropertyForMethod(metaMethod, propertyName, false, true); } performRegistryCallbacks(); expandoMethods.put(key, metaMethod); } } }); } protected Object getSubclassMetaMethods(String methodName) { if (!isModified()) return null; return expandoSubclassMethods.get(methodName); } /** * @return The Java class enhanced by this MetaClass */ public Class getJavaClass() { return theClass; } /** * Called from ExpandoMetaClassCreationHandle in the registry if it exists to * set up inheritance handling * * @param modifiedSuperExpandos A list of modified super ExpandoMetaClass */ public void refreshInheritedMethods(Set modifiedSuperExpandos) { for (Iterator i = modifiedSuperExpandos.iterator(); i.hasNext();) { ExpandoMetaClass superExpando = (ExpandoMetaClass) i.next(); if (superExpando != this) { refreshInheritedMethods(superExpando); } } } private void refreshInheritedMethods(ExpandoMetaClass superExpando) { List metaMethods = superExpando.getExpandoMethods(); for (MetaMethod metaMethod : metaMethods) { if (metaMethod.isStatic()) { if (superExpando.getTheClass() != getTheClass()) continue; // don't inherit static methods except our own registerStaticMethod(metaMethod.getName(), (Closure) ((ClosureStaticMetaMethod) metaMethod).getClosure().clone()); } else addSuperMethodIfNotOverridden(metaMethod); } Collection metaProperties = superExpando.getExpandoProperties(); for (Object metaProperty : metaProperties) { MetaBeanProperty property = (MetaBeanProperty) metaProperty; expandoProperties.put(property.getName(), property); addMetaBeanProperty(property); } } /** * Returns a list of expando MetaMethod instances added to this ExpandoMetaClass * * @return the expandoMethods */ public List getExpandoMethods() { return Collections.unmodifiableList(DefaultGroovyMethods.toList(expandoMethods.values())); } /** * Returns a list of MetaBeanProperty instances added to this ExpandoMetaClass * * @return the expandoProperties */ public Collection getExpandoProperties() { return Collections.unmodifiableCollection(expandoProperties.values()); } /** * Overrides default implementation just in case invokeMethod has been overridden by ExpandoMetaClass * * @see groovy.lang.MetaClassImpl#invokeMethod(Class, Object, String, Object[], boolean, boolean) */ public Object invokeMethod(Class sender, Object object, String methodName, Object[] originalArguments, boolean isCallToSuper, boolean fromInsideClass) { if (invokeMethodMethod != null) { MetaClassHelper.unwrap(originalArguments); return invokeMethodMethod.invoke(object, new Object[]{methodName, originalArguments}); } return super.invokeMethod(sender, object, methodName, originalArguments, isCallToSuper, fromInsideClass); } /** * Overrides default implementation just in case a static invoke method has been set on ExpandoMetaClass * * @see MetaClassImpl#invokeStaticMethod(Object, String, Object[]) */ public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { if (invokeStaticMethodMethod != null) { MetaClassHelper.unwrap(arguments); return invokeStaticMethodMethod.invoke(object, new Object[]{methodName, arguments}); } return super.invokeStaticMethod(object, methodName, arguments); } /** * Overrides default implementation just in case getProperty method has been overridden by ExpandoMetaClass * * @see MetaClassImpl#getProperty(Class, Object, String, boolean, boolean) */ public Object getProperty(Class sender, Object object, String name, boolean useSuper, boolean fromInsideClass) { if (hasOverrideGetProperty(name) && getJavaClass().isInstance(object)) { return getPropertyMethod.invoke(object, new Object[]{name}); } if ("mixedIn".equals(name)) { return new MixedInAccessor(object, mixinClasses); } return super.getProperty(sender, object, name, useSuper, fromInsideClass); } /** * Overrides default implementation just in case getProperty method has been overridden by ExpandoMetaClass * * @see MetaClassImpl#getProperty(Object, String) */ public Object getProperty(Object object, String name) { if (hasOverrideGetProperty(name) && getJavaClass().isInstance(object)) { return getPropertyMethod.invoke(object, new Object[]{name}); } return super.getProperty(object, name); } private boolean hasOverrideGetProperty(String name) { return getPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && !name.equals(CLASS_PROPERTY); } /** * Overrides default implementation just in case setProperty method has been overridden by ExpandoMetaClass * * @see MetaClassImpl#setProperty(Class, Object, String, Object, boolean, boolean) */ public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) { if (setPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && getJavaClass().isInstance(object)) { setPropertyMethod.invoke(object, new Object[]{name, newValue}); return; } super.setProperty(sender, object, name, newValue, useSuper, fromInsideClass); } /** * Looks up an existing MetaProperty by name * * @param name The name of the MetaProperty * @return The MetaProperty or null if it doesn't exist */ public MetaProperty getMetaProperty(String name) { MetaProperty mp = (MetaProperty) this.expandoProperties.get(name); if (mp != null) return mp; return super.getMetaProperty(name); } /** * Returns true if the MetaClass has the given property * * @param name The name of the MetaProperty * @return True it exists as a MetaProperty */ public boolean hasMetaProperty(String name) { return getMetaProperty(name) != null; } /** * Checks whether a MetaMethod for the given name and arguments exists * * @param name The name of the MetaMethod * @param args The arguments to the meta method * @return True if the method exists otherwise null */ public boolean hasMetaMethod(String name, Class[] args) { return super.pickMethod(name, args) != null; } /** * Determine if this method name suffix is a legitimate bean property name. * Either the first or second letter must be upperCase for that to be true. */ private static boolean isPropertyName(String name) { return ((name.length() > 0) && Character.isUpperCase(name.charAt(0))) || ((name.length() > 1) && Character.isUpperCase(name.charAt(1))); } /** * Returns true if the name of the method specified and the number of arguments make it a javabean property * * @param name True if its a Javabean property * @param args The arguments * @return True if it is a javabean property method */ private boolean isGetter(String name, CachedClass[] args) { if (name == null || name.length() == 0 || args == null) return false; if (args.length != 0) return false; if (name.startsWith("get")) { name = name.substring(3); return isPropertyName(name); } else if (name.startsWith("is")) { name = name.substring(2); return isPropertyName(name); } return false; } /** * Returns a property name equivalent for the given getter name or null if it is not a getter * * @param getterName The getter name * @return The property name equivalent */ private String getPropertyForGetter(String getterName) { if (getterName == null || getterName.length() == 0) return null; if (getterName.startsWith("get")) { String prop = getterName.substring(3); return convertPropertyName(prop); } else if (getterName.startsWith("is")) { String prop = getterName.substring(2); return convertPropertyName(prop); } return null; } private String convertPropertyName(String prop) { if (Character.isDigit(prop.charAt(0))) { return prop; } return java.beans.Introspector.decapitalize(prop); } /** * Returns a property name equivalent for the given setter name or null if it is not a getter * * @param setterName The setter name * @return The property name equivalent */ public String getPropertyForSetter(String setterName) { if (setterName == null || setterName.length() == 0) return null; if (setterName.startsWith("set")) { String prop = setterName.substring(3); return convertPropertyName(prop); } return null; } public boolean isSetter(String name, CachedClass[] args) { if (name == null || name.length() == 0 || args == null) return false; if (name.startsWith("set")) { if (args.length != 1) return false; name = name.substring(3); return isPropertyName(name); } return false; } public CallSite createPojoCallSite(CallSite site, Object receiver, Object[] args) { if (invokeMethodMethod != null) return new PojoMetaClassSite(site, this); return super.createPojoCallSite(site, receiver, args); } public CallSite createStaticSite(CallSite site, Object[] args) { if (invokeStaticMethodMethod != null) return new StaticMetaClassSite(site, this); return super.createStaticSite(site, args); } public CallSite createPogoCallSite(CallSite site, Object[] args) { if (invokeMethodMethod != null) return new PogoMetaClassSite(site, this); return super.createPogoCallSite(site, args); } public CallSite createPogoCallCurrentSite(CallSite site, Class sender, String name, Object[] args) { if (invokeMethodMethod != null) return new PogoMetaClassSite(site, this); return super.createPogoCallCurrentSite(site, sender, args); } public CallSite createConstructorSite(CallSite site, Object[] args) { Class[] params = MetaClassHelper.convertToTypeArray(args); MetaMethod method = pickMethod(GROOVY_CONSTRUCTOR, params); if (method != null && method.getParameterTypes().length == args.length) { if (method.getDeclaringClass().getTheClass().equals(getTheClass())) { return new ConstructorMetaMethodSite(site, this, method, params); } } return super.createConstructorSite(site, args); } private class SubClassDefiningClosure extends GroovyObjectSupport { private final Class klazz; public SubClassDefiningClosure(Class klazz) { this.klazz = klazz; } public Object invokeMethod(String name, Object obj) { if (obj instanceof Object[]) { Object args[] = (Object[]) obj; if (args.length == 1 && args[0] instanceof Closure) { registerSubclassInstanceMethod(name, klazz, (Closure) args[0]); return null; } } throw new MissingMethodException(name, getClass(), new Object[]{obj}); } } private class DefiningClosure extends GroovyObjectSupport { boolean definition = true; public void mixin(Class category) { mixin(Collections.singletonList(category)); } public void mixin(List categories) { DefaultGroovyMethods.mixin(ExpandoMetaClass.this, categories); } public void mixin(Class[] categories) { DefaultGroovyMethods.mixin(ExpandoMetaClass.this, categories); } public void define(Class subClass, Closure closure) { final SubClassDefiningClosure definer = new SubClassDefiningClosure(subClass); closure.setDelegate(definer); closure.setResolveStrategy(Closure.DELEGATE_FIRST); closure.call((Object)null); } public Object invokeMethod(String name, Object obj) { try { return getMetaClass().invokeMethod(this, name, obj); } catch (MissingMethodException mme) { if (obj instanceof Object[]) { if (STATIC_QUALIFIER.equals(name)) { final StaticDefiningClosure staticDef = new StaticDefiningClosure(); Closure c = (Closure) ((Object[]) obj)[0]; c.setDelegate(staticDef); c.setResolveStrategy(Closure.DELEGATE_ONLY); c.call((Object)null); return null; } Object args[] = (Object[]) obj; if (args.length == 1 && args[0] instanceof Closure) { registerInstanceMethod(name, (Closure) args[0]); } else if (args.length == 2 && args[0] instanceof Class && args[1] instanceof Closure) registerSubclassInstanceMethod(name, (Class) args[0], (Closure) args[1]); else ExpandoMetaClass.this.setProperty(name, ((Object[]) obj)[0]); return null; } throw mme; } } public void setProperty(String property, Object newValue) { ExpandoMetaClass.this.setProperty(property, newValue); } public Object getProperty(String property) { if (STATIC_QUALIFIER.equals(property)) return new StaticDefiningClosure(); if (definition) return new ExpandoMetaProperty(property); else throw new MissingPropertyException(property, getClass()); } } private class StaticDefiningClosure extends ExpandoMetaProperty { protected StaticDefiningClosure() { super(STATIC_QUALIFIER, true); } public Object invokeMethod(String name, Object obj) { if (obj instanceof Object[]) { final Object[] args = (Object[]) obj; if (args.length == 1 && args[0] instanceof Closure) { registerStaticMethod(name, (Closure) args[0]); return null; } } throw new MissingMethodException(name, getClass(), obj instanceof Object[] ? (Object[]) obj : new Object[]{obj}); } } private static class MixedInAccessor { private final Object object; private final Set mixinClasses; public MixedInAccessor(Object object, Set mixinClasses) { this.object = object; this.mixinClasses = mixinClasses; } public Object getAt(Class key) { if (key.isAssignableFrom(object.getClass())) { return new GroovyObjectSupport() { { final MetaClass ownMetaClass = InvokerHelper.getMetaClass(object.getClass()); setMetaClass(new OwnedMetaClass(ownMetaClass) { protected Object getOwner() { return object; } protected MetaClass getOwnerMetaClass(Object owner) { return getAdaptee(); } }); } }; } for (final MixinInMetaClass mixin : mixinClasses) { if (key.isAssignableFrom(mixin.getMixinClass().getTheClass())) { return new GroovyObjectSupport() { { final Object mixedInInstance = mixin.getMixinInstance(object); setMetaClass(new OwnedMetaClass(InvokerHelper.getMetaClass(mixedInInstance)) { @Override protected Object getOwner() { return mixedInInstance; } @Override protected MetaClass getOwnerMetaClass(Object owner) { return ((MixedInMetaClass) getAdaptee()).getAdaptee(); } }); } }; } } throw new RuntimeException("Class " + key + " isn't mixed in " + object.getClass()); } public void putAt(Class key, Object value) { for (MixinInMetaClass mixin : mixinClasses) if (mixin.getMixinClass().getTheClass() == key) { mixin.setMixinInstance(object, value); return; } throw new RuntimeException("Class " + key + " isn't mixed in " + object.getClass()); } } } groovy-1.8.6/src/main/groovy/lang/SpreadListEvaluatingException.java0000644001501200150120000000145111627206700025170 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; public class SpreadListEvaluatingException extends GroovyRuntimeException { public SpreadListEvaluatingException(String message) { super(message); } } groovy-1.8.6/src/main/groovy/lang/PropertyAccessInterceptor.java0000644001501200150120000000263411627206700024410 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** *

    An interface that adds the ability to intercept * property getters/setters * * @author Graeme Rocher * @since Oct 24, 2005 */ public interface PropertyAccessInterceptor extends Interceptor { /** * Intercepts a getXXX call and returns a result. The result is replaced by the * real value if doGet() return false * * @param object The target object * @param property The property to get * @return A value supplied by the interceptor */ Object beforeGet(Object object, String property); /** * Intercepts a setXXX call * * @param object The target object * @param property The property to set * @param newValue The new value */ void beforeSet(Object object, String property, Object newValue); } groovy-1.8.6/src/main/groovy/lang/Closure.java0000644001501200150120000011404711712272374020646 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.reflection.stdclasses.CachedClosureClass; import org.codehaus.groovy.runtime.ComposedClosure; import org.codehaus.groovy.runtime.CurriedClosure; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.memoize.LRUCache; import org.codehaus.groovy.runtime.memoize.Memoize; import org.codehaus.groovy.runtime.memoize.UnlimitedConcurrentCache; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.List; import java.util.Map; /** * Represents any closure object in Groovy. *

    * Groovy allows instances of Closures to be called in a * short form. For example: *

     *   def a = 1
     *   def c = {a}
     *   assert c() == 1
     * 
    * To be able to use a Closure in this way with your own * subclass, you need to provide a doCall method with any * signature you want to. This ensures that * {@link #getMaximumNumberOfParameters()} and * {@link #getParameterTypes()} will work too without any * additional code. If no doCall method is provided a * closure must be used in its long form like *
     *   def a = 1
     *   def c = {a}
     *   assert c.call() == 1
     * 
    * * @author James Strachan * @author John Wilson * @author Jochen Theodorou * @author Graeme Rocher * @author Paul King * * @version $Revision$ */ public abstract class Closure extends GroovyObjectSupport implements Cloneable, Runnable, GroovyCallable, Serializable { /** * With this resolveStrategy set the closure will attempt to resolve property references to the * owner first, then the delegate (this is the default strategy). * * For example the following code : *
         *  class Test {
         *    def x = 30
         *    def y = 40
         *
         *    def run() {
         *        def data = [ x: 10, y: 20 ]
         *        def cl = { y = x + y }
         *        cl.delegate = data
         *        cl()
         *        println x
         *        println y
         *        println data
         *    }
         *  }
         *
         *  new Test().run()
         * 
    * will output : *
         *     30
         *     70
         *     [x:10, y:20]
         * 
    * because the x and y fields declared in the Test class the variables in the delegate.

    * Note that local variables are always looked up first, independently of the resolution strategy. */ public static final int OWNER_FIRST = 0; /** * With this resolveStrategy set the closure will attempt to resolve property references to the * delegate first then the owner. * * For example the following code : *

         *  class Test {
         *    def x = 30
         *    def y = 40
         *
         *    def run() {
         *        def data = [ x: 10, y: 20 ]
         *        def cl = { y = x + y }
         *        cl.delegate = data
         *        cl.resolveStrategy = Closure.DELEGATE_FIRST
         *        cl()
         *        println x
         *        println y
         *        println data
         *    }
         *  }
         *
         *  new Test().run()
         * 
    * will output : *
         *     30
         *     40
         *     [x:10, y:30]
         * 
    * because the x and y variables declared in the delegate shadow the fields in the owner class.

    * Note that local variables are always looked up first, independently of the resolution strategy. */ public static final int DELEGATE_FIRST = 1; /** * With this resolveStrategy set the closure will resolve property references to the owner only * and not call the delegate at all. For example the following code : * *

         *  class Test {
         *    def x = 30
         *    def y = 40
         *
         *    def run() {
         *        def data = [ x: 10, y: 20, z: 30 ]
         *        def cl = { y = x + y }
         *        cl.delegate = data
         *        cl.resolveStrategy = Closure.OWNER_ONLY
         *        cl()
         *        println x
         *        println y
         *        println data
         *    }
         *  }
         *
         *  new Test().run()
         * 
    * * will throw "No such property: z" error because even if the z variable is declared in the delegate, no * lookup is made.

    * Note that local variables are always looked up first, independently of the resolution strategy. */ public static final int OWNER_ONLY = 2; /** * With this resolveStrategy set the closure will resolve property references to the delegate * only and entirely bypass the owner. For example the following code : * *

         *  class Test {
         *    def x = 30
         *    def y = 40
         *    def z = 50
         *
         *    def run() {
         *        def data = [ x: 10, y: 20 ]
         *        def cl = { y = x + y + z}
         *        cl.delegate = data
         *        cl.resolveStrategy = Closure.DELEGATE_ONLY
         *        cl()
         *        println x
         *        println y
         *        println data
         *    }
         *  }
         *
         *  new Test().run()
         * 
    * * will throw an error because even if the owner declares a "z" field, the resolution strategy will bypass * lookup in the owner.

    * Note that local variables are always looked up first, independently of the resolution strategy. */ public static final int DELEGATE_ONLY = 3; /** * With this resolveStrategy set the closure will resolve property references to itself and go * through the usual MetaClass look-up process. This means that properties are neither resolved from * the owner nor the delegate, but only on the closure object itself. This allows the developer to override * getProperty using ExpandoMetaClass of the closure itself.

    * Note that local variables are always looked up first, independently of the resolution strategy. */ public static final int TO_SELF = 4; public static final int DONE = 1, SKIP = 2; private static final Object[] EMPTY_OBJECT_ARRAY = {}; public static final Closure IDENTITY = new Closure(null) { public Object doCall(Object args) { return args; } }; private Object delegate; private Object owner; private Object thisObject; private int resolveStrategy = OWNER_FIRST; private int directive; protected Class[] parameterTypes; protected int maximumNumberOfParameters; private static final long serialVersionUID = 4368710879820278874L; public Closure(Object owner, Object thisObject) { this.owner = owner; this.delegate = owner; this.thisObject = thisObject; final CachedClosureClass cachedClass = (CachedClosureClass) ReflectionCache.getCachedClass(getClass()); parameterTypes = cachedClass.getParameterTypes(); maximumNumberOfParameters = cachedClass.getMaximumNumberOfParameters(); } /** * Constructor used when the "this" object for the Closure is null. * This is rarely the case in normal Groovy usage. * * @param owner the Closure owner */ public Closure(Object owner) { this(owner, null); } /** * Sets the strategy which the closure uses to resolve property references. The default is Closure.OWNER_FIRST * * @param resolveStrategy The resolve strategy to set * * @see groovy.lang.Closure#DELEGATE_FIRST * @see groovy.lang.Closure#DELEGATE_ONLY * @see groovy.lang.Closure#OWNER_FIRST * @see groovy.lang.Closure#OWNER_ONLY * @see groovy.lang.Closure#TO_SELF */ public void setResolveStrategy(int resolveStrategy) { this.resolveStrategy = resolveStrategy; } /** * Gets the strategy which the closure users to resolve methods and properties * * @return The resolve strategy * * @see groovy.lang.Closure#DELEGATE_FIRST * @see groovy.lang.Closure#DELEGATE_ONLY * @see groovy.lang.Closure#OWNER_FIRST * @see groovy.lang.Closure#OWNER_ONLY * @see groovy.lang.Closure#TO_SELF */ public int getResolveStrategy() { return resolveStrategy; } public Object getThisObject(){ return thisObject; } public Object getProperty(final String property) { if ("delegate".equals(property)) { return getDelegate(); } else if ("owner".equals(property)) { return getOwner(); } else if ("maximumNumberOfParameters".equals(property)) { return getMaximumNumberOfParameters(); } else if ("parameterTypes".equals(property)) { return getParameterTypes(); } else if ("metaClass".equals(property)) { return getMetaClass(); } else if ("class".equals(property)) { return getClass(); } else if ("directive".equals(property)) { return getDirective(); } else if ("resolveStrategy".equals(property)) { return getResolveStrategy(); } else if ("thisObject".equals(property)) { return getThisObject(); } else { switch(resolveStrategy) { case DELEGATE_FIRST: return getPropertyDelegateFirst(property); case DELEGATE_ONLY: return InvokerHelper.getProperty(this.delegate, property); case OWNER_ONLY: return InvokerHelper.getProperty(this.owner, property); case TO_SELF: return super.getProperty(property); default: return getPropertyOwnerFirst(property); } } } private Object getPropertyDelegateFirst(String property) { if (delegate == null) return getPropertyOwnerFirst(property); return getPropertyTryThese(property, this.delegate, this.owner); } private Object getPropertyOwnerFirst(String property) { return getPropertyTryThese(property, this.owner, this.delegate); } private Object getPropertyTryThese(String property, Object firstTry, Object secondTry) { try { // let's try getting the property on the first object return InvokerHelper.getProperty(firstTry, property); } catch (MissingPropertyException e1) { if (secondTry != null && firstTry != this && firstTry != secondTry) { try { // let's try getting the property on the second object return InvokerHelper.getProperty(secondTry, property); } catch (GroovyRuntimeException e2) { // ignore, we'll throw e1 } } throw e1; } } public void setProperty(String property, Object newValue) { if ("delegate".equals(property)) { setDelegate(newValue); } else if ("metaClass".equals(property)) { setMetaClass((MetaClass) newValue); } else if ("resolveStrategy".equals(property)) { setResolveStrategy(((Number) newValue).intValue()); } else if ("directive".equals(property)) { setDirective(((Number) newValue).intValue()); } else { switch(resolveStrategy) { case DELEGATE_FIRST: setPropertyDelegateFirst(property, newValue); break; case DELEGATE_ONLY: InvokerHelper.setProperty(this.delegate, property, newValue); break; case OWNER_ONLY: InvokerHelper.setProperty(this.owner, property, newValue); break; case TO_SELF: super.setProperty(property, newValue); break; default: setPropertyOwnerFirst(property, newValue); } } } private void setPropertyDelegateFirst(String property, Object newValue) { if (delegate == null) setPropertyOwnerFirst(property, newValue); else setPropertyTryThese(property, newValue, this.delegate, this.owner); } private void setPropertyOwnerFirst(String property, Object newValue) { setPropertyTryThese(property, newValue, this.owner, this.delegate); } private void setPropertyTryThese(String property, Object newValue, Object firstTry, Object secondTry) { try { // let's try setting the property on the first object InvokerHelper.setProperty(firstTry, property, newValue); } catch (GroovyRuntimeException e1) { if (firstTry != null && firstTry != this && firstTry != secondTry) { try { // let's try setting the property on the second object InvokerHelper.setProperty(secondTry, property, newValue); return; } catch (GroovyRuntimeException e2) { // ignore, we'll throw e1 } } throw e1; } } public boolean isCase(Object candidate){ return DefaultTypeTransformation.castToBoolean(call(candidate)); } /** * Invokes the closure without any parameters, returning any value if applicable. * * @return the value if applicable or null if there is no return statement in the closure */ public V call() { final Object[] NOARGS = EMPTY_OBJECT_ARRAY; return call(NOARGS); } @SuppressWarnings("unchecked") public V call(Object... args) { try { return (V) getMetaClass().invokeMethod(this,"doCall",args); } catch (Exception e) { return (V) throwRuntimeException(e); } } /** * Invokes the closure, returning any value if applicable. * * @param arguments could be a single value or a List of values * @return the value if applicable or null if there is no return statement in the closure */ public V call(final Object arguments) { return call(new Object[]{arguments}); } protected static Object throwRuntimeException(Throwable throwable) { if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else { throw new GroovyRuntimeException(throwable.getMessage(), throwable); } } /** * @return the owner Object to which method calls will go which is * typically the outer class when the closure is constructed */ public Object getOwner() { return this.owner; } /** * @return the delegate Object to which method calls will go which is * typically the outer class when the closure is constructed */ public Object getDelegate() { return this.delegate; } /** * Allows the delegate to be changed such as when performing markup building * * @param delegate the new delegate */ public void setDelegate(Object delegate) { this.delegate = delegate; } /** * @return the parameter types of the longest doCall method * of this closure */ public Class[] getParameterTypes() { return parameterTypes; } /** * @return the maximum number of parameters a doCall method * of this closure can take */ public int getMaximumNumberOfParameters() { return maximumNumberOfParameters; } /** * @return a version of this closure which implements Writable. Note that * the returned Writable also overrides {@link #toString()} in order * to allow rendering the result directly to a String. */ public Closure asWritable() { return new WritableClosure(); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { call(); } /** * Support for Closure currying. *

    * Typical usage: *

         * def multiply = { a, b -> a * b }
         * def doubler = multiply.curry(2)
         * assert doubler(4) == 8
         * 
    * Note: special treatment is given to Closure vararg-style capability. * If you curry a vararg parameter, you don't consume the entire vararg array * but instead the first parameter of the vararg array as the following example shows: *
         * def a = { one, two, Object[] others -> one + two + others.sum() }
         * assert a.parameterTypes.name == ['java.lang.Object', 'java.lang.Object', '[Ljava.lang.Object;']
         * assert a(1,2,3,4) == 10
         * def b = a.curry(1)
         * assert b.parameterTypes.name == ['java.lang.Object', '[Ljava.lang.Object;']
         * assert b(2,3,4) == 10
         * def c = b.curry(2)
         * assert c.parameterTypes.name == ['[Ljava.lang.Object;']
         * assert c(3,4) == 10
         * def d = c.curry(3)
         * assert d.parameterTypes.name == ['[Ljava.lang.Object;']
         * assert d(4) == 10
         * def e = d.curry(4)
         * assert e.parameterTypes.name == ['[Ljava.lang.Object;']
         * assert e() == 10
         * assert e(5) == 15
         * 
    * * * @param arguments the arguments to bind * @return the new closure with its arguments bound */ public Closure curry(final Object... arguments) { return new CurriedClosure(this, arguments); } /** * Support for Closure currying. * * @param argument the argument to bind * @return the new closure with the argument bound * @see #curry(Object...) */ public Closure curry(final Object argument) { return curry(new Object[]{argument}); } /** * Support for Closure "right" currying. * Parameters are supplied on the right rather than left as per the normal curry() method. * Typical usage: *
         * def divide = { a, b -> a / b }
         * def halver = divide.rcurry(2)
         * assert halver(8) == 4
         * 
    * * @param arguments the arguments to bind * @return the new closure with its arguments bound * @see #curry(Object...) */ public Closure rcurry(final Object... arguments) { return new CurriedClosure(-arguments.length, this, arguments); } /** * Support for Closure "right" currying. * * @param argument the argument to bind * @return the new closure with the argument bound * @see #rcurry(Object...) */ public Closure rcurry(final Object argument) { return rcurry(new Object[]{argument}); } /** * Support for Closure currying at a given index. * Parameters are supplied from index position "n". * Typical usage: *
         * def caseInsensitive = { a, b -> a.toLowerCase() <=> b.toLowerCase() } as Comparator
         * def caseSensitive = { a, b -> a <=> b } as Comparator
         * def animals1 = ['ant', 'dog', 'BEE']
         * def animals2 = animals1 + ['Cat']
         * // curry middle param of this utility method:
         * // Collections#binarySearch(List list, Object key, Comparator c)
         * def catSearcher = Collections.&binarySearch.ncurry(1, "cat")
         * [[animals1, animals2], [caseInsensitive, caseSensitive]].combinations().each{ a, c ->
         *   def idx = catSearcher(a.sort(c), c)
         *   print a.sort(c).toString().padRight(22)
         *   if (idx < 0) println "Not found but would belong in position ${-idx - 1}"
         *   else println "Found at index $idx"
         * }
         * // =>
         * // [ant, BEE, dog]       Not found but would belong in position 2
         * // [ant, BEE, Cat, dog]  Found at index 2
         * // [BEE, ant, dog]       Not found but would belong in position 2
         * // [BEE, Cat, ant, dog]  Not found but would belong in position 3
         * 
    * * @param n the index from which to bind parameters (may be -ve in which case it will be normalized) * @param arguments the arguments to bind * @return the new closure with its arguments bound * @see #curry(Object...) */ public Closure ncurry(int n, final Object... arguments) { return new CurriedClosure(n, this, arguments); } /** * Support for Closure currying at a given index. * * @param argument the argument to bind * @return the new closure with the argument bound * @see #ncurry(int, Object...) */ public Closure ncurry(int n, final Object argument) { return ncurry(n, new Object[]{argument}); } /** * Support for Closure forward composition. *

    * Typical usage: *

         * def twice = { a -> a * 2 }
         * def thrice = { a -> a * 3 }
         * def times6 = twice >> thrice
         * // equivalent: times6 = { a -> thrice(twice(a)) }
         * assert times6(3) == 18
         * 
    * * @param other the Closure to compose with the current Closure * @return the new composed Closure */ public Closure rightShift(final Closure other) { return new ComposedClosure(this, other); } /** * Support for Closure reverse composition. *

    * Typical usage: *

         * def twice = { a -> a * 2 }
         * def thrice = { a -> a * 3 }
         * def times6 = thrice << twice
         * // equivalent: times6 = { a -> thrice(twice(a)) }
         * assert times6(3) == 18
         * 
    * * @param other the Closure to compose with the current Closure * @return the new composed Closure */ public Closure leftShift(final Closure other) { return new ComposedClosure(other, this); } /* * * Alias for calling a Closure for non-closure arguments. *

    * Typical usage: *

         * def twice = { a -> a * 2 }
         * def thrice = { a -> a * 3 }
         * assert thrice << twice << 3 == 18
         * 
    * * @param arg the argument to call the closure with * @return the result of calling the Closure */ public V leftShift(final Object arg) { return call(arg); } /** * Creates a caching variant of the closure. * Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache * making subsequent calls with the same arguments fast. * This variant will keep all cached values forever, i.e. till the closure gets garbage-collected. * The returned function can be safely used concurrently from multiple threads, however, the implementation * values high average-scenario performance and so concurrent calls on the memoized function with identical argument values * may not necessarily be able to benefit from each other's cached return value. With this having been mentioned, * the performance trade-off still makes concurrent use of memoized functions safe and highly recommended. * * The cache gets garbage-collected together with the memoized closure. * * @return A new closure forwarding to the original one while caching the results */ public Closure memoize() { return Memoize.buildMemoizeFunction(new UnlimitedConcurrentCache(), this); } /** * Creates a caching variant of the closure with upper limit on the cache size. * Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache * making subsequent calls with the same arguments fast. * This variant will keep all values until the upper size limit is reached. Then the values in the cache start rotating * using the LRU (Last Recently Used) strategy. * The returned function can be safely used concurrently from multiple threads, however, the implementation * values high average-scenario performance and so concurrent calls on the memoized function with identical argument values * may not necessarily be able to benefit from each other's cached return value. With this having been mentioned, * the performance trade-off still makes concurrent use of memoized functions safe and highly recommended. * * The cache gets garbage-collected together with the memoized closure. * * @param maxCacheSize The maximum size the cache can grow to * @return A new function forwarding to the original one while caching the results */ public Closure memoizeAtMost(final int maxCacheSize) { if (maxCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the maxCacheSize parameter for memoizeAtMost."); return Memoize.buildMemoizeFunction(new LRUCache(maxCacheSize), this); } /** * Creates a caching variant of the closure with automatic cache size adjustment and lower limit * on the cache size. * Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache * making subsequent calls with the same arguments fast. * This variant allows the garbage collector to release entries from the cache and at the same time allows * the user to specify how many entries should be protected from the eventual gc-initiated eviction. * Cached entries exceeding the specified preservation threshold are made available for eviction based on * the LRU (Last Recently Used) strategy. * Given the non-deterministic nature of garbage collector, the actual cache size may grow well beyond the limits * set by the user if memory is plentiful. * The returned function can be safely used concurrently from multiple threads, however, the implementation * values high average-scenario performance and so concurrent calls on the memoized function with identical argument values * may not necessarily be able to benefit from each other's cached return value. Also the protectedCacheSize parameter * might not be respected accurately in such scenarios for some periods of time. With this having been mentioned, * the performance trade-off still makes concurrent use of memoized functions safe and highly recommended. * * The cache gets garbage-collected together with the memoized closure. * @param protectedCacheSize Number of cached return values to protect from garbage collection * @return A new function forwarding to the original one while caching the results */ public Closure memoizeAtLeast(final int protectedCacheSize) { if (protectedCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the protectedCacheSize parameter for memoizeAtLeast."); return Memoize.buildSoftReferenceMemoizeFunction(protectedCacheSize, new UnlimitedConcurrentCache(), this); } /** * Creates a caching variant of the closure with automatic cache size adjustment and lower and upper limits * on the cache size. * Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache * making subsequent calls with the same arguments fast. * This variant allows the garbage collector to release entries from the cache and at the same time allows * the user to specify how many entries should be protected from the eventual gc-initiated eviction. * Cached entries exceeding the specified preservation threshold are made available for eviction based on * the LRU (Last Recently Used) strategy. * Given the non-deterministic nature of garbage collector, the actual cache size may grow well beyond the protected * size limits set by the user, if memory is plentiful. * Also, this variant will never exceed in size the upper size limit. Once the upper size limit has been reached, * the values in the cache start rotating using the LRU (Last Recently Used) strategy. * The returned function can be safely used concurrently from multiple threads, however, the implementation * values high average-scenario performance and so concurrent calls on the memoized function with identical argument values * may not necessarily be able to benefit from each other's cached return value. Also the protectedCacheSize parameter * might not be respected accurately in such scenarios for some periods of time. With this having been mentioned, * the performance trade-off still makes concurrent use of memoized functions safe and highly recommended. * * The cache gets garbage-collected together with the memoized closure. * @param protectedCacheSize Number of cached return values to protect from garbage collection * @param maxCacheSize The maximum size the cache can grow to * @return A new function forwarding to the original one while caching the results */ public Closure memoizeBetween(final int protectedCacheSize, final int maxCacheSize) { if (protectedCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the protectedCacheSize parameter for memoizeBetween."); if (maxCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the maxCacheSize parameter for memoizeBetween."); if (protectedCacheSize > maxCacheSize) throw new IllegalArgumentException("The maxCacheSize parameter to memoizeBetween is required to be greater or equal to the protectedCacheSize parameter."); return Memoize.buildSoftReferenceMemoizeFunction(protectedCacheSize, new LRUCache(maxCacheSize), this); } /** * Builds a trampolined variant of the current closure. * To prevent stack overflow due to deep recursion, functions can instead leverage the trampoline mechanism * and avoid recursive calls altogether. Under trampoline, the function is supposed to perform one step of * the calculation and, instead of a recursive call to itself or another function, it return back a new closure, * which will be executed by the trampoline as the next step. * Once a non-closure value is returned, the trampoline stops and returns the value as the final result. * Here is an example: *
         * def fact
         * fact = { n, total ->
         *     n == 0 ? total : fact.trampoline(n - 1, n * total)
         * }.trampoline()
         * def factorial = { n -> fact(n, 1G)}
         * println factorial(20) // => 2432902008176640000
         * 
    * * @param args Parameters to the closure, so as the trampoline mechanism can call it * @return A closure, which will execute the original closure on a trampoline. */ public Closure trampoline(final Object... args) { return new TrampolineClosure(this.curry(args)); } /** * Builds a trampolined variant of the current closure. * To prevent stack overflow due to deep recursion, functions can instead leverage the trampoline mechanism * and avoid recursive calls altogether. Under trampoline, the function is supposed to perform one step of * the calculation and, instead of a recursive call to itself or another function, it return back a new closure, * which will be executed by the trampoline as the next step. * Once a non-closure value is returned, the trampoline stops and returns the value as the final result. * @return A closure, which will execute the original closure on a trampoline. * @see #trampoline(Object...) */ public Closure trampoline() { return new TrampolineClosure(this); } /* (non-Javadoc) * @see java.lang.Object#clone() */ public Object clone() { try { return super.clone(); } catch (final CloneNotSupportedException e) { return null; } } /* * Implementation note: * This has to be an inner class! * * Reason: * Closure.this.call will call the outer call method, but * with the inner class as executing object. This means any * invokeMethod or getProperty call will be called on this * inner class instead of the outer! */ private class WritableClosure extends Closure implements Writable { public WritableClosure() { super(Closure.this); } /* (non-Javadoc) * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(Writer out) throws IOException { Closure.this.call(new Object[]{out}); return out; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object) */ public Object invokeMethod(String method, Object arguments) { if ("clone".equals(method)) { return clone(); } else if ("curry".equals(method)) { return curry((Object[]) arguments); } else if ("asWritable".equals(method)) { return asWritable(); } else { return Closure.this.invokeMethod(method, arguments); } } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getProperty(java.lang.String) */ public Object getProperty(String property) { return Closure.this.getProperty(property); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(String property, Object newValue) { Closure.this.setProperty(property, newValue); } /* (non-Javadoc) * @see groovy.lang.Closure#call() */ public Object call() { return ((Closure) getOwner()).call(); } /* (non-Javadoc) * @see groovy.lang.Closure#call(java.lang.Object) */ public Object call(Object arguments) { return ((Closure) getOwner()).call(arguments); } public Object call(Object... args) { return ((Closure) getOwner()).call(args); } public Object doCall(Object... args) { return call(args); } /* (non-Javadoc) * @see groovy.lang.Closure#getDelegate() */ public Object getDelegate() { return Closure.this.getDelegate(); } /* (non-Javadoc) * @see groovy.lang.Closure#setDelegate(java.lang.Object) */ public void setDelegate(Object delegate) { Closure.this.setDelegate(delegate); } /* (non-Javadoc) * @see groovy.lang.Closure#getParameterTypes() */ public Class[] getParameterTypes() { return Closure.this.getParameterTypes(); } /* (non-Javadoc) * @see groovy.lang.Closure#getParameterTypes() */ public int getMaximumNumberOfParameters() { return Closure.this.getMaximumNumberOfParameters(); } /* (non-Javadoc) * @see groovy.lang.Closure#asWritable() */ public Closure asWritable() { return this; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { Closure.this.run(); } /* (non-Javadoc) * @see java.lang.Object#clone() */ public Object clone() { return ((Closure) Closure.this.clone()).asWritable(); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return Closure.this.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object arg0) { return Closure.this.equals(arg0); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { final StringWriter writer = new StringWriter(); try { writeTo(writer); } catch (IOException e) { return null; } return writer.toString(); } public Closure curry(final Object... arguments) { return (new CurriedClosure(this, arguments)).asWritable(); } public void setResolveStrategy(int resolveStrategy) { Closure.this.setResolveStrategy(resolveStrategy); } public int getResolveStrategy() { return Closure.this.getResolveStrategy(); } } /** * @return Returns the directive. */ public int getDirective() { return directive; } /** * @param directive The directive to set. */ public void setDirective(int directive) { this.directive = directive; } /** * Returns a copy of this closure where the "owner", "delegate" and "thisObject" * fields are null, allowing proper serialization when one of them is not serializable. * * @return a serializable closure. * * @since 1.8.5 */ @SuppressWarnings("unchecked") public Closure dehydrate() { Closure result = (Closure) this.clone(); result.delegate = null; result.owner = null; result.thisObject = null; return result; } /** * Returns a copy of this closure for which the delegate, owner and thisObject are * replaced with the supplied parameters. Use this when you want to rehydrate a * closure which has been made serializable thanks to the {@link #dehydrate()} * method. * @param delegate the closure delegate * @param owner the closure owner * @param thisObject the closure "this" object * @return a copy of this closure where owner, delegate and thisObject are replaced * * @since 1.8.5 */ @SuppressWarnings("unchecked") public Closure rehydrate(Object delegate, Object owner, Object thisObject) { Closure result = (Closure) this.clone(); result.delegate = delegate; result.owner = owner; result.thisObject = thisObject; return result; } } groovy-1.8.6/src/main/groovy/lang/Grab.java0000644001501200150120000001321511707612044020074 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; /** * Used to grab the referenced artifact and its dependencies and make it available on the Classpath. *

    * Some examples: *

     * {@code @Grab}(group='commons-lang', module='commons-lang', version='2.4')
     * import org.apache.commons.lang.WordUtils
     * println "Hello ${WordUtils.capitalize('world')}"
     * 
    * Or using the compact Gradle-inspired syntax: *
     * {@code @Grab}('commons-lang:commons-lang:2.4')
     * import org.apache.commons.lang.WordUtils
     * println "Hello ${WordUtils.capitalize('world')}"
     * 
    * or the same thing again using the Ivy-inspired syntax variant: *
     * {@code @Grab}('commons-lang#commons-lang;2.4')
     * import org.apache.commons.lang.WordUtils
     * println "Hello ${WordUtils.capitalize('world')}"
     * 
    * Further information such as where artifacts are downloaded to, how to add additional resolvers, * how to customise artifact resolution etc., can be found on the Grape documentation page: * http://groovy.codehaus.org/Grape. */ @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) public @interface Grab { /** * The organisation or group, e.g.: "org.apache.ant" */ String group() default ""; /** * The module or artifact, e.g.: "ant-junit" */ String module(); /** * The revision or version, e.g.: "1.7.1" */ String version(); /** * The classifier if in use, e.g.: "jdk14" */ String classifier() default ""; /** * Defaults to {@code true} but set to {@code false} if you don't want transitive dependencies also to be downloaded. * You may then need additional {@code @Grab} statements for any required dependencies. */ boolean transitive() default true; /** * Defaults to {@code false} but set to {@code true} to indicate to the underlying Ivy conflict manager that this * dependency should be forced to the given revision. Otherwise, depending on the conflict manager in play, a later * compatible version might be used instead. */ boolean force() default false; /** * Defaults to {@code false} but set to {@code true} if the dependency artifacts may change without a corresponding * revision change. Not normally recommended but may be useful for certain kinds of snapshot artifacts. * May reduce the amount of underlying Ivy caching. Proper behavior may be dependent on the resolver in use. */ boolean changing() default false; /** * The configuration if in use (normally only used by internal ivy repositories). * One or more comma separated values with or without square brackets, * e.g. for hibernate you might have "default,proxool,oscache" or "[default,dbcp,swarmcache]". * This last hibernate example assumes you have set up such configurations in your local Ivy repo * and have changed your grape config (using grapeConfig.xml) or the {@code @GrabConfig} annotation * to point to that repo. */ String conf() default ""; /** * The extension of the artifact (normally safe to leave at default value of "jar" but other values like "zip" * are sometimes useful). */ String ext() default ""; /** * The type of the artifact (normally safe to leave at default value of "jar" but other values like "sources" and "javadoc" are sometimes useful). * But see also the "classifier" attribute which is also sometimes used for "sources" and "javadoc". */ String type() default ""; /** * Allows a more compact convenience form in one of two formats with optional appended attributes. *

    * You can choose either format but not mix-n-match:
    * {@code group:module:version:classifier@ext} (where only group and module are required)
    * {@code group#module;version[confs]} (where only group and module are required and confs, * if used, is one or more comma separated configuration names)
    * In addition, you can add any valid Ivy attributes at the end of your string value using * semi-colon separated name = value pairs, e.g.:
    * {@code @Grab('junit:junit:*;transitive=false')}
    * {@code @Grab('group=junit;module=junit;version=4.8.2;classifier=javadoc') }
    */ String value() default ""; /** * By default, when a {@code @Grab} annotation is used, the {@code grab()} call is added * to the static initializers of the class the annotatable node appears in. * If you wish to disable this, add {@code initClass=false} to the annotation. */ boolean initClass() default true; } groovy-1.8.6/src/main/groovy/lang/TrampolineClosure.java0000644001501200150120000000670111707612044022672 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * A TrampolineClosure wraps a closure that needs to be executed on a functional trampoline. * Upon calling, a TrampolineClosure will call the original closure waiting for its result. * If the outcome of the call is another instance of a TrampolineClosure, created perhaps as a result to a call to the TrampolineClosure.trampoline() * method, the TrampolineClosure will again be invoked. This repetitive invocation of returned TrampolineClosure instances will continue * until a value other than TrampolineClosure is returned. * That value will become the final result of the trampoline. * * @author Vaclav Pech */ final class TrampolineClosure extends Closure { private final Closure original; TrampolineClosure(final Closure original) { super(original.getOwner(), original.getDelegate()); this.original = original; } /** * Delegates to the wrapped closure */ @Override public int getMaximumNumberOfParameters() { return original.maximumNumberOfParameters; } /** * Delegates to the wrapped closure */ @Override public Class[] getParameterTypes() { return original.parameterTypes; } /** * Starts the trampoline loop and calls the wrapped closure as the first step. * @return The final result of the trampoline */ @Override public V call() { return loop(original.call()); } /** * Starts the trampoline loop and calls the wrapped closure as the first step. * @return The final result of the trampoline */ @Override public V call(final Object arguments) { return loop(original.call(arguments)); } /** * Starts the trampoline loop and calls the wrapped closure as the first step. * @return The final result of the trampoline */ @Override public V call(final Object... args) { return loop(original.call(args)); } private V loop(final Object lastResult) { Object result = lastResult; for (;;) { if (result instanceof TrampolineClosure) { result = ((TrampolineClosure)result).original.call(); } else return (V) result; } } /** * Builds a trampolined variant of the current closure. * @param args Parameters to curry to the underlying closure. * @return An instance of TrampolineClosure wrapping the original closure after currying. */ @Override public Closure trampoline(final Object... args) { return new TrampolineClosure(original.curry(args)); } /** * Returns itself, since it is a good enough trampolined variant of the current closure. * @return An instance of TrampolineClosure wrapping the original closure. */ @Override public Closure trampoline() { return this; } } groovy-1.8.6/src/main/groovy/lang/Delegate.java0000644001501200150120000001261411707612044020735 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Field annotation to automatically delegate part of the functionality of an owner class to the annotated field. *

    * All public instance methods present in the type of the annotated field and not present in the owner class * will be added to owner class at compile time. The implementation of such automatically added * methods is code which calls through to the delegate as per the normal delegate pattern. *

    * As an example, consider this code: *

     * class Event {
     *     {@code @Delegate} Date when
     *     String title, url
     * }
     *
     * def gr8conf = new Event(title: "GR8 Conference",
     *                           url: "http://www.gr8conf.org",
     *                          when: Date.parse("yyyy/MM/dd", "2009/05/18"))
     *
     * def javaOne = new Event(title: "JavaOne",
     *                           url: "http://java.sun.com/javaone/",
     *                          when: Date.parse("yyyy/MM/dd", "2009/06/02"))
     *
     * assert gr8conf.before(javaOne.when)
     * 
    * * In this example, the {@code Event} class will have a method called * {@code before(Date otherDate)} as well as other public methods of the * {@code Date} class. * The implementation of the {@code before()} method will look like this: *
     *     public boolean before(Date otherDate) {
     *         return when.before(otherDate);
     *     }
     * 
    * * By default, the owner class will also be modified to implement any interfaces * implemented by the field. So, in the example above, because {@code Date} * implements {@code Cloneable} the following will be true: * *
     * assert gr8conf instanceof Cloneable
     * 
    * * This behavior can be disabled by setting the * annotation's {@code interfaces} element to false, * i.e. {@code @Delegate(interfaces = false)}, e.g. in the above * example, the delegate definition would become: *
     *     {@code @Delegate}(interfaces = false) Date when
     * 
    * and the following would be true: *
     * assert !(gr8conf instanceof Cloneable)
     * 
    * * If multiple delegate fields are used and the same method signature occurs * in more than one of the respective field types, then the delegate will be * made to the first defined field having that signature. If this does occur, * it might be regarded as a smell (or at least poor style) and it might be * clearer to do the delegation by long hand. *

    * By default, methods of the delegate type marked as {@code @Deprecated} are * not automatically added to the owner class. You can force these methods to * be added by setting the annotation's {@code deprecated} element to true, * i.e. {@code @Delegate(deprecated = true)}. *

    * For example, in the example above if we change the delegate definition to: *

     *     {@code @Delegate}(deprecated = true) Date when
     * 
    * then the following additional lines will execute successfully (during 2009): *
     * assert gr8conf.year + 1900 == 2009
     * assert gr8conf.toGMTString().contains(" 2009 ")
     * 
    * Otherwise these lines produce a groovy.lang.MissingPropertyException * or groovy.lang.MissingMethodException respectively as those two methods are * {@code @Deprecated} in {@code Date}. *

    * Technical notes: *

      *
    • Static methods, synthetic methods or methods from the GroovyObject interface * are not candidates for delegation *
    • Non-abstract non-static methods defined in the owner class or its superclasses take * precedence over methods with identical signatures from a {@code @Delegate} field *
    • All methods defined in the owner class (including static, abstract or private etc.) * take precedence over methods with identical signatures from a {@code @Delegate} field *
    • Recursive delegation to your own class is not allowed *
    • Mixing of {@code @Delegate} with default method arguments is known not to work in some cases. We recommend * not using these features together. *
    * * @author Alex Tkachman * @author Paul King */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.DelegateASTTransformation") public @interface Delegate { /** * @return true if owner class should implement interfaces implemented by field */ boolean interfaces() default true; /** * @return true if owner class should delegate to methods annotated with @Deprecated */ boolean deprecated() default false; } groovy-1.8.6/src/main/groovy/lang/GString.java0000644001501200150120000001745611707612044020611 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; /** * Represents a String which contains embedded values such as "hello there * ${user} how are you?" which can be evaluated lazily. Advanced users can * iterate over the text and values to perform special processing, such as for * performing SQL operations, the values can be substituted for ? and the * actual value objects can be bound to a JDBC statement. The lovely name of * this class was suggested by Jules Gosnell and was such a good idea, I * couldn't resist :) * * @author James Strachan * @version $Revision$ */ public abstract class GString extends GroovyObjectSupport implements Comparable, CharSequence, Writable, Buildable, Serializable { static final long serialVersionUID = -2638020355892246323L; /** * A GString containing a single empty String and no values. */ public static final GString EMPTY = new GString(new Object[0]) { public String[] getStrings() { return new String[]{""}; } }; private Object[] values; public GString(Object values) { this.values = (Object[]) values; } public GString(Object[] values) { this.values = values; } // will be static in an instance public abstract String[] getStrings(); /** * Overloaded to implement duck typing for Strings * so that any method that can't be evaluated on this * object will be forwarded to the toString() object instead. */ public Object invokeMethod(String name, Object args) { try { return super.invokeMethod(name, args); } catch (MissingMethodException e) { // lets try invoke the method on the real String return InvokerHelper.invokeMethod(toString(), name, args); } } public Object[] getValues() { return values; } public GString plus(GString that) { List stringList = new ArrayList(); List valueList = new ArrayList(); stringList.addAll(Arrays.asList(getStrings())); valueList.addAll(Arrays.asList(getValues())); List thatStrings = Arrays.asList(that.getStrings()); if (stringList.size() > valueList.size()) { thatStrings = new ArrayList(thatStrings); // merge onto end of previous GString to avoid an empty bridging value String s = stringList.get(stringList.size() - 1); s += thatStrings.get(0); thatStrings.remove(0); stringList.set(stringList.size() - 1, s); } stringList.addAll(thatStrings); valueList.addAll(Arrays.asList(that.getValues())); final String[] newStrings = new String[stringList.size()]; stringList.toArray(newStrings); Object[] newValues = valueList.toArray(); return new GString(newValues) { public String[] getStrings() { return newStrings; } }; } public GString plus(String that) { String[] currentStrings = getStrings(); String[] newStrings; Object[] newValues; boolean appendToLastString = currentStrings.length > getValues().length; if (appendToLastString) { newStrings = new String[currentStrings.length]; } else { newStrings = new String[currentStrings.length + 1]; } newValues = new Object[getValues().length]; int lastIndex = currentStrings.length; System.arraycopy(currentStrings, 0, newStrings, 0, lastIndex); System.arraycopy(getValues(), 0, newValues, 0, getValues().length); if (appendToLastString) { newStrings[lastIndex - 1] += that; } else { newStrings[lastIndex] = that; } final String[] finalStrings = newStrings; return new GString(newValues) { public String[] getStrings() { return finalStrings; } }; } public int getValueCount() { return values.length; } public Object getValue(int idx) { return values[idx]; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new StringWriterIOException(e); } return buffer.toString(); } public Writer writeTo(Writer out) throws IOException { String[] s = getStrings(); int numberOfValues = values.length; for (int i = 0, size = s.length; i < size; i++) { out.write(s[i]); if (i < numberOfValues) { final Object value = values[i]; if (value instanceof Closure) { final Closure c = (Closure) value; if (c.getMaximumNumberOfParameters() == 0) { InvokerHelper.write(out, c.call()); } else if (c.getMaximumNumberOfParameters() == 1) { c.call(out); } else { throw new GroovyRuntimeException("Trying to evaluate a GString containing a Closure taking " + c.getMaximumNumberOfParameters() + " parameters"); } } else { InvokerHelper.write(out, value); } } } return out; } /* (non-Javadoc) * @see groovy.lang.Buildable#build(groovy.lang.GroovyObject) */ public void build(final GroovyObject builder) { final String[] s = getStrings(); final int numberOfValues = values.length; for (int i = 0, size = s.length; i < size; i++) { builder.getProperty("mkp"); builder.invokeMethod("yield", new Object[]{s[i]}); if (i < numberOfValues) { builder.getProperty("mkp"); builder.invokeMethod("yield", new Object[]{values[i]}); } } } public boolean equals(Object that) { if (that instanceof GString) { return equals((GString) that); } return false; } public boolean equals(GString that) { return toString().equals(that.toString()); } public int hashCode() { return 37 + toString().hashCode(); } public int compareTo(Object that) { return toString().compareTo(that.toString()); } public char charAt(int index) { return toString().charAt(index); } public int length() { return toString().length(); } public CharSequence subSequence(int start, int end) { return toString().subSequence(start, end); } /** * Turns a String into a regular expression pattern * * @return the regular expression pattern */ public Pattern negate() { return DefaultGroovyMethods.bitwiseNegate(toString()); } } groovy-1.8.6/src/main/groovy/lang/GroovyResourceLoader.java0000644001501200150120000000217711627206700023351 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.net.URL; import java.net.MalformedURLException; /** * Allows frameworks that integrate with Groovy to determine how Groovy files are resolved. * * @author Steven Devijver */ public interface GroovyResourceLoader { /** * Loads a Groovy source file given its name. * * @param filename name of the file * @return a URL * @throws java.net.MalformedURLException if the URL is invalid */ URL loadGroovySource(String filename) throws MalformedURLException; } groovy-1.8.6/src/main/groovy/lang/IntRange.java0000644001501200150120000002362111707612044020732 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.IteratorClosureAdapter; import java.math.BigInteger; import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Represents a list of Integer objects from a specified int up (or down) to and including * a given to.

    *

    * This class is a copy of {@link ObjectRange} optimized for int. If you make any * changes to this class, you might consider making parallel changes to {@link ObjectRange}. * * @author James Strachan * @version $Revision$ */ public class IntRange extends AbstractList implements Range { /** * Iterates through each number in an IntRange. */ private class IntRangeIterator implements Iterator { /** * Counts from 0 up to size - 1. */ private int index; /** * The number of values in the range. */ private int size = size(); /** * The next value to return. */ private int value = reverse ? to : from; /** * {@inheritDoc} */ public boolean hasNext() { return index < size; } /** * {@inheritDoc} */ public Integer next() { if (index++ > 0) { if (index > size) { return null; } else { if (reverse) { --value; } else { ++value; } } } return Integer.valueOf(value); } /** * Not supported. * * @throws java.lang.UnsupportedOperationException * always */ public void remove() { IntRange.this.remove(index); } } /** * The first number in the range. from is always less than or equal to to. */ private int from; /** * The last number in the range. to is always greater than or equal to from. */ private int to; /** * If false, counts up from from to to. Otherwise, counts down * from to to from. */ private boolean reverse; /** * Creates a new IntRange. If from is greater * than to, a reverse range is created with * from and to swapped. * * @param from the first number in the range. * @param to the last number in the range. * @throws IllegalArgumentException if the range would contain more than * {@link Integer#MAX_VALUE} values. */ public IntRange(int from, int to) { if (from > to) { this.from = to; this.to = from; this.reverse = true; } else { this.from = from; this.to = to; } // size() an integer so ranges can have no more than Integer.MAX_VALUE elements if (this.to - this.from >= Integer.MAX_VALUE) { throw new IllegalArgumentException("range must have no more than " + Integer.MAX_VALUE + " elements"); } } /** * Creates a new IntRange. * * @param from the first value in the range. * @param to the last value in the range. * @param reverse true if the range should count from * to to from. * @throws IllegalArgumentException if from is greater than to. */ protected IntRange(int from, int to, boolean reverse) { if (from > to) { throw new IllegalArgumentException("'from' must be less than or equal to 'to'"); } this.from = from; this.to = to; this.reverse = reverse; } /** * Determines if this object is equal to another object. Delegates to * {@link AbstractList#equals(Object)} if that is anything * other than an {@link IntRange}. *

    *

    * It is not necessary to override hashCode, as * {@link AbstractList#hashCode()} provides a suitable hash code.

    *

    * Note that equals is generally handled by {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#equals(List,List)} * instead of this method. * * @param that the object to compare * @return true if the objects are equal */ public boolean equals(Object that) { return that instanceof IntRange ? equals((IntRange) that) : super.equals(that); } /** * Compares an {@link IntRange} to another {@link IntRange}. * * @param that the object to compare for equality * @return true if the ranges are equal */ public boolean equals(IntRange that) { return that != null && this.reverse == that.reverse && this.from == that.from && this.to == that.to; } /** * {@inheritDoc} */ public Comparable getFrom() { return Integer.valueOf(from); } /** * {@inheritDoc} */ public Comparable getTo() { return Integer.valueOf(to); } /** * Gets the 'from' value as an integer. * * @return the 'from' value as an integer. */ public int getFromInt() { return from; } /** * Gets the 'to' value as an integer. * * @return the 'to' value as an integer. */ public int getToInt() { return to; } /** * {@inheritDoc} */ public boolean isReverse() { return reverse; } public boolean containsWithinBounds(Object o) { return contains(o); } /** * {@inheritDoc} */ public Integer get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } if (index >= size()) { throw new IndexOutOfBoundsException("Index: " + index + " too big for range: " + this); } int value = reverse ? to - index : index + from; return Integer.valueOf(value); } /** * {@inheritDoc} */ public int size() { return to - from + 1; } /** * {@inheritDoc} */ public Iterator iterator() { return new IntRangeIterator(); } /** * {@inheritDoc} */ public List subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (toIndex > size()) { throw new IndexOutOfBoundsException("toIndex = " + toIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange(Integer.valueOf(from)); } return new IntRange(fromIndex + this.from, toIndex + this.from - 1, reverse); } /** * {@inheritDoc} */ public String toString() { return reverse ? "" + to + ".." + from : "" + from + ".." + to; } /** * {@inheritDoc} */ public String inspect() { return toString(); } /** * {@inheritDoc} */ public boolean contains(Object value) { if (value instanceof Integer) { Integer integer = (Integer) value; int i = integer.intValue(); return i >= from && i <= to; } if (value instanceof BigInteger) { BigInteger bigint = (BigInteger) value; return bigint.compareTo(BigInteger.valueOf(from)) >= 0 && bigint.compareTo(BigInteger.valueOf(to)) <= 0; } return false; } /** * {@inheritDoc} */ public boolean containsAll(Collection other) { if (other instanceof IntRange) { final IntRange range = (IntRange) other; return this.from <= range.from && range.to <= this.to; } return super.containsAll(other); } /** * {@inheritDoc} */ public void step(int step, Closure closure) { if (step == 0) { if (from != to) { throw new GroovyRuntimeException("Infinite loop detected due to step size of 0"); } else { return; // from == to and step == 0, nothing to do, so return } } if (reverse) { step = -step; } if (step > 0) { int value = from; while (value <= to) { closure.call(Integer.valueOf(value)); value = value + step; } } else { int value = to; while (value >= from) { closure.call(Integer.valueOf(value)); value = value + step; } } } /** * {@inheritDoc} */ public List step(int step) { IteratorClosureAdapter adapter = new IteratorClosureAdapter(this); step(step, adapter); return adapter.asList(); } } groovy-1.8.6/src/main/groovy/lang/AdaptingMetaClass.java0000644001501200150120000000223511627206700022544 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * An interface for MetaClass instances that "adapt" other MetaClass instances such as a proxy or * delegating MetaClass. * * @author Graeme Rocher * @since 1.5 */ public interface AdaptingMetaClass extends MetaClass { /** * Returns the MetaClass that this adapter adapts * * @return The MetaClass instance */ MetaClass getAdaptee(); /** * Sets the MetaClass adapted by this MetaClass * * @param metaClass The MetaClass to adapt */ void setAdaptee(MetaClass metaClass); } groovy-1.8.6/src/main/groovy/lang/Buildable.java0000644001501200150120000000131111627206700021075 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; public interface Buildable { void build(GroovyObject builder); } groovy-1.8.6/src/main/groovy/lang/Interceptor.java0000644001501200150120000000415311627206700021517 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Implementers of this interface can be registered in the ProxyMetaClass for * notifications about method calls for objects managed by the ProxyMetaClass. * See groovy/lang/InterceptorTest.groovy for details. * @author Dierk Koenig */ public interface Interceptor { /** * This code is executed before the method is optionally called. * @param object receiver object for the method call * @param methodName name of the method to call * @param arguments arguments to the method call * @return any arbitrary result that replaces the result of the * original method call only if doInvoke() returns false and afterInvoke() * relays this result. */ Object beforeInvoke(Object object, String methodName, Object[] arguments); /** * This code is executed after the method is optionally called. * @param object receiver object for the called method * @param methodName name of the called method * @param arguments arguments to the called method * @param result result of the executed method call or result of beforeInvoke if method was not called * @return any arbitrary result that can replace the result of the * original method call. Typically, the result parameter is returned. */ Object afterInvoke(Object object, String methodName, Object[] arguments, Object result); /** * @return whether the target method should be invoked at all. */ boolean doInvoke(); } groovy-1.8.6/src/main/groovy/lang/PackageScope.java0000644001501200150120000000304711715031256021547 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class or field annotation used for turning off Groovy's auto property * conversion of default or package scoped fields. Place it on the field(s) * of interest or on the class to apply for all package-scoped fields. * * This transformation is normally only used in conjunction with a third-party * library or framework which requires package scoping. * * @author Paul King * @deprecated use groovy.transform.PackageScope */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.PackageScopeASTTransformation") @Deprecated public @interface PackageScope { }groovy-1.8.6/src/main/groovy/lang/GroovySystem.java0000644001501200150120000000563111707612044021716 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl; import org.codehaus.groovy.util.ReferenceBundle; import org.codehaus.groovy.util.ReleaseInfo; public final class GroovySystem { // // TODO: make this initialization able to set useReflection true // TODO: have some way of specifying another MetaClass Registry implementation // static { USE_REFLECTION = true; META_CLASS_REGISTRY = new MetaClassRegistryImpl(); } /** * The MetaClass for java.lang.Object */ private static MetaClass objectMetaClass; /** * If true then the MetaClass will only use reflection for method dispatch, property access, etc. */ private static final boolean USE_REFLECTION; /** * Reference to the MetaClass Registry to be used by the Groovy run time system to map classes to MetaClasses */ private static final MetaClassRegistry META_CLASS_REGISTRY; private static boolean keepJavaMetaClasses=false; private GroovySystem() { // Do not allow this class to be instantiated } public static boolean isUseReflection() { return USE_REFLECTION; } public static MetaClassRegistry getMetaClassRegistry() { return META_CLASS_REGISTRY; } public static void setKeepJavaMetaClasses(boolean keepJavaMetaClasses) { GroovySystem.keepJavaMetaClasses = keepJavaMetaClasses; } public static boolean isKeepJavaMetaClasses() { return keepJavaMetaClasses; } /** * This method can be used to ensure that no threaded created * by a reference manager will be active. This is useful if the Groovy * runtime itself is loaded through a class loader which should be disposed * off. Without calling this method and if a threaded reference manager is * active the class loader cannot be unloaded! * * Per default no threaded manager will be used. * * @since 1.6 */ public static void stopThreadedReferenceManager() { ReferenceBundle.getSoftBundle().getManager().stopThread(); ReferenceBundle.getWeakBundle().getManager().stopThread(); } /** * Returns the groovy version */ public static String getVersion() { return ReleaseInfo.getVersion(); } } groovy-1.8.6/src/main/groovy/lang/MutableMetaClass.java0000644001501200150120000000504311627206700022406 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.reflect.Method; /** *

    An interface that defines methods that implementers of mutable Meta classes should specify. It provides operations to perform mutations * on the MetaClass instance.

    * *

    Whether a MetaClass allows mutation is up to the MetaClass itself and considerations of Thread safety * need to be taken into account when making a MetaClass mutable

    * *

    The default implementation allows mutation of MetaClass instances before initialisation (before the initialize() method is called) * but not after, thus ensuring Thread safety once a MetaClass has been constructed and placed in the registry

    * * @see MetaClassImpl * @see MetaClass * * @author Graeme Rocher * @since 1.5 */ public interface MutableMetaClass extends MetaClass { /** * Return whether the MetaClass has been modified or not * @return True if it has */ boolean isModified(); /** * adds a new instance method to this MetaClass. Instance * methods are able to overwrite the original methods of the * class. Calling this method should not be done after * initialise was called. * * @param method the method to be added */ void addNewInstanceMethod(Method method); /** * adds a new static method to this MetaClass. This is only * possible as long as initialise was not called. * * @param method the method to be added */ void addNewStaticMethod(Method method); /** * Adds a new MetaMethod to the MetaClass * * @param metaMethod The MetaMethod to add */ void addMetaMethod(MetaMethod metaMethod); /** * Adds a new MetaBeanProperty to the MetaClass * * @param metaBeanProperty The MetaBeanProperty instance */ void addMetaBeanProperty(MetaBeanProperty metaBeanProperty); // TODO: Add methods like addMetaConstructor, addMetaAttribute, addMetaAnnotation etc. } groovy-1.8.6/src/main/groovy/lang/GroovyClassLoader.java0000644001501200150120000010766111715031256022633 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @todo multi threaded compiling of the same class but with different roots * for compilation... T1 compiles A, which uses B, T2 compiles B... mark A and B * as parsed and then synchronize compilation. Problems: How to synchronize? * How to get error messages? * */ package groovy.lang; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.*; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import java.io.*; import java.net.*; import java.security.*; import java.util.*; /** * A ClassLoader which can load Groovy classes. The loaded classes are cached, * classes from other classloaders should not be cached. To be able to load a * script that was asked for earlier but was created later it is essential not * to keep anything like a "class not found" information for that class name. * This includes possible parent loaders. Classes that are not cached are always * reloaded. * * @author James Strachan * @author Guillaume Laforge * @author Steve Goetze * @author Bing Ran * @author Scott Stirling * @author Jochen Theodorou * @version $Revision$ */ public class GroovyClassLoader extends URLClassLoader { /** * this cache contains the loaded classes or PARSING, if the class is currently parsed */ protected final Map classCache = new HashMap(); /** * This cache contains mappings of file name to class. It is used * to bypass compilation. */ protected final Map sourceCache = new HashMap(); private final CompilerConfiguration config; private Boolean recompile; // use 1000000 as offset to avoid conflicts with names form the GroovyShell private static int scriptNameCounter = 1000000; private GroovyResourceLoader resourceLoader = new GroovyResourceLoader() { public URL loadGroovySource(final String filename) throws MalformedURLException { return AccessController.doPrivileged(new PrivilegedAction() { public URL run() { for (String extension : config.getScriptExtensions()) { try { URL ret = getSourceFile(filename, extension); if (ret != null) return ret; } catch (Throwable t) { // } } return null; } }); } }; /** * creates a GroovyClassLoader using the current Thread's context * Class loader as parent. */ public GroovyClassLoader() { this(Thread.currentThread().getContextClassLoader()); } /** * creates a GroovyClassLoader using the given ClassLoader as parent */ public GroovyClassLoader(ClassLoader loader) { this(loader, null); } /** * creates a GroovyClassLoader using the given GroovyClassLoader as parent. * This loader will get the parent's CompilerConfiguration */ public GroovyClassLoader(GroovyClassLoader parent) { this(parent, parent.config, false); } /** * creates a GroovyClassLoader. * * @param parent the parent class loader * @param config the compiler configuration * @param useConfigurationClasspath determines if the configurations classpath should be added */ public GroovyClassLoader(ClassLoader parent, CompilerConfiguration config, boolean useConfigurationClasspath) { super(new URL[0], parent); if (config == null) config = CompilerConfiguration.DEFAULT; this.config = config; if (useConfigurationClasspath) { for (String path : config.getClasspath()) { this.addClasspath(path); } } } /** * creates a GroovyClassLoader using the given ClassLoader as parent. */ public GroovyClassLoader(ClassLoader loader, CompilerConfiguration config) { this(loader, config, true); } public void setResourceLoader(GroovyResourceLoader resourceLoader) { if (resourceLoader == null) { throw new IllegalArgumentException("Resource loader must not be null!"); } this.resourceLoader = resourceLoader; } public GroovyResourceLoader getResourceLoader() { return resourceLoader; } /** * Loads the given class node returning the implementation Class * * @param classNode * @return a class * @deprecated */ public Class defineClass(ClassNode classNode, String file) { //return defineClass(classNode, file, "/groovy/defineClass"); throw new DeprecationException("the method GroovyClassLoader#defineClass(ClassNode, String) is no longer used and removed"); } /** * Loads the given class node returning the implementation Class. *

    * WARNING: this compilation is not synchronized * * @param classNode * @return a class */ public Class defineClass(ClassNode classNode, String file, String newCodeBase) { CodeSource codeSource = null; try { codeSource = new CodeSource(new URL("file", "", newCodeBase), (java.security.cert.Certificate[]) null); } catch (MalformedURLException e) { //swallow } CompilationUnit unit = createCompilationUnit(config, codeSource); ClassCollector collector = createCollector(unit, classNode.getModule().getContext()); try { unit.addClassNode(classNode); unit.setClassgenCallback(collector); unit.compile(Phases.CLASS_GENERATION); definePackage(collector.generatedClass.getName()); return collector.generatedClass; } catch (CompilationFailedException e) { throw new RuntimeException(e); } } /** * Parses the given file into a Java class capable of being run * * @param file the file name to parse * @return the main class defined in the given script */ public Class parseClass(File file) throws CompilationFailedException, IOException { return parseClass(new GroovyCodeSource(file, config.getSourceEncoding())); } /** * Parses the given text into a Java class capable of being run * * @param text the text of the script/class to parse * @param fileName the file name to use as the name of the class * @return the main class defined in the given script */ public Class parseClass(final String text, final String fileName) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { return new GroovyCodeSource(text, fileName, "/groovy/script"); } }); gcs.setCachable(false); return parseClass(gcs); } /** * Parses the given text into a Java class capable of being run * * @param text the text of the script/class to parse * @return the main class defined in the given script */ public Class parseClass(String text) throws CompilationFailedException { return parseClass(text, "script" + System.currentTimeMillis() + Math.abs(text.hashCode()) + ".groovy"); } /** * Parses the given character stream into a Java class capable of being run * * @param in an InputStream * @return the main class defined in the given script * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Class parseClass(InputStream in) throws CompilationFailedException { return parseClass(in, generateScriptName()); } public synchronized String generateScriptName() { scriptNameCounter++; return "script" + scriptNameCounter + ".groovy"; } /** * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Class parseClass(final InputStream in, final String fileName) throws CompilationFailedException { // For generic input streams, provide a catch-all codebase of GroovyScript // Security for these classes can be administered via policy grants with // a codebase of file:groovy.script GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { try { String scriptText = config.getSourceEncoding() != null ? DefaultGroovyMethods.getText(in, config.getSourceEncoding()) : DefaultGroovyMethods.getText(in); return new GroovyCodeSource(scriptText, fileName, "/groovy/script"); } catch (IOException e) { throw new RuntimeException("Impossible to read the content of the input stream for file named: " + fileName, e); } } }); return parseClass(gcs); } public Class parseClass(GroovyCodeSource codeSource) throws CompilationFailedException { return parseClass(codeSource, codeSource.isCachable()); } /** * Parses the given code source into a Java class. If there is a class file * for the given code source, then no parsing is done, instead the cached class is returned. * * @param shouldCacheSource if true then the generated class will be stored in the source cache * @return the main class defined in the given script */ public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource) throws CompilationFailedException { Class answer; synchronized (sourceCache) { answer = sourceCache.get(codeSource.getName()); if (answer != null) return answer; if (shouldCacheSource) { answer = doParseClass(codeSource); sourceCache.put(codeSource.getName(), answer); } } if (!shouldCacheSource) answer = doParseClass(codeSource); return answer; } private Class doParseClass(GroovyCodeSource codeSource) { validate(codeSource); Class answer; // Was neither already loaded nor compiling, so compile and add to cache. CompilationUnit unit = createCompilationUnit(config, codeSource.getCodeSource()); SourceUnit su = null; if (codeSource.getFile() == null) { su = unit.addSource(codeSource.getName(), codeSource.getScriptText()); } else { su = unit.addSource(codeSource.getFile()); } ClassCollector collector = createCollector(unit, su); unit.setClassgenCallback(collector); int goalPhase = Phases.CLASS_GENERATION; if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT; unit.compile(goalPhase); answer = collector.generatedClass; String mainClass = su.getAST().getMainClassName(); for (Object o : collector.getLoadedClasses()) { Class clazz = (Class) o; String clazzName = clazz.getName(); definePackage(clazzName); setClassCacheEntry(clazz); if (clazzName.equals(mainClass)) answer = clazz; } return answer; } private void validate(GroovyCodeSource codeSource) { if (codeSource.getFile() == null) { if (codeSource.getScriptText() == null) { throw new IllegalArgumentException("Script text to compile cannot be null!"); } } } private void definePackage(String className) { int i = className.lastIndexOf('.'); if (i != -1) { String pkgName = className.substring(0, i); java.lang.Package pkg = getPackage(pkgName); if (pkg == null) { definePackage(pkgName, null, null, null, null, null, null, null); } } } /** * gets the currently used classpath. * * @return a String[] containing the file information of the urls * @see #getURLs() */ protected String[] getClassPath() { //workaround for Groovy-835 URL[] urls = getURLs(); String[] ret = new String[urls.length]; for (int i = 0; i < ret.length; i++) { ret[i] = urls[i].getFile(); } return ret; } /** * expands the classpath * * @param pathList an empty list that will contain the elements of the classpath * @param classpath the classpath specified as a single string * @deprecated */ protected void expandClassPath(List pathList, String base, String classpath, boolean isManifestClasspath) { throw new DeprecationException("the method groovy.lang.GroovyClassLoader#expandClassPath(List,String,String,boolean) is no longer used internally and removed"); } /** * A helper method to allow bytecode to be loaded. spg changed name to * defineClass to make it more consistent with other ClassLoader methods * * @deprecated */ protected Class defineClass(String name, byte[] bytecode, ProtectionDomain domain) { throw new DeprecationException("the method groovy.lang.GroovyClassLoader#defineClass(String,byte[],ProtectionDomain) is no longer used internally and removed"); } protected PermissionCollection getPermissions(CodeSource codeSource) { PermissionCollection perms; try { perms = super.getPermissions(codeSource); } catch (SecurityException e) { // We lied about our CodeSource and that makes URLClassLoader unhappy. perms = new Permissions(); } ProtectionDomain myDomain = AccessController.doPrivileged(new PrivilegedAction() { public ProtectionDomain run() { return getClass().getProtectionDomain(); } }); PermissionCollection myPerms = myDomain.getPermissions(); if (myPerms != null) { for (Enumeration elements = myPerms.elements(); elements.hasMoreElements();) { perms.add(elements.nextElement()); } } perms.setReadOnly(); return perms; } public static class InnerLoader extends GroovyClassLoader { private final GroovyClassLoader delegate; private final long timeStamp; public InnerLoader(GroovyClassLoader delegate) { super(delegate); this.delegate = delegate; timeStamp = System.currentTimeMillis(); } public void addClasspath(String path) { delegate.addClasspath(path); } public void clearCache() { delegate.clearCache(); } public URL findResource(String name) { return delegate.findResource(name); } public Enumeration findResources(String name) throws IOException { return delegate.findResources(name); } public Class[] getLoadedClasses() { return delegate.getLoadedClasses(); } public URL getResource(String name) { return delegate.getResource(name); } public InputStream getResourceAsStream(String name) { return delegate.getResourceAsStream(name); } public GroovyResourceLoader getResourceLoader() { return delegate.getResourceLoader(); } public URL[] getURLs() { return delegate.getURLs(); } public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript, boolean resolve) throws ClassNotFoundException, CompilationFailedException { Class c = findLoadedClass(name); if (c != null) return c; return delegate.loadClass(name, lookupScriptFiles, preferClassOverScript, resolve); } public Class parseClass(GroovyCodeSource codeSource, boolean shouldCache) throws CompilationFailedException { return delegate.parseClass(codeSource, shouldCache); } public void setResourceLoader(GroovyResourceLoader resourceLoader) { delegate.setResourceLoader(resourceLoader); } public void addURL(URL url) { delegate.addURL(url); } public long getTimeStamp() { return timeStamp; } } /** * creates a new CompilationUnit. If you want to add additional * phase operations to the CompilationUnit (for example to inject * additional methods, variables, fields), then you should overwrite * this method. * * @param config the compiler configuration, usually the same as for this class loader * @param source the source containing the initial file to compile, more files may follow during compilation * @return the CompilationUnit */ protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) { return new CompilationUnit(config, source, this); } /** * creates a ClassCollector for a new compilation. * * @param unit the compilationUnit * @param su the SourceUnit * @return the ClassCollector */ protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { InnerLoader loader = AccessController.doPrivileged(new PrivilegedAction() { public InnerLoader run() { return new InnerLoader(GroovyClassLoader.this); } }); return new ClassCollector(loader, unit, su); } public static class ClassCollector extends CompilationUnit.ClassgenCallback { private Class generatedClass; private final GroovyClassLoader cl; private final SourceUnit su; private final CompilationUnit unit; private final Collection loadedClasses; protected ClassCollector(InnerLoader cl, CompilationUnit unit, SourceUnit su) { this.cl = cl; this.unit = unit; this.loadedClasses = new ArrayList(); this.su = su; } public GroovyClassLoader getDefiningClassLoader() { return cl; } protected Class createClass(byte[] code, ClassNode classNode) { GroovyClassLoader cl = getDefiningClassLoader(); Class theClass = cl.defineClass(classNode.getName(), code, 0, code.length, unit.getAST().getCodeSource()); this.loadedClasses.add(theClass); if (generatedClass == null) { ModuleNode mn = classNode.getModule(); SourceUnit msu = null; if (mn != null) msu = mn.getContext(); ClassNode main = null; if (mn != null) main = (ClassNode) mn.getClasses().get(0); if (msu == su && main == classNode) generatedClass = theClass; } return theClass; } protected Class onClassNode(ClassWriter classWriter, ClassNode classNode) { byte[] code = classWriter.toByteArray(); return createClass(code, classNode); } public void call(ClassVisitor classWriter, ClassNode classNode) { onClassNode((ClassWriter) classWriter, classNode); } public Collection getLoadedClasses() { return this.loadedClasses; } } /** * open up the super class define that takes raw bytes */ public Class defineClass(String name, byte[] b) { return super.defineClass(name, b, 0, b.length); } /** * loads a class from a file or a parent classloader. * This method does call loadClass(String, boolean, boolean, boolean) * with the last parameter set to false. * * @throws CompilationFailedException if compilation was not successful */ public Class loadClass(final String name, boolean lookupScriptFiles, boolean preferClassOverScript) throws ClassNotFoundException, CompilationFailedException { return loadClass(name, lookupScriptFiles, preferClassOverScript, false); } /** * gets a class from the class cache. This cache contains only classes loaded through * this class loader or an InnerLoader instance. If no class is stored for a * specific name, then the method should return null. * * @param name of the class * @return the class stored for the given name * @see #removeClassCacheEntry(String) * @see #setClassCacheEntry(Class) * @see #clearCache() */ protected Class getClassCacheEntry(String name) { if (name == null) return null; synchronized (classCache) { return classCache.get(name); } } /** * sets an entry in the class cache. * * @param cls the class * @see #removeClassCacheEntry(String) * @see #getClassCacheEntry(String) * @see #clearCache() */ protected void setClassCacheEntry(Class cls) { synchronized (classCache) { classCache.put(cls.getName(), cls); } } /** * removes a class from the class cache. * * @param name of the class * @see #getClassCacheEntry(String) * @see #setClassCacheEntry(Class) * @see #clearCache() */ protected void removeClassCacheEntry(String name) { synchronized (classCache) { classCache.remove(name); } } /** * adds a URL to the classloader. * * @param url the new classpath element */ public void addURL(URL url) { super.addURL(url); } /** * Indicates if a class is recompilable. Recompilable means, that the classloader * will try to locate a groovy source file for this class and then compile it again, * adding the resulting class as entry to the cache. Giving null as class is like a * recompilation, so the method should always return true here. Only classes that are * implementing GroovyObject are compilable and only if the timestamp in the class * is lower than Long.MAX_VALUE. *

    * NOTE: First the parent loaders will be asked and only if they don't return a * class the recompilation will happen. Recompilation also only happen if the source * file is newer. * * @param cls the class to be tested. If null the method should return true * @return true if the class should be compiled again * @see #isSourceNewer(URL, Class) */ protected boolean isRecompilable(Class cls) { if (cls == null) return true; if (cls.getClassLoader() == this) return false; if (recompile == null && !config.getRecompileGroovySource()) return false; if (recompile != null && !recompile) return false; if (!GroovyObject.class.isAssignableFrom(cls)) return false; long timestamp = getTimeStamp(cls); if (timestamp == Long.MAX_VALUE) return false; return true; } /** * sets if the recompilation should be enable. There are 3 possible * values for this. Any value different than null overrides the * value from the compiler configuration. true means to recompile if needed * false means to never recompile. * * @param mode the recompilation mode * @see CompilerConfiguration */ public void setShouldRecompile(Boolean mode) { recompile = mode; } /** * gets the currently set recompilation mode. null means, the * compiler configuration is used. False means no recompilation and * true means that recompilation will be done if needed. * * @return the recompilation mode */ public Boolean isShouldRecompile() { return recompile; } /** * loads a class from a file or a parent classloader. * * @param name of the class to be loaded * @param lookupScriptFiles if false no lookup at files is done at all * @param preferClassOverScript if true the file lookup is only done if there is no class * @param resolve see {@link java.lang.ClassLoader#loadClass(java.lang.String, boolean)} * @return the class found or the class created from a file lookup * @throws ClassNotFoundException if the class could not be found * @throws CompilationFailedException if the source file could not be compiled */ public Class loadClass(final String name, boolean lookupScriptFiles, boolean preferClassOverScript, boolean resolve) throws ClassNotFoundException, CompilationFailedException { // look into cache Class cls = getClassCacheEntry(name); // enable recompilation? boolean recompile = isRecompilable(cls); if (!recompile) return cls; // try parent loader ClassNotFoundException last = null; try { Class parentClassLoaderClass = super.loadClass(name, resolve); // always return if the parent loader was successful if (cls != parentClassLoaderClass) return parentClassLoaderClass; } catch (ClassNotFoundException cnfe) { last = cnfe; } catch (NoClassDefFoundError ncdfe) { if (ncdfe.getMessage().indexOf("wrong name") > 0) { last = new ClassNotFoundException(name); } else { throw ncdfe; } } // check security manager SecurityManager sm = System.getSecurityManager(); if (sm != null) { String className = name.replace('/', '.'); int i = className.lastIndexOf('.'); // no checks on the sun.reflect classes for reflection speed-up // in particular ConstructorAccessorImpl, MethodAccessorImpl, FieldAccessorImpl and SerializationConstructorAccessorImpl // which are generated at runtime by the JDK if (i != -1 && !className.startsWith("sun.reflect.")) { sm.checkPackageAccess(className.substring(0, i)); } } // prefer class if no recompilation if (cls != null && preferClassOverScript) return cls; // at this point the loading from a parent loader failed // and we want to recompile if needed. if (lookupScriptFiles) { // try groovy file try { // check if recompilation already happened. final Class classCacheEntry = getClassCacheEntry(name); if (classCacheEntry != cls) return classCacheEntry; URL source = resourceLoader.loadGroovySource(name); // if recompilation fails, we want cls==null Class oldClass = cls; cls = null; cls = recompile(source, name, oldClass); } catch (IOException ioe) { last = new ClassNotFoundException("IOException while opening groovy source: " + name, ioe); } finally { if (cls == null) { removeClassCacheEntry(name); } else { setClassCacheEntry(cls); } } } if (cls == null) { // no class found, there should have been an exception before now if (last == null) throw new AssertionError(true); throw last; } return cls; } /** * (Re)Compiles the given source. * This method starts the compilation of a given source, if * the source has changed since the class was created. For * this isSourceNewer is called. * * @param source the source pointer for the compilation * @param className the name of the class to be generated * @param oldClass a possible former class * @return the old class if the source wasn't new enough, the new class else * @throws CompilationFailedException if the compilation failed * @throws IOException if the source is not readable * @see #isSourceNewer(URL, Class) */ protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException { if (source != null) { // found a source, compile it if newer if ((oldClass != null && isSourceNewer(source, oldClass)) || (oldClass == null)) { synchronized (sourceCache) { sourceCache.remove(className); if (isFile(source)) { try { return doParseClass(new GroovyCodeSource(new File(source.toURI()), config.getSourceEncoding())); } catch (URISyntaxException e) { // do nothing and fall back to the other version } } return parseClass(source.openStream(), makeFileName(className)); } } } return oldClass; } private String makeFileName(String className) { className = className.replace('.','/'); return className+".groovy"; } /** * Implemented here to check package access prior to returning an * already loaded class. * * @throws CompilationFailedException if the compilation failed * @throws ClassNotFoundException if the class was not found * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) */ protected Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { return loadClass(name, true, true, resolve); } /** * gets the time stamp of a given class. For groovy * generated classes this usually means to return the value * of the static field __timeStamp. If the parameter doesn't * have such a field, then Long.MAX_VALUE is returned * * @param cls the class * @return the time stamp */ protected long getTimeStamp(Class cls) { return Verifier.getTimestamp(cls); } /** * This method will take a file name and try to "decode" any URL encoded characters. For example * if the file name contains any spaces this method call will take the resulting %20 encoded values * and convert them to spaces. *

    * This method was added specifically to fix defect: Groovy-1787. The defect involved a situation * where two scripts were sitting in a directory with spaces in its name. The code would fail * when the class loader tried to resolve the file name and would choke on the URLEncoded space values. */ private String decodeFileName(String fileName) { String decodedFile = fileName; try { decodedFile = URLDecoder.decode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { System.err.println("Encountered an invalid encoding scheme when trying to use URLDecoder.decode() inside of the GroovyClassLoader.decodeFileName() method. Returning the unencoded URL."); System.err.println("Please note that if you encounter this error and you have spaces in your directory you will run into issues. Refer to GROOVY-1787 for description of this bug."); } return decodedFile; } private boolean isFile(URL ret) { return ret != null && ret.getProtocol().equals("file"); } private File getFileForUrl(URL ret, String filename) { String fileWithoutPackage = filename; if (fileWithoutPackage.indexOf('/') != -1) { int index = fileWithoutPackage.lastIndexOf('/'); fileWithoutPackage = fileWithoutPackage.substring(index + 1); } return fileReallyExists(ret, fileWithoutPackage); } private File fileReallyExists(URL ret, String fileWithoutPackage) { File path = new File(decodeFileName(ret.getFile())).getParentFile(); if (path.exists() && path.isDirectory()) { File file = new File(path, fileWithoutPackage); if (file.exists()) { // file.exists() might be case insensitive. Let's do // case sensitive match for the filename File parent = file.getParentFile(); for (String child : parent.list()) { if (child.equals(fileWithoutPackage)) return file; } } } //file does not exist! return null; } private URL getSourceFile(String name, String extension) { String filename = name.replace('.', '/') + "." + extension; URL ret = getResource(filename); if (isFile(ret) && getFileForUrl(ret, filename) == null) return null; return ret; } private URL getSourceFile(String name) { return getSourceFile(name, config.getDefaultScriptExtension()); } /** * Decides if the given source is newer than a class. * * @param source the source we may want to compile * @param cls the former class * @return true if the source is newer, false else * @throws IOException if it is not possible to open an * connection for the given source * @see #getTimeStamp(Class) */ protected boolean isSourceNewer(URL source, Class cls) throws IOException { long lastMod; // Special handling for file:// protocol, as getLastModified() often reports // incorrect results (-1) if (isFile(source)) { // Coerce the file URL to a File String path = source.getPath().replace('/', File.separatorChar).replace('|', ':'); File file = new File(path); lastMod = file.lastModified(); } else { URLConnection conn = source.openConnection(); lastMod = conn.getLastModified(); conn.getInputStream().close(); } long classTime = getTimeStamp(cls); return classTime + config.getMinimumRecompilationInterval() < lastMod; } /** * adds a classpath to this classloader. * * @param path is a jar file or a directory. * @see #addURL(URL) */ public void addClasspath(final String path) { AccessController.doPrivileged(new PrivilegedAction() { public Void run() { try { File f = new File(path); URL newURL = f.toURI().toURL(); URL[] urls = getURLs(); for (URL url : urls) { if (url.equals(newURL)) return null; } addURL(newURL); } catch (MalformedURLException e) { //TODO: fail through ? } return null; } }); } /** *

    Returns all Groovy classes loaded by this class loader. * * @return all classes loaded by this class loader */ public Class[] getLoadedClasses() { synchronized (classCache) { final Collection values = classCache.values(); return values.toArray(new Class[values.size()]); } } /** * Removes all classes from the class cache. * * @see #getClassCacheEntry(String) * @see #setClassCacheEntry(Class) * @see #removeClassCacheEntry(String) */ public void clearCache() { synchronized (classCache) { classCache.clear(); } synchronized (sourceCache) { sourceCache.clear(); } } } groovy-1.8.6/src/main/groovy/lang/MetaClassRegistryChangeEvent.java0000644001501200150120000000337611707612044024745 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.EventObject; /** * An event used to propagate meta class updates * * @author Jochen Theodorou */ public class MetaClassRegistryChangeEvent extends EventObject { private final Class clazz; private final Object instance; private final MetaClass metaClass; private final MetaClass oldMetaClass; public MetaClassRegistryChangeEvent(Object source, Object instance, Class clazz, MetaClass oldMetaClass, MetaClass newMetaClass) { super(source); this.clazz = clazz; this.metaClass = newMetaClass; this.oldMetaClass = oldMetaClass; this.instance = instance; } public Class getClassToUpdate() { return clazz; } public MetaClass getNewMetaClass() { return metaClass; } public MetaClass getOldMetaClass() { return oldMetaClass; } public boolean isPerInstanceMetaClassChange() { return instance!=null; } public Object getInstance() { return instance; } public MetaClassRegistry getRegistry() { return (MetaClassRegistry) source; } } groovy-1.8.6/src/main/groovy/lang/Mixin.java0000644001501200150120000000225111707612044020303 0ustar miguelmiguel/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Provides a mechanism for mixing in methods into a class. * * @author Alex Tkachman */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) @GroovyASTTransformationClass("org.codehaus.groovy.ast.MixinASTTransformation") public @interface Mixin { Class [] value (); } groovy-1.8.6/src/main/groovy/lang/GroovyInterceptable.java0000644001501200150120000000160311627206700023205 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Marker interface used to notify that all methods should be intercepted through the invokeMethod mechanism * of GroovyObject. * * @author Guillaume Laforge */ public interface GroovyInterceptable extends GroovyObject { } groovy-1.8.6/src/main/groovy/lang/GroovyCodeSource.java0000644001501200150120000002370611715031256022467 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import groovy.security.GroovyCodeSourcePermission; import groovy.util.CharsetToolkit; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.cert.Certificate; import org.codehaus.groovy.runtime.DefaultGroovyMethods; /** * CodeSource wrapper class that allows specific security policies to be associated with a class * compiled from groovy source. * * @author Steve Goetze * @author Guillaume Laforge * @author Merlyn Albery-Speyer */ public class GroovyCodeSource { /** * The codeSource to be given the generated class. This can be used by policy file * grants to administer security. */ private CodeSource codeSource; /** * The name given to the generated class */ private String name; /** * The groovy source to be compiled and turned into a class */ private String scriptText; /** * The certificates used to sign the items from the codesource */ Certificate[] certs; private boolean cachable; private File file; public GroovyCodeSource(String script, String name, String codeBase) { this.name = name; this.scriptText = script; this.codeSource = createCodeSource(codeBase); this.cachable = true; } /** * Construct a GroovyCodeSource for an inputStream of groovyCode that has an * unknown provenance -- meaning it didn't come from a File or a URL (e.g. a String). * The supplied codeBase will be used to construct a File URL that should match up * with a java Policy entry that determines the grants to be associated with the * class that will be built from the InputStream. *

    * The permission groovy.security.GroovyCodeSourcePermission will be used to determine if the given codeBase * may be specified. That is, the current Policy set must have a GroovyCodeSourcePermission that implies * the codeBase, or an exception will be thrown. This is to prevent callers from hijacking * existing codeBase policy entries unless explicitly authorized by the user. */ public GroovyCodeSource(Reader reader, String name, String codeBase) { this.name = name; this.codeSource = createCodeSource(codeBase); try { this.scriptText = DefaultGroovyMethods.getText(reader); } catch (IOException e) { throw new RuntimeException("Impossible to read the text content from that reader, for script: " + name + " with codeBase: " + codeBase, e); } } /** * Construct a GroovyCodeSource for an inputStream of groovyCode that has an * unknown provenance -- meaning it didn't come from a File or a URL (e.g. a String). * The supplied codeBase will be used to construct a File URL that should match up * with a java Policy entry that determines the grants to be associated with the * class that will be built from the InputStream. *

    * The permission groovy.security.GroovyCodeSourcePermission will be used to determine if the given codeBase * may be specified. That is, the current Policy set must have a GroovyCodeSourcePermission that implies * the codeBase, or an exception will be thrown. This is to prevent callers from hijacking * existing codeBase policy entries unless explicitly authorized by the user. * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ @Deprecated public GroovyCodeSource(InputStream inputStream, String name, String codeBase) { this.name = name; this.codeSource = createCodeSource(codeBase); try { this.scriptText = DefaultGroovyMethods.getText(inputStream); } catch (IOException e) { throw new RuntimeException("Impossible to read the text content from that input stream, for script: " + name + " with codeBase: " + codeBase, e); } } public GroovyCodeSource(final File infile, final String encoding) throws IOException { // avoid files which confuse us like ones with .. in path final File file = new File(infile.getCanonicalPath()); if (!file.exists()) { throw new FileNotFoundException(file.toString() + " (" + file.getAbsolutePath() + ")"); } if (file.isDirectory()) { throw new IllegalArgumentException(file.toString() + " (" + file.getAbsolutePath() + ") is a directory not a Groovy source file."); } try { if (!file.canRead()) throw new RuntimeException(file.toString() + " can not be read. Check the read permission of the file \"" + file.toString() + "\" (" + file.getAbsolutePath() + ")."); } catch (SecurityException e) { throw e; } this.file = file; this.cachable = true; //The calls below require access to user.dir - allow here since getName() and getCodeSource() are //package private and used only by the GroovyClassLoader. try { Object[] info = AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object[] run() throws IOException { // retrieve the content of the file using the provided encoding if (encoding != null) { scriptText = DefaultGroovyMethods.getText(infile, encoding); } else { scriptText = DefaultGroovyMethods.getText(infile); } Object[] info = new Object[2]; URL url = file.toURI().toURL(); info[0] = url.toExternalForm(); //toURI().toURL() will encode, but toURL() will not. info[1] = new CodeSource(url, (Certificate[]) null); return info; } }); this.name = (String) info[0]; this.codeSource = (CodeSource) info[1]; } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (cause != null && cause instanceof IOException) { throw (IOException) cause; } throw new RuntimeException("Could not construct CodeSource for file: " + file, cause); } } /** * @param infile the file to create a GroovyCodeSource for. * @throws IOException if an issue arises opening and reading the file. */ public GroovyCodeSource(final File infile) throws IOException { this(infile, CharsetToolkit.getDefaultSystemCharset().name()); } public GroovyCodeSource(URL url) throws IOException { if (url == null) { throw new RuntimeException("Could not construct a GroovyCodeSource from a null URL"); } this.name = url.toExternalForm(); this.codeSource = new CodeSource(url, (java.security.cert.Certificate[]) null); try { String contentEncoding = url.openConnection().getContentEncoding(); if (contentEncoding != null) { this.scriptText = DefaultGroovyMethods.getText(url, contentEncoding); } else { this.scriptText = DefaultGroovyMethods.getText(url); // falls-back on default encoding } } catch (IOException e) { throw new RuntimeException("Impossible to read the text content from " + name, e); } } CodeSource getCodeSource() { return codeSource; } /** * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ @Deprecated public InputStream getInputStream() { IOException ioe; if (file == null) { try { return new ByteArrayInputStream(scriptText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { ioe = e; } } else { try { return new FileInputStream(file); } catch (FileNotFoundException e) { ioe = e; } } String errorMsg = "Impossible to read the bytes from the associated script: " + scriptText + " with name: " + name; if (ioe != null) { throw new RuntimeException(errorMsg, ioe); } else { throw new RuntimeException(errorMsg); } } public String getScriptText() { return scriptText; } public String getName() { return name; } public File getFile() { return file; } public void setCachable(boolean b) { cachable = b; } public boolean isCachable() { return cachable; } private static CodeSource createCodeSource(final String codeBase) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new GroovyCodeSourcePermission(codeBase)); } try { return new CodeSource(new URL("file", "", codeBase), (java.security.cert.Certificate[]) null); } catch (MalformedURLException e) { throw new RuntimeException("A CodeSource file URL cannot be constructed from the supplied codeBase: " + codeBase); } } } groovy-1.8.6/src/main/groovy/lang/GrabConfig.java0000644001501200150120000000662011707612044021224 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to modify the grape configuration for grab requests. *

    * An example involving databases: *

     * {@code @Grab}('mysql:mysql-connector-java:5.1.6'),
     * {@code @GrabConfig}(systemClassLoader=true)
     * import groovy.sql.Sql
     *
     * def sql=Sql.newInstance("jdbc:mysql://localhost/test", "user", "password", "com.mysql.jdbc.Driver")
     * println sql.firstRow('SELECT * FROM INFORMATION_SCHEMA.COLUMNS')
     * 
    * Another example involving XStream: *
     * {@code @Grapes}([
     *     {@code @Grab}('com.thoughtworks.xstream:xstream:1.3.1'),
     *     {@code @Grab}('xpp3:xpp3_min:1.1.4c'),
     *     {@code @GrabConfig}(systemClassLoader=true, initContextClassLoader=true)
     * ])
     * import com.thoughtworks.xstream.*
     *
     * class Staff {
     *     String firstname, lastname, position
     * }
     *
     * def xstream = new XStream()
     * def john1 = new Staff(firstname:'John',
     *                      lastname:'Connor',
     *                      position:'Resistance Leader')
     *
     * // write out to XML file
     * new File("john.xml").withOutputStream { out ->
     *     xstream.toXML(john1, out)
     * }
     *
     * // now read back in
     * def john2
     * new File("john.xml").withInputStream { ins ->
     *     john2 = xstream.fromXML(ins)
     * }
     *
     * println john2.dump()
     * 
    *

    * Further information about customising grape behavior can be found on the Grape documentation page: * http://groovy.codehaus.org/Grape. */ @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) public @interface GrabConfig { /** * Set to true if you want to use the system classloader when loading the grape. * This is normally only required when a core Java class needs to reference the grabbed * classes, e.g. for a database driver accessed using DriverManager. */ boolean systemClassLoader() default false; /** * Set to true if you want the context classloader to be initialised to the classloader * of the current class or script. This is useful for libraries or frameworks that assume * that the context classloader has been set. But be careful when using this flag as your * script or class might behave differently when called directly (from the command line or * from an IDE) versus when called from within a container, e.g. a web container or a JEE container. */ boolean initContextClassLoader() default false; }groovy-1.8.6/src/main/groovy/lang/MissingClassException.java0000644001501200150120000000315211627206700023475 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassNode; /** * An exception occurred if a dynamic method dispatch fails with an unknown class. * * Note that the Missing*Exception classes were named for consistency and * to avoid conflicts with JDK exceptions of the same name. * * @author James Strachan * @version $Revision$ */ public class MissingClassException extends GroovyRuntimeException { private final String type; public MissingClassException(String type, ASTNode node, String message) { super("No such class: " + type + " " + message, node); this.type = type; } public MissingClassException(ClassNode type, String message){ super("No such class: " + type.getName() + " " + message); this.type = type.getName(); } /** * * @return The type that could not be resolved */ public String getType() { return type; } } groovy-1.8.6/src/main/groovy/lang/ParameterArray.java0000644001501200150120000000237111627206700022140 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Distinguish a parameter array from Object[]. * * @author Pilho Kim * @version $Revision$ */ public class ParameterArray { private Object parameters; public ParameterArray(Object data) { parameters = packArray(data); } private Object packArray(Object object) { if (object instanceof Object[]) return (Object[]) object; else return object; } public Object get() { return parameters; } public String toString() { if (parameters == null) return ""; return parameters.toString(); } } groovy-1.8.6/src/main/groovy/lang/package.html0000644001501200150120000000031111627206700020627 0ustar miguelmiguel package groovy.lang.*

    Core Groovy language classes for implementing data structures, closures, metadata and so forth.

    groovy-1.8.6/src/main/groovy/lang/MapWithDefault.java0000644001501200150120000000472111627206700022100 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.Collection; import java.util.Map; import java.util.Set; /** * A wrapper for Map which allows a default value to be specified. * * @author Paul King * @since 1.7.1 */ public final class MapWithDefault implements Map { private final Map delegate; private final Closure initClosure; private MapWithDefault(Map m, Closure initClosure) { delegate = m; this.initClosure = initClosure; } public static Map newInstance(Map m, Closure initClosure) { return new MapWithDefault(m, initClosure); } public int size() { return delegate.size(); } public boolean isEmpty() { return delegate.isEmpty(); } public boolean containsKey(Object key) { return delegate.containsKey(key); } public boolean containsValue(Object value) { return delegate.containsValue(value); } public V get(Object key) { if (!delegate.containsKey(key)) { delegate.put((K)key, (V)initClosure.call(new Object[]{key})); } return delegate.get(key); } public V put(K key, V value) { return delegate.put(key, value); } public V remove(Object key) { return delegate.remove(key); } public void putAll(Map m) { delegate.putAll(m); } public void clear() { delegate.clear(); } public Set keySet() { return delegate.keySet(); } public Collection values() { return delegate.values(); } public Set> entrySet() { return delegate.entrySet(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } }groovy-1.8.6/src/main/groovy/lang/BenchmarkInterceptor.java0000644001501200150120000000642611707612044023340 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.*; /** * Interceptor that registers the timestamp of each method call * before and after invocation. The timestamps are stored internally * and can be retrieved through the with the
    getCalls()
    * and
    statistic()
    API.

    * * Example usage can be seen here: *
     * def proxy = ProxyMetaClass.getInstance(ArrayList.class)
     * proxy.interceptor = new BenchmarkInterceptor()
     * proxy.use {
     *     def list = (0..10000).collect{ it }
     *     4.times { list.size() }
     *     4000.times { list.set(it, it+1) }
     * }
     * proxy.interceptor.statistic()
     * 
    * Which produces the following output: *
     * [[size, 4, 0], [set, 4000, 21]]
     * 
    */ public class BenchmarkInterceptor implements Interceptor { protected Map calls = new LinkedHashMap(); // keys to list of invocation times and before and after /** * Returns the raw data associated with the current benchmark run. */ public Map getCalls() { return calls; } /** * Resets all the benchmark data on this object. */ public void reset() { calls = new HashMap(); } public Object beforeInvoke(Object object, String methodName, Object[] arguments) { if (!calls.containsKey(methodName)) calls.put(methodName, new LinkedList()); ((List) calls.get(methodName)).add(new Long(System.currentTimeMillis())); return null; } public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) { ((List) calls.get(methodName)).add(new Long(System.currentTimeMillis())); return result; } public boolean doInvoke() { return true; } /** * Returns benchmark statistics as a List<Object[]>. * AccumulateTime is measured in milliseconds and is as accurate as * System.currentTimeMillis() allows it to be. * @return a list of lines, each item is [methodname, numberOfCalls, accumulatedTime] */ public List statistic() { List result = new LinkedList(); for (Iterator iter = calls.keySet().iterator(); iter.hasNext();) { Object[] line = new Object[3]; result.add(line); line[0] = iter.next(); List times = (List) calls.get(line[0]); line[1] = new Integer(times.size() / 2); int accTime = 0; for (Iterator it = times.iterator(); it.hasNext();) { Long start = (Long) it.next(); Long end = (Long) it.next(); accTime += end.longValue() - start.longValue(); } line[2] = new Long(accTime); } return result; } } groovy-1.8.6/src/main/groovy/lang/Immutable.java0000644001501200150120000001500611715031256021137 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Note: This class is Deprecated, please use groovy.transform.Immutable. *

    * Class annotation used to assist in the creation of immutable classes. *

    * It allows you to write classes in this shortened form: *

     * {@code @Immutable} class Customer {
     *     String first, last
     *     int age
     *     Date since
     *     Collection favItems
     * }
     * def d = new Date()
     * def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:d, favItems:['Books', 'Games'])
     * def c2 = new Customer('Tom', 'Jones', 21, d, ['Books', 'Games'])
     * assert c1 == c2
     * 
    * The {@code @Immutable} annotation instructs the compiler to execute an * AST transformation which adds the necessary getters, constructors, * equals, hashCode and other helper methods that are typically written * when creating immutable classes with the defined properties. *

    * A class created in this way has the following characteristics: *

      *
    • The class is automatically made final. *
    • Properties must be of an immutable type or a type with a strategy for handling non-immutable * characteristics. Specifically, the type must be one of the primitive or wrapper types, Strings, enums, * other {@code @Immutable} classes or known immutables (e.g. java.awt.Color, java.net.URI). Also handled are * Cloneable classes, collections, maps and arrays, and other "effectively immutable" classes with * special handling (e.g. java.util.Date). *
    • Properties automatically have private, final backing fields with getters. * Attempts to update the property will result in a {@code ReadOnlyPropertyException}. *
    • A map-based constructor is provided which allows you to set properties by name. *
    • A tuple-style constructor is provided which allows you to set properties in the same order as they are defined. *
    • Default {@code equals}, {@code hashCode} and {@code toString} methods are provided based on the property values. * Though not normally required, you may write your own implementations of these methods. For {@code equals} and {@code hashCode}, * if you do write your own method, it is up to you to obey the general contract for {@code equals} methods and supply * a corresponding matching {@code hashCode} method. * If you do provide one of these methods explicitly, the default implementation will be made available in a private * "underscore" variant which you can call. E.g., you could provide a (not very elegant) multi-line formatted * {@code toString} method for {@code Customer} above as follows: *
       *     String toString() {
       *        _toString().replaceAll(/\(/, '(\n\t').replaceAll(/\)/, '\n)').replaceAll(/, /, '\n\t')
       *    }
       * 
      * If an "underscore" version of the respective method already exists, then no default implementation is provided. *
    • {@code Date}s, {@code Cloneable}s and arrays are defensively copied on the way in (constructor) and out (getters). * Arrays and {@code Cloneable} objects use the {@code clone} method. For your own classes, * it is up to you to define this method and use deep cloning if appropriate. *
    • {@code Collection}s and {@code Map}s are wrapped by immutable wrapper classes (but not deeply cloned!). * Attempts to update them will result in an {@code UnsupportedOperationException}. *
    • Fields that are enums or other {@code @Immutable} classes are allowed but for an * otherwise possible mutable property type, an error is thrown. *
    • You don't have to follow Groovy's normal property conventions, e.g. you can create an explicit private field and * then you can write explicit get and set methods. Such an approach, isn't currently prohibited (to give you some * wiggle room to get around these conventions) but any fields created in this way are deemed not to be part of the * significant state of the object and aren't factored into the {@code equals} or {@code hashCode} methods. * Similarly, you may use static properties (though usually this is discouraged) and these too will be ignored * as far as significant state is concerned. If you do break standard conventions, you do so at your own risk and * your objects may no longer be immutable. It is up to you to ensure that your objects remain immutable at least * to the extent expected in other parts of your program! *
    *

    * Immutable classes are particularly useful for functional and concurrent styles of programming * and for use as key values within maps. *

    * Limitations: *

      *
    • * As outlined above, Arrays and {@code Cloneable} objects use the {@code clone} method. For your own classes, * it is up to you to define this method and use deep cloning if appropriate. *
    • *
    • * As outlined above, {@code Collection}s and {@code Map}s are wrapped by immutable wrapper classes (but not deeply cloned!). *
    • *
    • * Currently {@code BigInteger} and {@code BigDecimal} are deemed immutable but see: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370 *
    • *
    • * {@code java.awt.Color} is treated as "effectively immutable" but is not final so while not normally used with child * classes, it isn't strictly immutable. Use at your own risk. *
    • *
    • * {@code java.util.Date} is treated as "effectively immutable" but is not final so it isn't strictly immutable. * Use at your own risk. *
    • *
    * * @author Paul King * @deprecated use groovy.transform.Immutable */ @java.lang.annotation.Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.ImmutableASTTransformation") @Deprecated public @interface Immutable { } groovy-1.8.6/src/main/groovy/lang/MetaExpandoProperty.java0000644001501200150120000000272111627206700023172 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.Map.Entry; /** * Represents a property in an Expando object * * @author John Stump * @version $Revision$ */ public class MetaExpandoProperty extends MetaProperty { Object value = null; public MetaExpandoProperty(Entry entry) { super((String) entry.getKey(), Object.class); value = entry.getValue(); } /** * @return the property of the given object * @throws Exception if the property could not be evaluated */ public Object getProperty(Object object) { return value; } /** * Sets the property on the given object to the new value * * @param object on which to set the property * @param newValue the new value of the property */ public void setProperty(Object object, Object newValue) { value = newValue; } } groovy-1.8.6/src/main/groovy/lang/MissingFieldException.java0000644001501200150120000000367711627206700023467 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * An exception occurred if a dynamic field dispatch fails with an unknown field. * * Note that the Missing*Exception classes were named for consistency and * to avoid conflicts with JDK exceptions of the same name. * * @author James Strachan * @version $Revision$ */ public class MissingFieldException extends GroovyRuntimeException { private final String field; private final Class type; public MissingFieldException(String field, Class type) { super("No such field: " + field + " for class: " + type.getName()); this.field = field; this.type = type; } public MissingFieldException(String field, Class type, Throwable e) { super("No such field: " + field + " for class: " + type.getName() + ". Reason: " + e, e); this.field = field; this.type = type; } public MissingFieldException(String message, String field, Class type) { super(message); this.field = field; this.type = type; } /** * @return the name of the field that could not be found */ public String getField() { return field; } /** * * @return The type on which the field was attempted to be called */ public Class getType() { return type; } } groovy-1.8.6/src/main/groovy/lang/ObjectRange.java0000644001501200150120000003260111707612044021404 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.IteratorClosureAdapter; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.math.BigDecimal; import java.math.BigInteger; import java.util.AbstractList; import java.util.Iterator; import java.util.List; /** * Represents an inclusive list of objects from a value to a value using * comparators. *

    * This class is similar to {@link IntRange}. If you make any changes to this * class, you might consider making parallel changes to {@link IntRange}. * * @author James Strachan * @version $Revision$ */ public class ObjectRange extends AbstractList implements Range { /** * The first value in the range. */ private Comparable from; /** * The last value in the range. */ private Comparable to; /** * The cached size, or -1 if not yet computed */ private int size = -1; /** * true if the range counts backwards from to to from. */ private final boolean reverse; /** * Creates a new {@link ObjectRange}. Creates a reversed range if * from < to. * * @param from the first value in the range. * @param to the last value in the range. */ public ObjectRange(Comparable from, Comparable to) { if (from == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'from' index in a Range"); } if (to == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'to' index in a Range"); } try { this.reverse = ScriptBytecodeAdapter.compareGreaterThan(from, to); } catch (ClassCastException cce) { throw new IllegalArgumentException("Unable to create range due to incompatible types: " + from.getClass().getSimpleName() + ".." + to.getClass().getSimpleName() + " (possible missing brackets around range?)", cce); } if (this.reverse) { constructorHelper(to, from); } else { constructorHelper(from, to); } } public ObjectRange(Comparable from, Comparable to, boolean reverse) { constructorHelper(from, to); this.reverse = reverse; } private void constructorHelper(Comparable from, Comparable to) { if (from instanceof Short) { from = ((Short) from).intValue(); } else if (from instanceof Float) { from = ((Float) from).doubleValue(); } if (to instanceof Short) { to = ((Short) to).intValue(); } else if (to instanceof Float) { to = ((Float) to).doubleValue(); } if (from instanceof Integer && to instanceof Long) { from = Long.valueOf(((Integer) from).longValue()); } else if (to instanceof Integer && from instanceof Long) { to = Long.valueOf(((Integer) to).longValue()); } // TODO: should we care about different types here? if (from.getClass() == to.getClass()) { this.from = from; this.to = to; } else { this.from = normaliseStringType(from); this.to = normaliseStringType(to); } if (from instanceof String || to instanceof String) { // this test depends deeply on the String.next implementation // 009.next is 00:, not 010 String start = from.toString(); String end = to.toString(); if (start.length() > end.length()) { throw new IllegalArgumentException("Incompatible Strings for Range: starting String is longer than ending string"); } int length = Math.min(start.length(), end.length()); int i; for (i = 0; i < length; i++) { if (start.charAt(i) != end.charAt(i)) break; } if (i < length - 1) { throw new IllegalArgumentException("Incompatible Strings for Range: String#next() will not reach the expected value"); } } } /** * {@inheritDoc} */ public boolean equals(Object that) { return (that instanceof ObjectRange) ? equals((ObjectRange) that) : super.equals(that); } /** * Compares an {@link ObjectRange} to another {@link ObjectRange}. * * @param that the object to check equality with * @return true if the ranges are equal */ public boolean equals(ObjectRange that) { return that != null && this.reverse == that.reverse && DefaultTypeTransformation.compareEqual(this.from, that.from) && DefaultTypeTransformation.compareEqual(this.to, that.to); } /** * {@inheritDoc} */ public Comparable getFrom() { return from; } /** * {@inheritDoc} */ public Comparable getTo() { return to; } /** * {@inheritDoc} */ public boolean isReverse() { return reverse; } /** * {@inheritDoc} */ public Object get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } if (index >= size()) { throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this); } Object value; if (reverse) { value = to; for (int i = 0; i < index; i++) { value = decrement(value); } } else { value = from; for (int i = 0; i < index; i++) { value = increment(value); } } return value; } /** * {@inheritDoc} */ public Iterator iterator() { return new Iterator() { private int index; private Object value = reverse ? to : from; public boolean hasNext() { return index < size(); } public Object next() { if (index++ > 0) { if (index > size()) { value = null; } else { if (reverse) { value = decrement(value); } else { value = increment(value); } } } return value; } public void remove() { ObjectRange.this.remove(index); } }; } /** * Checks whether a value is between the from and to values of a Range * * @param value the value of interest * @return true if the value is within the bounds */ public boolean containsWithinBounds(Object value) { if (value instanceof Comparable) { int result = compareTo(from, (Comparable) value); return result == 0 || result < 0 && compareTo(to, (Comparable) value) >= 0; } return contains(value); } private int compareTo(Comparable first, Comparable second) { return DefaultGroovyMethods.numberAwareCompareTo(first, second); } /** * {@inheritDoc} */ public int size() { if (size == -1) { if ((from instanceof Integer || from instanceof Long) && (to instanceof Integer || to instanceof Long)) { // let's fast calculate the size long fromNum = ((Number) from).longValue(); long toNum = ((Number) to).longValue(); size = (int) (toNum - fromNum + 1); } else if (from instanceof Character && to instanceof Character) { // let's fast calculate the size char fromNum = (Character) from; char toNum = (Character) to; size = toNum - fromNum + 1; } else if (from instanceof BigDecimal || to instanceof BigDecimal) { // let's fast calculate the size BigDecimal fromNum = new BigDecimal("" + from); BigDecimal toNum = new BigDecimal("" + to); BigInteger sizeNum = toNum.subtract(fromNum).add(new BigDecimal(1.0)).toBigInteger(); size = sizeNum.intValue(); } else { // let's lazily calculate the size size = 0; Comparable first = from; Comparable value = from; while (compareTo(to, value) >= 0) { value = (Comparable) increment(value); size++; if (compareTo(first, value) >= 0) break; // handle back to beginning due to modulo incrementing } } } return size; } /** * {@inheritDoc} */ public List subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (toIndex > size()) { throw new IndexOutOfBoundsException("toIndex = " + toIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange(from); } return new ObjectRange((Comparable) get(fromIndex), (Comparable) get(--toIndex), reverse); } /** * {@inheritDoc} */ public String toString() { return reverse ? "" + to + ".." + from : "" + from + ".." + to; } /** * {@inheritDoc} */ public String inspect() { String toText = InvokerHelper.inspect(to); String fromText = InvokerHelper.inspect(from); return reverse ? "" + toText + ".." + fromText : "" + fromText + ".." + toText; } public boolean contains(Object value) { Iterator it = iterator(); if (value == null) return false; while (it.hasNext()) { try { if (DefaultTypeTransformation.compareEqual(value, it.next())) return true; } catch (ClassCastException e) { return false; } } return false; } /** * {@inheritDoc} */ public void step(int step, Closure closure) { if (step == 0) { if (compareTo(from, to) != 0) { throw new GroovyRuntimeException("Infinite loop detected due to step size of 0"); } else { return; // from == to and step == 0, nothing to do, so return } } if (reverse) { step = -step; } if (step > 0) { Comparable first = from; Comparable value = from; while (compareTo(value, to) <= 0) { closure.call(value); for (int i = 0; i < step; i++) { value = (Comparable) increment(value); if (compareTo(value, first) <= 0) return; } } } else { step = -step; Comparable first = to; Comparable value = to; while (compareTo(value, from) >= 0) { closure.call(value); for (int i = 0; i < step; i++) { value = (Comparable) decrement(value); if (compareTo(value, first) >= 0) return; } } } } /** * {@inheritDoc} */ public List step(int step) { IteratorClosureAdapter adapter = new IteratorClosureAdapter(this); step(step, adapter); return adapter.asList(); } /** * Increments by one * * @param value the value to increment * @return the incremented value */ protected Object increment(Object value) { return InvokerHelper.invokeMethod(value, "next", null); } /** * Decrements by one * * @param value the value to decrement * @return the decremented value */ protected Object decrement(Object value) { return InvokerHelper.invokeMethod(value, "previous", null); } private static Comparable normaliseStringType(final Comparable operand) { if (operand instanceof Character) { return (int) ((Character) operand).charValue(); } else if (operand instanceof String) { final String string = (String) operand; if (string.length() == 1) return (int) string.charAt(0); else return string; } else { return operand; } } } groovy-1.8.6/src/main/groovy/lang/GroovyObject.java0000644001501200150120000000366011627206700021637 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * The interface implemented by all Groovy objects. *

    * Especially handy for using Groovy objects when in the Java world. * * @author James Strachan * @version $Revision$ */ public interface GroovyObject { /** * Invokes the given method. * * @param name the name of the method to call * @param args the arguments to use for the method call * @return the result of invoking the method */ Object invokeMethod(String name, Object args); /** * Retrieves a property value. * * @param propertyName the name of the property of interest * @return the given property */ Object getProperty(String propertyName); /** * Sets the given property to the new value. * * @param propertyName the name of the property of interest * @param newValue the new value for the property */ void setProperty(String propertyName, Object newValue); /** * Returns the metaclass for a given class. * * @return the metaClass of this instance */ MetaClass getMetaClass(); /** * Allows the MetaClass to be replaced with a derived implementation. * * @param metaClass the new metaclass */ void setMetaClass(MetaClass metaClass); } groovy-1.8.6/src/main/groovy/lang/MetaBeanProperty.java0000644001501200150120000001037511627206700022445 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.lang.reflect.Modifier; /** * Represents a property on a bean which may have a getter and/or a setter * * @author James Strachan * @author Pilho Kim * @version $Revision$ */ public class MetaBeanProperty extends MetaProperty { private MetaMethod getter; private MetaMethod setter; private CachedField field; public MetaBeanProperty(String name, Class type, MetaMethod getter, MetaMethod setter) { super(name, type); this.getter = getter; this.setter = setter; } /** * Get the property of the given object. * * @param object which to be got * @return the property of the given object * @throws RuntimeException if the property could not be evaluated */ public Object getProperty(Object object) { MetaMethod getter = getGetter(); if (getter == null) { if (field != null) return field.getProperty(object); //TODO: create a WriteOnlyException class? throw new GroovyRuntimeException("Cannot read write-only property: " + name); } return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY); } /** * Set the property on the given object to the new value. * * @param object on which to set the property * @param newValue the new value of the property * @throws RuntimeException if the property could not be set */ public void setProperty(Object object, Object newValue) { MetaMethod setter = getSetter(); if (setter == null) { if (field != null && !Modifier.isFinal(field.getModifiers())) { field.setProperty(object, newValue); return; } throw new GroovyRuntimeException("Cannot set read-only property: " + name); } newValue = DefaultTypeTransformation.castToType(newValue, getType()); setter.invoke(object, new Object[]{newValue}); } /** * Get the getter method. */ public MetaMethod getGetter() { return getter; } /** * Get the setter method. */ public MetaMethod getSetter() { return setter; } /** * This is for MetaClass to patch up the object later when looking for get*() methods. */ void setGetter(MetaMethod getter) { this.getter = getter; } /** * This is for MetaClass to patch up the object later when looking for set*() methods. */ void setSetter(MetaMethod setter) { this.setter = setter; } public int getModifiers() { MetaMethod getter = getGetter(); MetaMethod setter = getSetter(); if (setter != null && getter == null) return setter.getModifiers(); if (getter != null && setter == null) return getter.getModifiers(); int modifiers = getter.getModifiers() | setter.getModifiers(); int visibility = 0; if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC; if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED; if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE; int states = getter.getModifiers() & setter.getModifiers(); states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); states |= visibility; return states; } public void setField(CachedField f) { this.field = f; } public CachedField getField() { return field; } } groovy-1.8.6/src/main/groovy/lang/ReadOnlyPropertyException.java0000644001501200150120000000240311627206700024356 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * This exception is thrown if an attempt is made to set a read only property * * @author James Strachan * @version $Revision$ */ public class ReadOnlyPropertyException extends MissingPropertyException { public ReadOnlyPropertyException(final String property, final Class type) { super("Cannot set readonly property: " + property + " for class: " + type.getName(), property, type); } public ReadOnlyPropertyException(final String property, final String classname) { super("Cannot set readonly property: " + property + " for class: " + classname); } } groovy-1.8.6/src/main/groovy/lang/DelegatingMetaClass.java0000644001501200150120000002412311627206700023060 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.InvokerHelper; import java.lang.reflect.Method; import java.util.List; /** * @author John Wilson */ public class DelegatingMetaClass implements MetaClass, MutableMetaClass, GroovyObject { protected MetaClass delegate; public DelegatingMetaClass(final MetaClass delegate) { this.delegate = delegate; } public DelegatingMetaClass(final Class theClass) { this(GroovySystem.getMetaClassRegistry().getMetaClass(theClass)); } public boolean isModified() { return this.delegate instanceof MutableMetaClass && ((MutableMetaClass) this.delegate).isModified(); } /* (non-Javadoc) * @see groovy.lang.MetaClass#addNewInstanceMethod(java.lang.reflect.Method) */ public void addNewInstanceMethod(Method method) { if (delegate instanceof MutableMetaClass) ((MutableMetaClass) delegate).addNewInstanceMethod(method); } /* (non-Javadoc) * @see groovy.lang.MetaClass#addNewStaticMethod(java.lang.reflect.Method) */ public void addNewStaticMethod(Method method) { if (delegate instanceof MutableMetaClass) ((MutableMetaClass) delegate).addNewStaticMethod(method); } public void addMetaMethod(MetaMethod metaMethod) { if (delegate instanceof MutableMetaClass) ((MutableMetaClass) delegate).addMetaMethod(metaMethod); } public void addMetaBeanProperty(MetaBeanProperty metaBeanProperty) { if (delegate instanceof MutableMetaClass) ((MutableMetaClass) delegate).addMetaBeanProperty(metaBeanProperty); } /* (non-Javadoc) * @see groovy.lang.MetaClass#initialize() */ public void initialize() { delegate.initialize(); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getAttribute(java.lang.Object, java.lang.String) */ public Object getAttribute(Object object, String attribute) { return delegate.getAttribute(object, attribute); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getClassNode() */ public ClassNode getClassNode() { return delegate.getClassNode(); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getMetaMethods() */ public List getMetaMethods() { return delegate.getMetaMethods(); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getMethods() */ public List getMethods() { return delegate.getMethods(); } public List respondsTo(Object obj, String name, Object[] argTypes) { return delegate.respondsTo(obj, name, argTypes); } public List respondsTo(Object obj, String name) { return delegate.respondsTo(obj, name); } public MetaProperty hasProperty(Object obj, String name) { return delegate.hasProperty(obj, name); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getProperties() */ public List getProperties() { return delegate.getProperties(); } /* (non-Javadoc) * @see groovy.lang.MetaClass#getProperty(java.lang.Object, java.lang.String) */ public Object getProperty(Object object, String property) { return delegate.getProperty(object, property); } /* (non-Javadoc) * @see groovy.lang.MetaClass#invokeConstructor(java.lang.Object[]) */ public Object invokeConstructor(Object[] arguments) { return delegate.invokeConstructor(arguments); } /* (non-Javadoc) * @see groovy.lang.MetaClass#invokeMethod(java.lang.Object, java.lang.String, java.lang.Object) */ public Object invokeMethod(Object object, String methodName, Object arguments) { return delegate.invokeMethod(object, methodName, arguments); } /* (non-Javadoc) * @see groovy.lang.MetaClass#invokeMethod(java.lang.Object, java.lang.String, java.lang.Object[]) */ public Object invokeMethod(Object object, String methodName, Object[] arguments) { return delegate.invokeMethod(object, methodName, arguments); } /* (non-Javadoc) * @see groovy.lang.MetaClass#invokeStaticMethod(java.lang.Object, java.lang.String, java.lang.Object[]) */ public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { return delegate.invokeStaticMethod(object, methodName, arguments); } /* (non-Javadoc) * @see groovy.lang.MetaClass#setAttribute(java.lang.Object, java.lang.String, java.lang.Object) */ public void setAttribute(Object object, String attribute, Object newValue) { delegate.setAttribute(object, attribute, newValue); } /* (non-Javadoc) * @see groovy.lang.MetaClass#setProperty(java.lang.Object, java.lang.String, java.lang.Object) */ public void setProperty(Object object, String property, Object newValue) { delegate.setProperty(object, property, newValue); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return delegate.equals(obj); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return delegate.hashCode(); } public String toString() { return super.toString() + "[" + delegate.toString() + "]"; } /** * @deprecated */ public MetaMethod pickMethod(String methodName, Class[] arguments) { return delegate.pickMethod(methodName, arguments); } public Object getAttribute(Class sender, Object receiver, String messageName, boolean useSuper) { return this.delegate.getAttribute(sender, receiver, messageName, useSuper); } public Object getProperty(Class sender, Object receiver, String messageName, boolean useSuper, boolean fromInsideClass) { return this.delegate.getProperty(sender, receiver, messageName, useSuper, fromInsideClass); } public MetaProperty getMetaProperty(String name) { return this.delegate.getMetaProperty(name); } public MetaMethod getStaticMetaMethod(String name, Object[] args) { return this.delegate.getStaticMetaMethod(name, args); } public MetaMethod getStaticMetaMethod(String name, Class[] argTypes) { return this.delegate.getStaticMetaMethod(name, argTypes); } public MetaMethod getMetaMethod(String name, Object[] args) { return this.delegate.getMetaMethod(name, args); } public Class getTheClass() { return this.delegate.getTheClass(); } public Object invokeMethod(Class sender, Object receiver, String methodName, Object[] arguments, boolean isCallToSuper, boolean fromInsideClass) { return this.delegate.invokeMethod(sender, receiver, methodName, arguments, isCallToSuper, fromInsideClass); } public Object invokeMissingMethod(Object instance, String methodName, Object[] arguments) { return this.delegate.invokeMissingMethod(instance, methodName, arguments); } public Object invokeMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) { return this.delegate.invokeMissingProperty(instance, propertyName, optionalValue, isGetter); } public boolean isGroovyObject() { return GroovyObject.class.isAssignableFrom(this.delegate.getTheClass()); } public void setAttribute(Class sender, Object receiver, String messageName, Object messageValue, boolean useSuper, boolean fromInsideClass) { this.delegate.setAttribute(sender, receiver, messageName, messageValue, useSuper, fromInsideClass); } public void setProperty(Class sender, Object receiver, String messageName, Object messageValue, boolean useSuper, boolean fromInsideClass) { this.delegate.setProperty(sender, receiver, messageName, messageValue, useSuper, fromInsideClass); } public int selectConstructorAndTransformArguments(int numberOfConstructors, Object[] arguments) { return this.delegate.selectConstructorAndTransformArguments(numberOfConstructors, arguments); } public void setAdaptee(MetaClass adaptee) { this.delegate = adaptee; } public MetaClass getAdaptee() { return this.delegate; } public Object invokeMethod(String name, Object args) { try { return getMetaClass().invokeMethod(this, name, args); } catch (MissingMethodException e) { if (delegate instanceof GroovyObject) return ((GroovyObject) delegate).invokeMethod(name, args); else throw e; } } public Object getProperty(String property) { try { return getMetaClass().getProperty(this, property); } catch (MissingPropertyException e) { if (delegate instanceof GroovyObject) return ((GroovyObject) delegate).getProperty(property); else throw e; } } public void setProperty(String property, Object newValue) { try { getMetaClass().setProperty(this, property, newValue); } catch (MissingPropertyException e) { if (delegate instanceof GroovyObject) ((GroovyObject) delegate).setProperty(property, newValue); else throw e; } } public MetaClass getMetaClass() { return InvokerHelper.getMetaClass(getClass()); } public void setMetaClass(MetaClass metaClass) { throw new UnsupportedOperationException(); } } groovy-1.8.6/src/main/groovy/lang/Category.java0000644001501200150120000001071611707612044021001 0ustar miguelmiguel/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Transforms an instance-style Groovy class or interface to become a static-style * conventional Groovy category. *

    * Groovy categories are the original mechanism used * by Groovy when augmenting classes with new methods. Writing categories required * using a class writing style where all methods were static and an additional * self parameter was defined. The self parameter and static nature of the methods * disappeared once applied by Groovy's metaclass framework but some regarded * the writing style as a little noisy. This transformation allows you to write * your categories without the "apparent noise" but adds it back in during * compilation so that the classes appear as normal categories. *

    * It might seem strange writing your class/object enhancements using a succinct * notation, then having "noise" added, then having the noise removed during * category application. If this worries you, then you may also like to consider * using Groovy's {@code ExpandoMetaClass} mechanism which avoids * the category definition altogether. If you already have an investment in * categories or like some of the other features which categories currently give you, * then read on. *

    * The mechanics: during compilation, all methods are transformed to static ones with an additional * self parameter of the type you supply as the annotation parameter (the default type * for the self parameters is {@code Object} which might be more broad reaching than * you like so it is usually wise to specify a type). * Properties invoked using 'this' references are transformed so that * they are instead invoked on the additional self parameter and not on * the Category instance. (Remember that once the category is applied, the reverse * will occur and we will be back to conceptually having methods on the {@code this} * references again!) *

    * Classes conforming to the conventional Groovy category conventions can be used * within {@code use} statements or mixed in at compile time with the {@code @Mixin} * transformation or at runtime with the {@code mixin} method on classes. *

    * An example showing a {@code use} statement (allowing fine-grained application of * the category methods): *
     * {@code @Category}(Integer)
     * class IntegerOps {
     *     def triple() {
     *         this * 3
     *     }
     * }
     *
     * use (IntegerOps) {
     *     assert 25.triple() == 75
     * }
     * 
    * Or, using the {@code @Mixin} flavor for compile-time "mixing in" of the methods: *
     * {@code @Category}(List)
     * class Shuffler {
     *     def shuffle() {
     *         def result = new ArrayList(this)
     *         Collections.shuffle(result)
     *         result
     *     }
     * }
     *
     * {@code @Mixin}(Shuffler)
     * class Sentence extends ArrayList {
     *     Sentence(Collection initial) { super(initial) }
     * }
     *
     * def words = ["The", "quick", "brown", "fox"]
     * println new Sentence(words).shuffle()
     * // => [quick, fox, The, brown]       (order will vary)
     * 
    * Or, instead of using {@code @Mixin}, try "mixing in" your methods at runtime: *
     * // ... as before ...
     *
     * class Sentence extends ArrayList {
     *     Sentence(Collection initial) { super(initial) }
     * }
     * Sentence.mixin Shuffler
     *
     * // ... as before ...
     * 
    * * @author Alex Tkachman */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) @GroovyASTTransformationClass("org.codehaus.groovy.transform.CategoryASTTransformation") public @interface Category { Class value () default Object.class; } groovy-1.8.6/src/main/groovy/lang/IncorrectClosureArgumentsException.java0000644001501200150120000000333711627206700026256 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; /** * An exception occurred when invoking a Closure with the wrong number and/or * types of arguments * * @author James Strachan * @version $Revision$ */ public class IncorrectClosureArgumentsException extends GroovyRuntimeException { private final Closure closure; private final Object arguments; private final Class[] expected; public IncorrectClosureArgumentsException(Closure closure, Object arguments, Class[] expected) { super( "Incorrect arguments to closure: " + closure + ". Expected: " + InvokerHelper.toString(expected) + ", actual: " + InvokerHelper.toString(arguments)); this.closure = closure; this.arguments = arguments; this.expected = expected; } public Object getArguments() { return arguments; } public Closure getClosure() { return closure; } public Class[] getExpected() { return expected; } } groovy-1.8.6/src/main/groovy/lang/SpreadMapEvaluatingException.java0000644001501200150120000000144711627206700024777 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; public class SpreadMapEvaluatingException extends GroovyRuntimeException { public SpreadMapEvaluatingException(String message) { super(message); } } groovy-1.8.6/src/main/groovy/lang/GroovyRuntimeException.java0000644001501200150120000000430611627206700023731 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ModuleNode; /** * An exception thrown by the interpreter * * @author James Strachan * @version $Revision$ */ public class GroovyRuntimeException extends RuntimeException { private ModuleNode module; private ASTNode node; public GroovyRuntimeException() { } public GroovyRuntimeException(String message) { super(message); } public GroovyRuntimeException(String message, ASTNode node) { super(message); this.node = node; } public GroovyRuntimeException(String message, Throwable cause) { super(message, cause); } public GroovyRuntimeException(Throwable t) { super(); initCause(t); } public void setModule(ModuleNode module) { this.module = module; } public ModuleNode getModule() { return module; } public String getMessage() { return getMessageWithoutLocationText() + getLocationText(); } public ASTNode getNode() { return node; } public String getMessageWithoutLocationText() { return super.getMessage(); } protected String getLocationText() { String answer = ". "; if (node != null) { answer += "At [" + node.getLineNumber() + ":" + node.getColumnNumber() + "] "; } if (module != null) { answer += module.getDescription(); } if (answer.equals(". ")) { return ""; } return answer; } } groovy-1.8.6/src/main/groovy/lang/ProxyMetaClass.java0000644001501200150120000002051511627206700022137 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.beans.IntrospectionException; /** * As subclass of MetaClass, ProxyMetaClass manages calls from Groovy Objects to POJOs. * It enriches MetaClass with the feature of making method invokations interceptable by * an Interceptor. To this end, it acts as a decorator (decorator pattern) allowing * to add or withdraw this feature at runtime. * See groovy/lang/InterceptorTest.groovy for details. *

    *

    WARNING: This implementation of ProxyMetaClass is NOT threadsafe and hence should only be used for * as a per-instance MetaClass running in a single thread. Do not place this MetaClass in the MetaClassRegistry * as it will result in unpredictable behaviour * * @author Dierk Koenig * @author Graeme Rocher * @see groovy.lang.MetaClassRegistry */ public class ProxyMetaClass extends MetaClassImpl implements AdaptingMetaClass { protected MetaClass adaptee = null; protected Interceptor interceptor = null; /** * convenience factory method for the most usual case. */ public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new ProxyMetaClass(metaRegistry, theClass, meta); } /** * @param adaptee the MetaClass to decorate with interceptability */ public ProxyMetaClass(MetaClassRegistry registry, Class theClass, MetaClass adaptee) throws IntrospectionException { super(registry, theClass); this.adaptee = adaptee; if (null == adaptee) throw new IllegalArgumentException("adaptee must not be null"); super.initialize(); } public synchronized void initialize() { this.adaptee.initialize(); } /** * Use the ProxyMetaClass for the given Closure. * Cares for balanced register/unregister. * * @param closure piece of code to be executed with registered ProxyMetaClass */ public Object use(Closure closure) { // grab existing meta (usually adaptee but we may have nested use calls) MetaClass origMetaClass = registry.getMetaClass(theClass); registry.setMetaClass(theClass, this); try { return closure.call(); } finally { registry.setMetaClass(theClass, origMetaClass); } } /** * Use the ProxyMetaClass for the given Closure. * Cares for balanced setting/unsetting ProxyMetaClass. * * @param closure piece of code to be executed with ProxyMetaClass */ public Object use(GroovyObject object, Closure closure) { // grab existing meta (usually adaptee but we may have nested use calls) MetaClass origMetaClass = object.getMetaClass(); object.setMetaClass(this); try { return closure.call(); } finally { object.setMetaClass(origMetaClass); } } /** * @return the interceptor in use or null if no interceptor is used */ public Interceptor getInterceptor() { return interceptor; } /** * @param interceptor may be null to reset any interception */ public void setInterceptor(Interceptor interceptor) { this.interceptor = interceptor; } /** * Call invokeMethod on adaptee with logic like in MetaClass unless we have an Interceptor. * With Interceptor the call is nested in its beforeInvoke and afterInvoke methods. * The method call is suppressed if Interceptor.doInvoke() returns false. * See Interceptor for details. */ public Object invokeMethod(final Object object, final String methodName, final Object[] arguments) { return doCall(object, methodName, arguments, interceptor, new Callable() { public Object call() { return adaptee.invokeMethod(object, methodName, arguments); } }); } /** * Call invokeStaticMethod on adaptee with logic like in MetaClass unless we have an Interceptor. * With Interceptor the call is nested in its beforeInvoke and afterInvoke methods. * The method call is suppressed if Interceptor.doInvoke() returns false. * See Interceptor for details. */ public Object invokeStaticMethod(final Object object, final String methodName, final Object[] arguments) { return doCall(object, methodName, arguments, interceptor, new Callable() { public Object call() { return adaptee.invokeStaticMethod(object, methodName, arguments); } }); } /** * Call invokeConstructor on adaptee with logic like in MetaClass unless we have an Interceptor. * With Interceptor the call is nested in its beforeInvoke and afterInvoke methods. * The method call is suppressed if Interceptor.doInvoke() returns false. * See Interceptor for details. */ public Object invokeConstructor(final Object[] arguments) { return doCall(theClass, "ctor", arguments, interceptor, new Callable() { public Object call() { return adaptee.invokeConstructor(arguments); } }); } /** * Interceptors the call to getProperty if a PropertyAccessInterceptor is * available * * @param object the object to invoke the getter on * @param property the property name * @return the value of the property */ public Object getProperty(Class aClass, Object object, String property, boolean b, boolean b1) { if (null == interceptor) { return super.getProperty(aClass, object, property, b, b1); } if (interceptor instanceof PropertyAccessInterceptor) { PropertyAccessInterceptor pae = (PropertyAccessInterceptor) interceptor; Object result = pae.beforeGet(object, property); if (interceptor.doInvoke()) { result = super.getProperty(aClass, object, property, b, b1); } return result; } return super.getProperty(aClass, object, property, b, b1); } /** * Interceptors the call to a property setter if a PropertyAccessInterceptor * is available * * @param object The object to invoke the setter on * @param property The property name to set * @param newValue The new value of the property */ public void setProperty(Class aClass, Object object, String property, Object newValue, boolean b, boolean b1) { if (null == interceptor) { super.setProperty(aClass, object, property, newValue, b, b1); } if (interceptor instanceof PropertyAccessInterceptor) { PropertyAccessInterceptor pae = (PropertyAccessInterceptor) interceptor; pae.beforeSet(object, property, newValue); if (interceptor.doInvoke()) { super.setProperty(aClass, object, property, newValue, b, b1); } } else { super.setProperty(aClass, object, property, newValue, b, b1); } } public MetaClass getAdaptee() { return this.adaptee; } public void setAdaptee(MetaClass metaClass) { this.adaptee = metaClass; } // since Java has no Closures... private interface Callable { Object call(); } private Object doCall(Object object, String methodName, Object[] arguments, Interceptor interceptor, Callable howToInvoke) { if (null == interceptor) { return howToInvoke.call(); } Object result = interceptor.beforeInvoke(object, methodName, arguments); if (interceptor.doInvoke()) { result = howToInvoke.call(); } result = interceptor.afterInvoke(object, methodName, arguments, result); return result; } } groovy-1.8.6/src/main/groovy/lang/Lazy.java0000644001501200150120000001104411707612044020136 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Field annotation to simplify lazy initialization. *

    * Example usage without any special modifiers just defers initialization until the first call but is not thread-safe: *

     * {@code @Lazy} T x
     * 
    * becomes *
     * private T $x
     *
     * T getX() {
     *    if ($x != null)
     *       return $x
     *    else {
     *       $x = new T()
     *       return $x
     *    }
     * }
     * 
    * * If the field is declared volatile then initialization will be synchronized using * the double-checked locking pattern as shown here: * *
     * {@code @Lazy} volatile T x
     * 
    * becomes *
     * private volatile T $x
     *
     * T getX() {
     *    T $x_local = $x
     *    if ($x_local != null)
     *       return $x_local
     *    else {
     *       synchronized(this) {
     *          if ($x == null) {
     *             $x = new T()
     *          }
     *          return $x
     *       }
     *    }
     * }
     * 
    * * By default a field will be initialized by calling its default constructor. * * If the field has an initial value expression then this expression will be used instead of calling the default constructor. * In particular, it is possible to use closure { ... } () syntax as follows: * *
     * {@code @Lazy} T x = { [1, 2, 3] } ()
     * 
    * becomes *
     * private T $x
     *
     * T getX() {
     *    T $x_local = $x
     *    if ($x_local != null)
     *       return $x_local
     *    else {
     *       synchronized(this) {
     *          if ($x == null) {
     *             $x = { [1, 2, 3] } ()
     *          }
     *          return $x
     *       }
     *    }
     * }
     * 
    *

    * @Lazy(soft=true) will use a soft reference instead of the field and use the above rules each time re-initialization is required. *

    * If the soft flag for the annotation is not set but the field is static, then * the initialization on demand holder idiom is * used as follows: *

     * {@code @Lazy} static FieldType field
     * {@code @Lazy} static Date date1
     * {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }()
     * {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
     * 
    * becomes these methods and inners classes within the class containing the above definitions: *
     * private static class FieldTypeHolder_field {
     *     private static final FieldType INSTANCE = new FieldType()
     * }
     *
     * private static class DateHolder_date1 {
     *     private static final Date INSTANCE = new Date()
     * }
     *
     * private static class DateHolder_date2 {
     *     private static final Date INSTANCE = { new Date().updated(year: 2000) }()
     * }
     *
     * private static class DateHolder_date3 {
     *     private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
     * }
     *
     * static FieldType getField() {
     *     return FieldTypeHolder_field.INSTANCE
     * }
     *
     * static Date getDate1() {
     *     return DateHolder_date1.INSTANCE
     * }
     *
     * static Date getDate2() {
     *     return DateHolder_date2.INSTANCE
     * }
     *
     * static Date getDate3() {
     *     return DateHolder_date3.INSTANCE
     * }
     * 
    * * @author Alex Tkachman * @author Paul King */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation") public @interface Lazy { /** * @return if field should be soft referenced instead of hard referenced */ boolean soft () default false; } groovy-1.8.6/src/main/groovy/lang/NonEmptySequence.java0000644001501200150120000000240411707612044022461 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.List; /** * Represents a sequence of objects which represents one or many instances of * of objects of a given type. The type can be omitted in which case any type of * object can be added. * * @author James Strachan * @version $Revision$ */ public class NonEmptySequence extends Sequence { public NonEmptySequence() { super(null); } public NonEmptySequence(Class type) { super(type); } public NonEmptySequence(Class type, List content) { super(type, content); } public int minimumSize() { return 1; } }groovy-1.8.6/src/main/groovy/lang/ClosureException.java0000644001501200150120000000220711627206700022512 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * An exception thrown by a closure invocation * * @author James Strachan * @version $Revision$ */ public class ClosureException extends RuntimeException { private final Closure closure; public ClosureException(Closure closure, Throwable cause) { super("Exception thrown by call to closure: " + closure + " reaason: " + cause, cause); this.closure = closure; } public Closure getClosure() { return closure; } } groovy-1.8.6/src/main/groovy/lang/Sequence.java0000644001501200150120000001416411707612044020775 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Represents a sequence of objects which represents zero or many instances of * of objects of a given type. The type can be omitted in which case any type of * object can be added. * * @author James Strachan * @version $Revision$ */ public class Sequence extends ArrayList implements GroovyObject { private MetaClass metaClass = InvokerHelper.getMetaClass(getClass()); private Class type; private int hashCode; public Sequence() { this(null); } public Sequence(Class type) { this.type = type; } public Sequence(Class type, List content) { super(content.size()); this.type = type; addAll(content); } /** * Sets the contents of this sequence to that * of the given collection. */ public void set(Collection collection) { checkCollectionType(collection); clear(); addAll(collection); } public boolean equals(Object that) { if (that instanceof Sequence) { return equals((Sequence) that); } return false; } public boolean equals(Sequence that) { if (size() == that.size()) { for (int i = 0; i < size(); i++) { if (!DefaultTypeTransformation.compareEqual(this.get(i), that.get(i))) { return false; } } return true; } return false; } public int hashCode() { if (hashCode == 0) { for (int i = 0; i < size(); i++) { Object value = get(i); int hash = (value != null) ? value.hashCode() : 0xbabe; hashCode ^= hash; } if (hashCode == 0) { hashCode = 0xbabe; } } return hashCode; } public int minimumSize() { return 0; } /** * @return the type of the elements in the sequence or null if there is no * type constraint on this sequence */ public Class type() { return type; } public void add(int index, Object element) { checkType(element); hashCode = 0; super.add(index, element); } public boolean add(Object element) { checkType(element); hashCode = 0; return super.add(element); } public boolean addAll(Collection c) { checkCollectionType(c); hashCode = 0; return super.addAll(c); } public boolean addAll(int index, Collection c) { checkCollectionType(c); hashCode = 0; return super.addAll(index, c); } public void clear() { hashCode = 0; super.clear(); } public Object remove(int index) { hashCode = 0; return super.remove(index); } protected void removeRange(int fromIndex, int toIndex) { hashCode = 0; super.removeRange(fromIndex, toIndex); } public Object set(int index, Object element) { hashCode = 0; return super.set(index, element); } // GroovyObject interface //------------------------------------------------------------------------- public Object invokeMethod(String name, Object args) { try { return getMetaClass().invokeMethod(this, name, args); } catch (MissingMethodException e) { // lets apply the method to each item in the collection List answer = new ArrayList(size()); for (Iterator iter = iterator(); iter.hasNext(); ) { Object element = iter.next(); Object value = InvokerHelper.invokeMethod(element, name, args); answer.add(value); } return answer; } } public Object getProperty(String property) { return getMetaClass().getProperty(this, property); } public void setProperty(String property, Object newValue) { getMetaClass().setProperty(this, property, newValue); } public MetaClass getMetaClass() { return metaClass; } public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } // Implementation methods //------------------------------------------------------------------------- /** * Checks that each member of the given collection are of the correct * type */ protected void checkCollectionType(Collection c) { if (type != null) { for (Iterator iter = c.iterator(); iter.hasNext(); ) { Object element = iter.next(); checkType(element); } } } /** * Checks that the given object instance is of the correct type * otherwise a runtime exception is thrown */ protected void checkType(Object object) { if (object == null) { throw new NullPointerException("Sequences cannot contain null, use a List instead"); } if (type != null) { if (!type.isInstance(object)) { throw new IllegalArgumentException( "Invalid type of argument for sequence of type: " + type.getName() + " cannot add object: " + object); } } } }groovy-1.8.6/src/main/groovy/lang/Grapes.java0000644001501200150120000000506211627206700020442 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Sometimes we will need more than one grab per class, but we can only add * one annotation type per annotatable node. This class allows for multiple * grabs to be added. *

    * For example: *

    *

     * {@code @Grapes([@Grab(module='m1'), @Grab(module='m2')])}
     * class AnnotatedClass { ... }
     * 
    *

    * You can override an implicit transitive dependency by providing an explicit one. * E.g. htmlunit 2.6 normally uses xerces 2.9.1 but you can get 2.9.0 as follows: *

     * {@code @Grapes}([
     *     {@code @Grab}('net.sourceforge.htmlunit:htmlunit:2.6'),
     *     {@code @Grab}('xerces#xercesImpl;2.9.0')
     * ])
     * 
    * Obviously, only do this if you understand the consequences. *

    * You can also remove transitive dependencies altogether (provided you * know you don't need them) using {@code @GrabExclude}. * For example, here is how we would not grab the {@code logkit} and * {@code avalon-framework} transitive dependencies for Apache POI: *

     * {@code @Grapes}([
     *   {@code @Grab}("org.apache.poi#poi;3.5-beta6"),
     *   {@code @GrabExclude}("logkit:logkit"),
     *   {@code @GrabExclude}("avalon-framework#avalon-framework")
     * ])
     * import org.apache.poi.hssf.util.CellReference
     * assert new CellReference(0, 0, false, false).formatAsString() == 'A1'
     * assert new CellReference(1, 3).formatAsString() == '$D$2'
     * 
    * It is also sometimes also useful to use {@code @GrabConfig} to further adjust how dependencies * are grabbed. See {@code @GrabConfig} for further information. */ public @interface Grapes { Grab[] value(); /** * This will be pushed into the child grab annotations if the value is not * set in the child annotation already. *

    * This results in an effective change in the default value, which each @Grab * can still override */ boolean initClass() default true; } groovy-1.8.6/src/main/groovy/lang/Binding.java0000644001501200150120000000705111715031256020573 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.LinkedHashMap; import java.util.Map; /** * Represents the variable bindings of a script which can be altered * from outside the script object or created outside of a script and passed * into it. * *

    Binding instances are not supposed to be used in a multithreaded context. * * @author James Strachan * @version $Revision$ */ public class Binding extends GroovyObjectSupport { private Map variables; public Binding() { } public Binding(Map variables) { this.variables = variables; } /** * A helper constructor used in main(String[]) method calls * * @param args are the command line arguments from a main() */ public Binding(String[] args) { this(); setVariable("args", args); } /** * @param name the name of the variable to lookup * @return the variable value */ public Object getVariable(String name) { if (variables == null) throw new MissingPropertyException(name, this.getClass()); Object result = variables.get(name); if (result == null && !variables.containsKey(name)) { throw new MissingPropertyException(name, this.getClass()); } return result; } /** * Sets the value of the given variable * * @param name the name of the variable to set * @param value the new value for the given variable */ public void setVariable(String name, Object value) { if (variables == null) variables = new LinkedHashMap(); variables.put(name, value); } /** * Simple check for whether the binding contains a particular variable or not. * * @param name the name of the variable to check for */ public boolean hasVariable(String name) { return variables != null && variables.containsKey(name); } public Map getVariables() { if (variables == null) variables = new LinkedHashMap(); return variables; } /** * Overloaded to make variables appear as bean properties or via the subscript operator */ public Object getProperty(String property) { /** @todo we should check if we have the property with the metaClass instead of try/catch */ try { return super.getProperty(property); } catch (MissingPropertyException e) { return getVariable(property); } } /** * Overloaded to make variables appear as bean properties or via the subscript operator */ public void setProperty(String property, Object newValue) { /** @todo we should check if we have the property with the metaClass instead of try/catch */ try { super.setProperty(property, newValue); } catch (MissingPropertyException e) { setVariable(property, newValue); } } } groovy-1.8.6/src/main/groovy/lang/TracingInterceptor.java0000644001501200150120000000732511707612044023034 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; /* * This {@link Interceptor} traces method calls on the proxied object to a log. * By default, the log is simply

    System.out
    ; however, that can be * changed with the
    setWriter(Writer)
    method.

    * * A message will be written to output before a method is invoked and after a method * is invoked. If methods are nested, and invoke one another, then indentation * of two spaces is written.

    * * Here is an example usage on the ArrayList object:
    *
     * def proxy = ProxyMetaClass.getInstance(ArrayList.class)
     * proxy.interceptor = new TracingInterceptor()
     * proxy.use {
     *     def list = [1, 2, 3]
     *     assert 3 == list.size()
     *     assert list.contains(1)
     * }
     * 
    * Running this code produces this output: *
     * before java.util.ArrayList.size()
     * after  java.util.ArrayList.size()
     * before java.util.ArrayList.contains(java.lang.Integer)
     * after  java.util.ArrayList.contains(java.lang.Integer)
     * 
    */ public class TracingInterceptor implements Interceptor { protected Writer writer = new PrintWriter(System.out); private int indent = 0; /** * Returns the writer associated with this interceptor. */ public Writer getWriter() { return writer; } /** * Changes the writer associated with this interceptor. */ public void setWriter(Writer writer) { this.writer = writer; } public Object beforeInvoke(Object object, String methodName, Object[] arguments) { write(object, methodName, arguments, "before"); indent++ ; return null; } public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) { indent--; write(object, methodName, arguments, "after "); return result; } public boolean doInvoke() { return true; } private String indent(){ StringBuffer result = new StringBuffer(); for (int i=0; i 0) writer.write(", "); Object argument = arguments[i]; writer.write(argument.getClass().getName()); } writer.write(")"); } } groovy-1.8.6/src/main/groovy/lang/SpreadMap.java0000644001501200150120000000734111707612044021100 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Iterator; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Represents a spreadable map which extends java.util.HashMap. * * @author Pilho Kim */ public class SpreadMap extends HashMap { private Map mapData; private int hashCode; public SpreadMap(Object[] values) { mapData = new HashMap(values.length / 2); int i = 0; while (i < values.length) { mapData.put(values[i++], values[i++]); } } public SpreadMap(Map map) { this.mapData = map; } /** * @since 1.8.0 * @param list the list to make spreadable */ public SpreadMap(List list) { this(list.toArray()); } public Object get(Object obj) { return mapData.get(obj); } public Object put(Object key, Object value) { throw new RuntimeException("SpreadMap: " + this + " is an immutable map, and so (" + key + ": " + value + ") cannot be added."); } public Object remove(Object key) { throw new RuntimeException("SpreadMap: " + this + " is an immutable map, and so the key (" + key + ") cannot be deleted."); } public void putAll(Map t) { throw new RuntimeException("SpreadMap: " + this + " is an immutable map, and so the map (" + t + ") cannot be put in this spreadMap."); } public int size() { return mapData.keySet().size(); } public boolean equals(Object that) { if (that instanceof SpreadMap) { return equals((SpreadMap) that); } return false; } public boolean equals(SpreadMap that) { if (that == null) return false; if (size() == that.size()) { Iterator iter = mapData.keySet().iterator(); for (; iter.hasNext(); ) { Object key = iter.next(); if (! DefaultTypeTransformation.compareEqual(get(key), that.get(key)) ) { return false; } } return true; } return false; } public int hashCode() { if (hashCode == 0) { Iterator iter = mapData.keySet().iterator(); for (; iter.hasNext(); ) { Object key = iter.next(); int hash = (key != null) ? key.hashCode() : 0xbabe; hashCode ^= hash; } } return hashCode; } /** * @return the string expression of this */ public String toString() { if (mapData.isEmpty()) { return "*:[:]"; } StringBuffer buff = new StringBuffer("*:["); Iterator iter = mapData.keySet().iterator(); for (; iter.hasNext(); ) { Object key = iter.next(); buff.append(key + ":" + mapData.get(key)); if (iter.hasNext()) buff.append(", "); } buff.append("]"); return buff.toString(); } } groovy-1.8.6/src/main/groovy/lang/GrabResolver.java0000644001501200150120000000424411707612044021620 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; /** * Used to add a repository for resolving Grape dependencies. *

    * For example: *

     * {@code @GrabResolver}(name='restlet.org', root='http://maven.restlet.org')
     * {@code @Grab}(group='org.restlet', module='org.restlet', version='1.1.6')
     * class MyRestlet extends org.restlet.Restlet {
     *   // ...
     * }
     * 
    * By default, the Grapes subsystem uses an Ivy chained resolver. Each resolver * added using {@code @GrabResolver} is appended to the chain. By default, the grape * subsystem is shared globally, so added resolvers will become available for any subsequent * grab calls. Dependency resolution follows Ivy's artifact resolution which tries * to resolve artifacts in the order specified in the chain of resolvers. *

    * Further information about customising grape behavior can be found on the Grape documentation page: * http://groovy.codehaus.org/Grape. * * @author Merlyn Albery-Speyer */ @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) public @interface GrabResolver { String value() default ""; String name(); String root(); boolean m2Compatible() default true; } groovy-1.8.6/src/main/groovy/lang/GroovyCallable.java0000644001501200150120000000213611707612044022126 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.concurrent.Callable; /** * A special "marker" style interface allowing Groovy classes to implement both * Runnable and Callable yet give preference to Runnable (for backwards compatibility) * for APIs having both Runnable and Callable methods. You should generally NOT use this * method in your own code. * * @see java.util.concurrent.Callable * @since 1.8.0 */ public interface GroovyCallable extends Callable { } groovy-1.8.6/src/main/groovy/lang/GroovyLogTestCase.groovy0000644001501200150120000000551711715031256023215 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang import java.util.logging.* /** Helper class to spoof log entries as produced by calling arbitrary code. This allows non-intrusive testing of dependent objects without explicitly using Mock objects as long as those dependent objects do some proper logging. As a measure of last resort, it can be used on MetaClass to spoof it's log entries on 'invokeMethod'. @author Dierk Koenig @see GroovyLogTestCaseTest **/ class GroovyLogTestCase extends GroovyTestCase { /** Execute the given Closure with the according level for the Logger that is qualified by the qualifier and return the log output as a String. Qualifiers are usually package or class names. Existing log level and handlers are restored after execution. **/ static String stringLog (Level level, String qualifier, Closure yield){ // store old values Logger logger = Logger.getLogger(qualifier) def usesParentHandlers = logger.useParentHandlers // set new values logger.useParentHandlers = false def out = new ByteArrayOutputStream(1024) Handler stringHandler = new StreamHandler(out, new SimpleFormatter()) stringHandler.level = Level.ALL logger.addHandler(stringHandler) // any old handlers remain withLevel(level, qualifier, yield) // restore old values logger.level = Level.OFF // temporarily, to avoid logging the 3 stmts below stringHandler.flush() out.close() logger.removeHandler(stringHandler) logger.useParentHandlers = usesParentHandlers return out.toString() } /** Execute the given Closure with the according level for the Logger that is qualified by the qualifier. Qualifiers are usually package or class names. The log level is restored after execution. **/ static def withLevel(Level level, String qualifier, Closure yield){ // store old values Logger logger = Logger.getLogger(qualifier) def loglevel = logger.level // set new values if (!logger.isLoggable(level)) logger.level = level // use min value def result = yield() // restore old values logger.level = loglevel return result } }groovy-1.8.6/src/main/groovy/lang/MetaObjectProtocol.java0000644001501200150120000002267711715031256022773 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.List; /** *

    An interface that defines the API usable by clients of Groovy's Meta Object Protocol (MOP). These methods are * implemented by the reference implementation of the {@link groovy.lang.MetaClass} interface.

    * * @see MetaClassImpl * * @author John Wilson * @author Graeme Rocher */ public interface MetaObjectProtocol { /** * Obtain a list of all meta properties available on this meta class * * @see groovy.lang.MetaProperty * @return A list of MetaProperty instances */ List getProperties(); /** * Obtain a list of all the meta methods available on this meta class * * @see groovy.lang.MetaMethod * @return A list of MetaMethod instances */ List getMethods(); /** *

    Returns an object satisfying Groovy truth if the implementing MetaClass responds to * a method with the given name and arguments types. * *

    Note that this method's return value is based on realised methods and does not take into account * objects or classes that implement invokeMethod or methodMissing * *

    This method is "safe" in that it will always return a value and never throw an exception * * @param obj The object to inspect * @param name The name of the method of interest * @param argTypes The argument types to match against * @return A List of MetaMethods matching the argument types which will be empty if no matching methods exist */ List respondsTo(Object obj, String name, Object[] argTypes); /** *

    Returns an object satisfying Groovy truth if the implementing MetaClass responds to * a method with the given name regardless of arguments. In other words this method will * return for foo() and foo(String). * *

    Note that this method's return value is based on realised methods and does not take into account * objects or classes that implement invokeMethod or methodMissing * *

    This method is "safe" in that it will always return a value and never throw an exception * * @param obj The object to inspect * @param name The name of the method of interest * @return A List of MetaMethods which will be empty if no methods with the given name exist */ List respondsTo(Object obj, String name); /** *

    Returns true of the implementing MetaClass has a property of the given name * *

    Note that this method will only return true for realised properties and does not take into * account implementation of getProperty or propertyMissing * * @param obj The object to inspect * @param name The name of the property * @return The MetaProperty or null if it doesn't exist */ MetaProperty hasProperty(Object obj, String name); /** * Returns a MetaProperty for the given name or null if it doesn't exist * * @param name The name of the MetaProperty * @return A MetaProperty or null */ MetaProperty getMetaProperty(String name); /** * Retrieves a static MetaMethod for the given name and argument values, using the types of the arguments * to establish the chosen MetaMethod * * @param name The name of the MetaMethod * @param args The argument types * @return A MetaMethod or null if it doesn't exist */ MetaMethod getStaticMetaMethod(String name, Object[] args); /** * Retrieves an instance MetaMethod for the given name and argument values, using the types of the * argument values to establish the chosen MetaMethod * * @param name The name of the MetaMethod * @param args Array containing - 1) the argument values (using which their types are then inferred), or 2) the corresponding argument types * @return A MetaMethod or null if it doesn't exist */ MetaMethod getMetaMethod(String name, Object[] args); /** * Retrieves that Java Class that the attached Meta behaviours apply to * * @return The java.lang.Class instance */ Class getTheClass(); /** * Invokes a constructor for the given arguments. The MetaClass will attempt to pick the best argument which * matches the types of the objects passed within the arguments array * * @param arguments The arguments to the constructor * @return An instance of the java.lang.Class that this MetaObjectProtocol object applies to */ Object invokeConstructor(Object[] arguments); /** *

    Invokes a method on the given Object with the given name and arguments. The MetaClass will attempt to pick * the best method for the given name and arguments. If a method cannot be invoked a MissingMethodException will be * thrown.

    * * * @see groovy.lang.MissingMethodException * * @param object The instance which the method is invoked on * @param methodName The name of the method * @param arguments The arguments to the method * @return The return value of the method which is null if the return type is void */ Object invokeMethod(Object object, String methodName, Object[] arguments); /** *

    Invokes a method on the given object, with the given name and single argument.

    * * @see #invokeMethod(Object, String, Object[]) * * @param object The Object to invoke the method on * @param methodName The name of the method * @param arguments The argument to the method * @return The return value of the method which is null if the return type is void */ Object invokeMethod(Object object, String methodName, Object arguments); /** *

    Invokes a static method on the given Object with the given name and arguments.

    * *

    The Object can either be an instance of the class that this * MetaObjectProtocol instance applies to or the java.lang.Class instance itself. If a method cannot be invoked * a MissingMethodException is will be thrown

    * * @see groovy.lang.MissingMethodException * * @param object An instance of the class returned by the getTheClass() method or the class itself * @param methodName The name of the method * @param arguments The arguments to the method * @return The return value of the method which is null if the return type is void */ Object invokeStaticMethod(Object object, String methodName, Object[] arguments); /** *

    Retrieves a property of an instance of the class returned by the getTheClass() method.

    * *

    What this means is largely down to the MetaClass implementation, however the default case would result * in an attempt to invoke a JavaBean getter, or if no such getter exists a public field of the instance.

    * * @see MetaClassImpl * * @param object An instance of the class returned by the getTheClass() method * @param property The name of the property to retrieve the value for * @return The properties value */ Object getProperty(Object object, String property); /** *

    Sets a property of an instance of the class returned by the getTheClass() method.

    * *

    What this means is largely down to the MetaClass implementation, however the default case would result * in an attempt to invoke a JavaBean setter, or if no such setter exists to set a public field of the instance.

    * * @see MetaClassImpl * * @param object An instance of the class returned by the getTheClass() method * @param property The name of the property to set * @param newValue The new value of the property */ void setProperty(Object object, String property, Object newValue); /** *

    Retrieves an attribute of an instance of the class returned by the getTheClass() method.

    * *

    What this means is largely down to the MetaClass implementation, however the default case would result * in attempt to read a field of the instance.

    * * @see MetaClassImpl * * @param object An instance of the class returned by the getTheClass() method * @param attribute The name of the attribute to retrieve the value for * @return The attribute value */ Object getAttribute(Object object, String attribute); /** *

    Sets an attribute of an instance of the class returned by the getTheClass() method.

    * *

    What this means is largely down to the MetaClass implementation, however the default case would result * in an attempt to set a field of the instance.

    * * @see MetaClassImpl * * @param object An instance of the class returned by the getTheClass() method * @param attribute The name of the attribute to set * @param newValue The new value of the attribute */ void setAttribute(Object object, String attribute, Object newValue); } groovy-1.8.6/src/main/groovy/lang/IllegalPropertyAccessException.java0000644001501200150120000000345311627206700025342 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.reflect.Field; import java.lang.reflect.Modifier; /** * An exception occurred if a dynamic property dispatch fails with a * field not accessible. * * @author Jochen Theodorou * @version $Revision$ */ public class IllegalPropertyAccessException extends MissingPropertyException { private static String makeMessage(String propertyName, Class clazz, int modifiers, boolean isField) { String access = "private"; if (Modifier.isProtected(modifiers)) access = "protected"; if (Modifier.isPublic(modifiers)) access = "public"; String propertyType = "property"; if (isField) propertyType = "field"; return "Can not access the "+access+" "+propertyType+" "+propertyName+" in class "+clazz.getName(); } public IllegalPropertyAccessException(String propertyName, Class clazz, int modifiers) { super(makeMessage(propertyName,clazz,modifiers,false),propertyName,clazz); } public IllegalPropertyAccessException(Field field, Class clazz) { super(makeMessage(field.getName(),clazz,field.getModifiers(),true),field.getName(),clazz); } } groovy-1.8.6/src/main/groovy/lang/EmptyRange.java0000644001501200150120000001164211627206700021275 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import java.util.*; /** * Constructing Ranges like 0..<0 * @author Dierk Koenig * @author Edwin Tellman */ public class EmptyRange extends AbstractList implements Range { /** * The value at which the range originates (may be null). */ protected Comparable at; /** * Creates a new {@link EmptyRange}. * * @param at the value at which the range starts (may be null). */ public EmptyRange(Comparable at) { this.at = at; } /** * {@inheritDoc} */ public Comparable getFrom() { return at; } /** * {@inheritDoc} */ public Comparable getTo() { return at; } /** * Never true for an empty range. * * @return false */ public boolean isReverse() { return false; } /** * Never true for an empty range. * * @return false */ public boolean containsWithinBounds(Object o) { return false; } /** * {@inheritDoc} */ public String inspect() { return InvokerHelper.inspect(at) + "..<" + InvokerHelper.inspect(at); } /** * {@inheritDoc} */ public String toString() { return (null == at) ? "null..IndexOutOfBoundsException for an empty range. * * @throws IndexOutOfBoundsException always */ public Object get(int index) { throw new IndexOutOfBoundsException("can't get values from Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException always */ public boolean add(Object o) { throw new UnsupportedOperationException("cannot add to Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException("cannot add to Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public boolean addAll(Collection c) { throw new UnsupportedOperationException("cannot add to Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public boolean remove(Object o) { throw new UnsupportedOperationException("cannot remove from Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public Object remove(int index) { throw new UnsupportedOperationException("cannot remove from Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public boolean removeAll(Collection c) { throw new UnsupportedOperationException("cannot remove from Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public boolean retainAll(Collection c) { throw new UnsupportedOperationException("cannot retainAll in Empty Ranges"); } /** * Always throws UnsupportedOperationException for an empty range. * * @throws UnsupportedOperationException */ public Object set(int index, Object element) { throw new UnsupportedOperationException("cannot set in Empty Ranges"); } /** * Always does nothing for an empty range. */ public void step(int step, Closure closure) { } /** * Always returns an empty list for an empty range. */ public List step(int step) { return new ArrayList(); } } groovy-1.8.6/src/main/groovy/lang/Reference.java0000644001501200150120000000410411627206700021113 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.Serializable; /** * Represents a reference to a value * * @author James Strachan * @version $Revision$ */ public class Reference extends GroovyObjectSupport implements Serializable { private T value; public Reference() { } public Reference(T value) { this.value = value; } public Object getProperty(String property) { Object value = get(); if (value != null) { return InvokerHelper.getProperty(value, property); } return super.getProperty(property); } public void setProperty(String property, Object newValue) { Object value = get(); if (value != null) { InvokerHelper.setProperty(value, property, newValue); } else { super.setProperty(property, newValue); } } public Object invokeMethod(String name, Object args) { Object value = get(); if (value != null) { try { return InvokerHelper.invokeMethod(value, name, args); } catch (Exception e) { return super.invokeMethod(name, args); } } else { return super.invokeMethod(name, args); } } public T get() { return value; } public void set(T value) { this.value = value; } } groovy-1.8.6/src/main/groovy/lang/GroovyShell.java0000644001501200150120000007536011715031256021506 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import groovy.ui.GroovyMain; import groovy.security.GroovyCodeSourcePermission; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerInvocationException; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.Map; /** * Represents a groovy shell capable of running arbitrary groovy scripts * * @author James Strachan * @author Guillaume Laforge * @author Paul King * @version $Revision$ */ public class GroovyShell extends GroovyObjectSupport { public static final String DEFAULT_CODE_BASE = "/groovy/shell"; @Deprecated public static final String[] EMPTY_ARGS = {}; private Binding context; private int counter; private CompilerConfiguration config; private GroovyClassLoader loader; public static void main(String[] args) { GroovyMain.main(args); } public GroovyShell() { this(null, new Binding()); } public GroovyShell(Binding binding) { this(null, binding); } public GroovyShell(CompilerConfiguration config) { this(new Binding(), config); } public GroovyShell(Binding binding, CompilerConfiguration config) { this(null, binding, config); } public GroovyShell(ClassLoader parent, Binding binding) { this(parent, binding, CompilerConfiguration.DEFAULT); } public GroovyShell(ClassLoader parent) { this(parent, new Binding(), CompilerConfiguration.DEFAULT); } public GroovyShell(ClassLoader parent, Binding binding, final CompilerConfiguration config) { if (binding == null) { throw new IllegalArgumentException("Binding must not be null."); } if (config == null) { throw new IllegalArgumentException("Compiler configuration must not be null."); } final ClassLoader parentLoader = (parent!=null)?parent:GroovyShell.class.getClassLoader(); this.loader = AccessController.doPrivileged(new PrivilegedAction() { public GroovyClassLoader run() { return new GroovyClassLoader(parentLoader,config); } }); this.context = binding; this.config = config; } @Deprecated public void initializeBinding() { Map map = context.getVariables(); if (map.get("shell")==null) map.put("shell",this); } public void resetLoadedClasses() { loader.clearCache(); } /** * Creates a child shell using a new ClassLoader which uses the parent shell's * class loader as its parent * * @param shell is the parent shell used for the variable bindings and the parent class loader */ public GroovyShell(GroovyShell shell) { this(shell.loader, shell.context); } public Binding getContext() { return context; } public GroovyClassLoader getClassLoader() { return loader; } public Object getProperty(String property) { Object answer = getVariable(property); if (answer == null) { answer = super.getProperty(property); } return answer; } public void setProperty(String property, Object newValue) { setVariable(property, newValue); try { super.setProperty(property, newValue); } catch (GroovyRuntimeException e) { // ignore, was probably a dynamic property } } // // FIXME: Use List here, current version is not safe // /** * A helper method which runs the given script file with the given command line arguments * * @param scriptFile the file of the script to run * @param list the command line arguments to pass in */ public Object run(File scriptFile, List list) throws CompilationFailedException, IOException { String[] args = new String[list.size()]; return run(scriptFile, (String[]) list.toArray(args)); } /** * A helper method which runs the given cl script with the given command line arguments * * @param scriptText is the text content of the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @param list the command line arguments to pass in */ public Object run(String scriptText, String fileName, List list) throws CompilationFailedException { String[] args = new String[list.size()]; list.toArray(args); return run(scriptText, fileName, args); } /** * Runs the given script file name with the given command line arguments * * @param scriptFile the file name of the script to run * @param args the command line arguments to pass in */ public Object run(final File scriptFile, String[] args) throws CompilationFailedException, IOException { String scriptName = scriptFile.getName(); int p = scriptName.lastIndexOf("."); if (p++ >= 0) { if (scriptName.substring(p).equals("java")) { throw new CompilationFailedException(0, null); } } // Get the current context classloader and save it on the stack final Thread thread = Thread.currentThread(); //ClassLoader currentClassLoader = thread.getContextClassLoader(); class DoSetContext implements PrivilegedAction { ClassLoader classLoader; public DoSetContext(ClassLoader loader) { classLoader = loader; } public Object run() { thread.setContextClassLoader(classLoader); return null; } } AccessController.doPrivileged(new DoSetContext(loader)); // Parse the script, generate the class, and invoke the main method. This is a little looser than // if you are compiling the script because the JVM isn't executing the main method. Class scriptClass; try { scriptClass = AccessController.doPrivileged(new PrivilegedExceptionAction() { public Class run() throws CompilationFailedException, IOException { return loader.parseClass(scriptFile); } }); } catch (PrivilegedActionException pae) { Exception e = pae.getException(); if (e instanceof CompilationFailedException) { throw (CompilationFailedException) e; } else if (e instanceof IOException) { throw (IOException) e; } else { throw (RuntimeException) pae.getException(); } } return runScriptOrMainOrTestOrRunnable(scriptClass, args); // Set the context classloader back to what it was. //AccessController.doPrivileged(new DoSetContext(currentClassLoader)); } /** * if (theClass is a Script) { * run it like a script * } else if (theClass has a main method) { * run the main method * } else if (theClass instanceof GroovyTestCase) { * use the test runner to run it * } else if (theClass implements Runnable) { * if (theClass has a constructor with String[] params) * instantiate theClass with this constructor and run * else if (theClass has a no-args constructor) * instantiate theClass with the no-args constructor and run * } */ private Object runScriptOrMainOrTestOrRunnable(Class scriptClass, String[] args) { if (scriptClass == null) { return null; } if (Script.class.isAssignableFrom(scriptClass)) { // treat it just like a script if it is one Script script = null; try { script = (Script) scriptClass.newInstance(); } catch (InstantiationException e) { // ignore instantiation errors,, try to do main } catch (IllegalAccessException e) { // ignore instantiation errors, try to do main } if (script != null) { script.setBinding(context); script.setProperty("args", args); return script.run(); } } try { // let's find a main method scriptClass.getMethod("main", new Class[]{String[].class}); // if that main method exist, invoke it return InvokerHelper.invokeMethod(scriptClass, "main", new Object[]{args}); } catch (NoSuchMethodException e) { // if it implements Runnable, try to instantiate it if (Runnable.class.isAssignableFrom(scriptClass)) { return runRunnable(scriptClass, args); } // if it's a JUnit 3.8.x test, run it with an appropriate runner if (isJUnit3Test(scriptClass)) { return runJUnit3Test(scriptClass); } // if it's a JUnit 3.8.x test suite, run it with an appropriate runner if (isJUnit3TestSuite(scriptClass)) { return runJUnit3TestSuite(scriptClass); } // if it's a JUnit 4.x test, run it with an appropriate runner if (isJUnit4Test(scriptClass)) { return runJUnit4Test(scriptClass); } // if it's a TestNG tst, run it with an appropriate runner if (isTestNgTest(scriptClass)) { return runTestNgTest(scriptClass); } throw new GroovyRuntimeException("This script or class could not be run.\n" + "It should either: \n" + "- have a main method, \n" + "- be a JUnit test, TestNG test or extend GroovyTestCase, \n" + "- or implement the Runnable interface."); } } private Object runRunnable(Class scriptClass, String[] args) { Constructor constructor = null; Runnable runnable = null; Throwable reason = null; try { // first, fetch the constructor taking String[] as parameter constructor = scriptClass.getConstructor(new Class[]{(new String[]{}).getClass()}); try { // instantiate a runnable and run it runnable = (Runnable) constructor.newInstance(new Object[]{args}); } catch (Throwable t) { reason = t; } } catch (NoSuchMethodException e1) { try { // otherwise, find the default constructor constructor = scriptClass.getConstructor(new Class[]{}); try { // instantiate a runnable and run it runnable = (Runnable) constructor.newInstance(); } catch (InvocationTargetException ite) { throw new InvokerInvocationException(ite.getTargetException()); } catch (Throwable t) { reason = t; } } catch (NoSuchMethodException nsme) { reason = nsme; } } if (constructor != null && runnable != null) { runnable.run(); } else { throw new GroovyRuntimeException("This script or class was runnable but could not be run. ", reason); } return null; } /** * Run the specified class extending TestCase as a unit test. * This is done through reflection, to avoid adding a dependency to the JUnit framework. * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile * groovy scripts and classes would have to add another dependency on their classpath. * * @param scriptClass the class to be run as a unit test */ private Object runJUnit3Test(Class scriptClass) { try { Object testSuite = InvokerHelper.invokeConstructorOf("junit.framework.TestSuite",new Object[]{scriptClass}); return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite}); } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e); } } /** * Run the specified class extending TestSuite as a unit test. * This is done through reflection, to avoid adding a dependency to the JUnit framework. * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile * groovy scripts and classes would have to add another dependency on their classpath. * * @param scriptClass the class to be run as a unit test */ private Object runJUnit3TestSuite(Class scriptClass) { try { Object testSuite = InvokerHelper.invokeStaticMethod(scriptClass, "suite", new Object[]{}); return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite}); } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e); } } private Object runJUnit4Test(Class scriptClass) { try { return InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.JUnit4Utils", "realRunJUnit4Test", new Object[]{scriptClass, this.loader}); } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to run the JUnit 4 test.", e); } } private Object runTestNgTest(Class scriptClass) { try { return InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.TestNgUtils", "realRunTestNgTest", new Object[]{scriptClass, this.loader}); } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to run the TestNG test.", e); } } /** * Utility method to check through reflection if the class appears to be a * JUnit 3.8.x test, i.e.&nsbp;checks if it extends JUnit 3.8.x's TestCase. * * @param scriptClass the class we want to check * @return true if the class appears to be a test */ private boolean isJUnit3Test(Class scriptClass) { // check if the parsed class is a GroovyTestCase, // so that it is possible to run it as a JUnit test boolean isUnitTestCase = false; try { try { Class testCaseClass = this.loader.loadClass("junit.framework.TestCase"); // if scriptClass extends testCaseClass if (testCaseClass.isAssignableFrom(scriptClass)) { isUnitTestCase = true; } } catch (ClassNotFoundException e) { // fall through } } catch (Throwable e) { // fall through } return isUnitTestCase; } /** * Utility method to check through reflection if the class appears to be a * JUnit 3.8.x test suite, i.e.&nsbp;checks if it extends JUnit 3.8.x's TestSuite. * * @param scriptClass the class we want to check * @return true if the class appears to be a test */ private boolean isJUnit3TestSuite(Class scriptClass) { // check if the parsed class is a TestSuite, // so that it is possible to run it as a JUnit test boolean isUnitTestSuite = false; try { try { Class testSuiteClass = this.loader.loadClass("junit.framework.TestSuite"); // if scriptClass extends TestSuiteClass if (testSuiteClass.isAssignableFrom(scriptClass)) { isUnitTestSuite = true; } } catch (ClassNotFoundException e) { // fall through } } catch (Throwable e) { // fall through } return isUnitTestSuite; } /** * Utility method to check via reflection if the parsed class appears to be a JUnit4 * test, i.e.&nsbp;checks whether it appears to be using the relevant JUnit 4 annotations. * * @param scriptClass the class we want to check * @return true if the class appears to be a test */ private boolean isJUnit4Test(Class scriptClass) { // if we are running under Java 1.4 don't bother trying to check char version = System.getProperty("java.version").charAt(2); if (version < '5') { return false; } // check if there are appropriate class or method annotations // that suggest we have a JUnit 4 test boolean isTest = false; try { if (InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.JUnit4Utils", "realIsJUnit4Test", new Object[]{scriptClass, this.loader}) == Boolean.TRUE) { isTest = true; }; } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to invoke the JUnit 4 helper class.", e); } return isTest; } /** * Utility method to check via reflection if the parsed class appears to be a TestNG * test, i.e.&nsbp;checks whether it appears to be using the relevant TestNG annotations. * * @param scriptClass the class we want to check * @return true if the class appears to be a test */ private boolean isTestNgTest(Class scriptClass) { char version = System.getProperty("java.version").charAt(2); if (version < '5') { return false; } // check if there are appropriate class or method annotations // that suggest we have a TestNG test boolean isTest = false; try { if (InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.TestNgUtils", "realIsTestNgTest", new Object[]{scriptClass, this.loader}) == Boolean.TRUE) { isTest = true; }; } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Failed to invoke the TestNG helper class.", e); } return isTest; } /** * Runs the given script text with command line arguments * * @param scriptText is the text content of the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @param args the command line arguments to pass in */ public Object run(final String scriptText, final String fileName, String[] args) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE); } }); Class scriptClass = parseClass(gcs); return runScriptOrMainOrTestOrRunnable(scriptClass, args); } /** * Runs the given script with command line arguments * * @param in the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @param args the command line arguments to pass in */ public Object run(final Reader in, final String fileName, String[] args) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { return new GroovyCodeSource(in, fileName, DEFAULT_CODE_BASE); } }); Class scriptClass = parseClass(gcs); return runScriptOrMainOrTestOrRunnable(scriptClass, args); } /** * Runs the given script with command line arguments * * @param in the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @param args the command line arguments to pass in * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Object run(final InputStream in, final String fileName, String[] args) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { try { String scriptText = config.getSourceEncoding() != null ? DefaultGroovyMethods.getText(in, config.getSourceEncoding()) : DefaultGroovyMethods.getText(in); return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE); } catch (IOException e) { throw new RuntimeException("Impossible to read the content of the input stream for file named: " + fileName, e); } } }); Class scriptClass = parseClass(gcs); return runScriptOrMainOrTestOrRunnable(scriptClass, args); } public Object getVariable(String name) { return context.getVariables().get(name); } public void setVariable(String name, Object value) { context.setVariable(name, value); } /** * Evaluates some script against the current Binding and returns the result * * @param codeSource * @throws CompilationFailedException */ public Object evaluate(GroovyCodeSource codeSource) throws CompilationFailedException { Script script = parse(codeSource); script.setBinding(context); return script.run(); } /** * Evaluates some script against the current Binding and returns the result * * @param scriptText the text of the script */ public Object evaluate(final String scriptText) throws CompilationFailedException { return evaluate(scriptText, generateScriptName(), DEFAULT_CODE_BASE); } /** * Evaluates some script against the current Binding and returns the result * * @param scriptText the text of the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) */ public Object evaluate(String scriptText, String fileName) throws CompilationFailedException { return evaluate(scriptText, fileName, DEFAULT_CODE_BASE); } /** * Evaluates some script against the current Binding and returns the result. * The .class file created from the script is given the supplied codeBase */ public Object evaluate(final String scriptText, final String fileName, final String codeBase) throws CompilationFailedException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new GroovyCodeSourcePermission(codeBase)); } GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { return new GroovyCodeSource(scriptText, fileName, codeBase); } }); return evaluate(gcs); } /** * Evaluates some script against the current Binding and returns the result * * @param file is the file of the script (which is used to create the class name of the script) */ public Object evaluate(File file) throws CompilationFailedException, IOException { return evaluate(new GroovyCodeSource(file, config.getSourceEncoding())); } /** * Evaluates some script against the current Binding and returns the result * * @param in the stream reading the script */ public Object evaluate(Reader in) throws CompilationFailedException { return evaluate(in, generateScriptName()); } /** * Evaluates some script against the current Binding and returns the result * * @param in the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) */ public Object evaluate(Reader in, String fileName) throws CompilationFailedException { Script script = null; try { script = parse(in, fileName); script.setBinding(context); return script.run(); } finally { if (script != null) { InvokerHelper.removeClass(script.getClass()); } } } /** * Evaluates some script against the current Binding and returns the result * * @param in the stream reading the script * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Object evaluate(InputStream in) throws CompilationFailedException { return evaluate(in, generateScriptName()); } /** * Evaluates some script against the current Binding and returns the result * * @param in the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Object evaluate(InputStream in, String fileName) throws CompilationFailedException { Script script = null; try { script = parse(in, fileName); script.setBinding(context); return script.run(); } finally { if (script != null) { InvokerHelper.removeClass(script.getClass()); } } } /** * Parses the given script and returns it ready to be run * * @param reader the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @return the parsed script which is ready to be run via {@link Script#run()} */ public Script parse(final Reader reader, final String fileName) throws CompilationFailedException { return parse(new GroovyCodeSource(reader, fileName, DEFAULT_CODE_BASE)); } /** * Parses the given script and returns it ready to be run * * @param in the stream reading the script * @param fileName is the logical file name of the script (which is used to create the class name of the script) * @return the parsed script which is ready to be run via @link Script.run() * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Script parse(final InputStream in, final String fileName) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { try { String scriptText = config.getSourceEncoding() != null ? DefaultGroovyMethods.getText(in, config.getSourceEncoding()) : DefaultGroovyMethods.getText(in); return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE); } catch (IOException e) { throw new RuntimeException("Impossible to read the content of the input stream for file named: " + fileName, e); } } }); return parse(gcs); } /** * Parses the groovy code contained in codeSource and returns a java class. */ private Class parseClass(final GroovyCodeSource codeSource) throws CompilationFailedException { // Don't cache scripts return loader.parseClass(codeSource, false); } /** * Parses the given script and returns it ready to be run. When running in a secure environment * (-Djava.security.manager) codeSource.getCodeSource() determines what policy grants should be * given to the script. * * @param codeSource * @return ready to run script */ public Script parse(final GroovyCodeSource codeSource) throws CompilationFailedException { return InvokerHelper.createScript(parseClass(codeSource), context); } /** * Parses the given script and returns it ready to be run * * @param file is the file of the script (which is used to create the class name of the script) */ public Script parse(File file) throws CompilationFailedException, IOException { return parse(new GroovyCodeSource(file, config.getSourceEncoding())); } /** * Parses the given script and returns it ready to be run * * @param scriptText the text of the script */ public Script parse(String scriptText) throws CompilationFailedException { return parse(scriptText, generateScriptName()); } public Script parse(final String scriptText, final String fileName) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction() { public GroovyCodeSource run() { return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE); } }); return parse(gcs); } /** * Parses the given script and returns it ready to be run * * @param in the stream reading the script */ public Script parse(Reader in) throws CompilationFailedException { return parse(in, generateScriptName()); } /** * Parses the given script and returns it ready to be run * * @param in the stream reading the script * * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong encoding issues. */ public Script parse(InputStream in) throws CompilationFailedException { return parse(in, generateScriptName()); } protected synchronized String generateScriptName() { return "Script" + (++counter) + ".groovy"; } } groovy-1.8.6/src/main/groovy/lang/MetaMethod.java0000644001501200150120000002100011707612044021237 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ParameterTypes; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MetaClassHelper; import java.lang.reflect.Modifier; /** * Represents a Method on a Java object a little like {@link java.lang.reflect.Method} * except without using reflection to invoke the method * * @author James Strachan * @author Alex Tkachman * @version $Revision$ */ public abstract class MetaMethod extends ParameterTypes implements Cloneable { private String signature; private String mopName; public MetaMethod() { } public MetaMethod(Class [] pt) { super (pt); } public abstract int getModifiers(); public abstract String getName(); public abstract Class getReturnType(); public abstract CachedClass getDeclaringClass(); public abstract Object invoke(Object object, Object[] arguments); /** * Checks that the given parameters are valid to call this method * * @param arguments the arguments to check * @throws IllegalArgumentException if the parameters are not valid */ public void checkParameters(Class[] arguments) { // lets check that the argument types are valid if (!isValidMethod(arguments)) { throw new IllegalArgumentException( "Parameters to method: " + getName() + " do not match types: " + InvokerHelper.toString(getParameterTypes()) + " for arguments: " + InvokerHelper.toString(arguments)); } } public boolean isMethod(MetaMethod method) { return getName().equals(method.getName()) && getModifiers() == method.getModifiers() && getReturnType().equals(method.getReturnType()) && equal(getParameterTypes(), method.getParameterTypes()); } protected static boolean equal(CachedClass[] a, Class[] b) { if (a.length == b.length) { for (int i = 0, size = a.length; i < size; i++) { if (!a[i].getTheClass().equals(b[i])) { return false; } } return true; } return false; } protected static boolean equal(CachedClass[] a, CachedClass[] b) { if (a.length == b.length) { for (int i = 0, size = a.length; i < size; i++) { if (a[i] != b[i]) { return false; } } return true; } return false; } public String toString() { return super.toString() + "[name: " + getName() + " params: " + InvokerHelper.toString(getParameterTypes()) + " returns: " + getReturnType() + " owner: " + getDeclaringClass() + "]"; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new GroovyRuntimeException("This should never happen", e); } } public boolean isStatic() { return (getModifiers() & Modifier.STATIC) != 0; } public boolean isAbstract() { return (getModifiers() & Modifier.ABSTRACT) != 0; } public final boolean isPrivate() { return (getModifiers() & Modifier.PRIVATE) != 0; } public final boolean isProtected() { return (getModifiers() & Modifier.PROTECTED) != 0; } public final boolean isPublic() { return (getModifiers() & Modifier.PUBLIC) != 0; } /** * @param method the method to compare against * @return true if the given method has the same name, parameters, return type * and modifiers but may be defined on another type */ public final boolean isSame(MetaMethod method) { return getName().equals(method.getName()) && compatibleModifiers(getModifiers(), method.getModifiers()) && getReturnType().equals(method.getReturnType()) && equal(getParameterTypes(), method.getParameterTypes()); } private static boolean compatibleModifiers(int modifiersA, int modifiersB) { int mask = Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC | Modifier.STATIC; return (modifiersA & mask) == (modifiersB & mask); } public boolean isCacheable() { return true; } public String getDescriptor() { return BytecodeHelper.getMethodDescriptor(getReturnType(), getNativeParameterTypes()); } public synchronized String getSignature() { if (signature == null) { CachedClass [] parameters = getParameterTypes(); final String name = getName(); StringBuffer buf = new StringBuffer(name.length()+parameters.length*10); buf.append(getReturnType().getName()); // buf.append(' '); buf.append(name); buf.append('('); for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); } buf.append(parameters[i].getName()); } buf.append(')'); signature = buf.toString(); } return signature; } public String getMopName() { if (mopName == null) { String name = getName(); CachedClass declaringClass = getDeclaringClass(); if (Modifier.isPrivate(getModifiers())) mopName = new StringBuffer().append("this$").append(declaringClass.getSuperClassDistance()).append("$").append(name).toString(); else mopName = new StringBuffer().append("super$").append(declaringClass.getSuperClassDistance()).append("$").append(name).toString(); } return mopName; } public final RuntimeException processDoMethodInvokeException (Exception e, Object object, Object [] argumentArray) { // if (e instanceof IllegalArgumentException) { // //TODO: test if this is OK with new MOP, should be changed! // // we don't want the exception being unwrapped if it is a IllegalArgumentException // // but in the case it is for example a IllegalThreadStateException, we want the unwrapping // // from the runtime // //Note: the reason we want unwrapping sometimes and sometimes not is that the method // // invocation tries to invoke the method with and then reacts with type transformation // // if the invocation failed here. This is OK for IllegalArgumentException, but it is // // possible that a Reflector will be used to execute the call and then an Exception from inside // // the method is not wrapped in a InvocationTargetException and we will end here. // boolean setReason = e.getClass() != IllegalArgumentException.class || this instanceof org.codehaus.groovy.reflection.GeneratedMetaMethod; // return MetaClassHelper.createExceptionText("failed to invoke method: ", this, object, argumentArray, e, setReason); // } if (e instanceof RuntimeException) return (RuntimeException) e; return MetaClassHelper.createExceptionText("failed to invoke method: ", this, object, argumentArray, e, true); } // This method is not final but it should be overloaded very carefully and only by generated methods // there is no guarantee that it will be called public Object doMethodInvoke(Object object, Object[] argumentArray) { argumentArray = coerceArgumentsToClasses(argumentArray); try { return invoke(object, argumentArray); } catch (Exception e) { throw processDoMethodInvokeException(e, object, argumentArray); } } } groovy-1.8.6/src/main/groovy/lang/GroovyObjectSupport.java0000644001501200150120000000336211627206700023233 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; /** * A useful base class for Java objects wishing to be Groovy objects * * @author James Strachan * @version $Revision$ */ public abstract class GroovyObjectSupport implements GroovyObject { // never persist the MetaClass private transient MetaClass metaClass; public GroovyObjectSupport() { this.metaClass = InvokerHelper.getMetaClass(this.getClass()); } public Object getProperty(String property) { return getMetaClass().getProperty(this, property); } public void setProperty(String property, Object newValue) { getMetaClass().setProperty(this, property, newValue); } public Object invokeMethod(String name, Object args) { return getMetaClass().invokeMethod(this, name, args); } public MetaClass getMetaClass() { if (metaClass == null) { metaClass = InvokerHelper.getMetaClass(getClass()); } return metaClass; } public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } } groovy-1.8.6/src/main/groovy/lang/MetaArrayLengthProperty.java0000644001501200150120000000300711627206700024012 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; /** * Represents a property on a bean which may have a getter and/or a setter * * @author James Strachan * @version $Revision$ */ public class MetaArrayLengthProperty extends MetaProperty { public MetaArrayLengthProperty() { super("length", int.class); } /** * @return the property of the given object */ public Object getProperty(Object object) { return java.lang.reflect.Array.getLength(object); } /** * Sets the property on the given object to the new value * * @param object on which to set the property * @param newValue the new value of the property * @throws RuntimeException if the property could not be set */ public void setProperty(Object object, Object newValue) { throw new ReadOnlyPropertyException("length", object.getClass()); } } groovy-1.8.6/src/main/groovy/lang/Range.java0000644001501200150120000000562011627206700020255 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.List; /** * A Range represents the list of all items obtained by starting from a * from value and calling next() successively * until you reach the to value. For a reverse range, * the list is obtained by starting at the to value and * successively calling previous() until the from * value is reached. * * @author James Strachan * @version $Revision$ */ public interface Range extends List { /** * The lower value in the range. * * @return the lower value in the range. */ Comparable getFrom(); /** * The upper value in the range. * * @return the upper value in the range */ Comparable getTo(); /** * Indicates whether this is a reverse range which iterates backwards * starting from the to value and ending on the from value * * @return true if this is a reverse range */ boolean isReverse(); /** * Indicates whether an object is greater than or equal to the from * value for the range and less than or equal to the to value. * * @param o the object to check against the boundaries of the range * @return true if the object is between the from and to values */ boolean containsWithinBounds(Object o); /** * Steps through the range, calling a closure for each number. * * @param step the amount by which to step. If negative, steps through the * range backwards. * @param closure the {@link Closure} to call */ void step(int step, Closure closure); /** * Forms a list by stepping through the range by the indicated interval. * * @param step the amount by which to step. If negative, steps through the * range backwards. * @return the list formed by stepping through the range by the indicated * interval. */ List step(int step); /** * @return the verbose {@link String} representation of this {@link Range} as would be typed into a console * to create the {@link Range} instance */ String inspect(); } groovy-1.8.6/src/main/groovy/lang/ExpandoMetaClassCreationHandle.java0000644001501200150120000000667111627206700025224 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import groovy.lang.MetaClassRegistry.MetaClassCreationHandle; import org.codehaus.groovy.reflection.ClassInfo; /** *

    A handle for the MetaClassRegistry that changes all classes loaded into the Grails VM * to use ExpandoMetaClass instances * *

    The handle should be registered with the Groovy runtime before Groovy loads, for example * in your main method. * * GroovySystem.metaClassRegistry.metaClassCreationHandle = new ExpandoMetaClassCreationHandle() * * @see groovy.lang.MetaClassRegistry * @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle * @see org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl#setMetaClassCreationHandle(groovy.lang.MetaClassRegistry.MetaClassCreationHandle) * * @author Graeme Rocher * @since 1.5 */ public class ExpandoMetaClassCreationHandle extends MetaClassCreationHandle { public static final ExpandoMetaClassCreationHandle instance = new ExpandoMetaClassCreationHandle(); /* (non-Javadoc) * @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle#create(java.lang.Class, groovy.lang.MetaClassRegistry) */ protected MetaClass createNormalMetaClass(Class theClass, MetaClassRegistry registry) { if(theClass != ExpandoMetaClass.class) { return new ExpandoMetaClass(theClass, true, true); } else { return super.createNormalMetaClass(theClass, registry); } } /** * Registers a modified ExpandoMetaClass with the creation handle * * @param emc The EMC */ public void registerModifiedMetaClass(ExpandoMetaClass emc) { final Class klazz = emc.getJavaClass(); GroovySystem.getMetaClassRegistry().setMetaClass(klazz,emc); } public boolean hasModifiedMetaClass(ExpandoMetaClass emc) { return emc.getClassInfo().getModifiedExpando() != null; } /** *

    Enables the ExpandoMetaClassCreationHandle with the registry * * ExpandoMetaClassCreationHandle.enable(); * */ public static void enable() { final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); synchronized (metaClassRegistry) { if (metaClassRegistry.getMetaClassCreationHandler() != instance) { ClassInfo.clearModifiedExpandos(); metaClassRegistry.setMetaClassCreationHandle(instance); } } } public static void disable() { final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); synchronized (metaClassRegistry) { if (metaClassRegistry.getMetaClassCreationHandler() == instance) { ClassInfo.clearModifiedExpandos(); metaClassRegistry.setMetaClassCreationHandle(new MetaClassCreationHandle()); } } } } groovy-1.8.6/src/main/groovy/lang/MetaClassImpl.java0000644001501200150120000043647111715031256021733 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedConstructor; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.reflection.GeneratedMetaMethod; import org.codehaus.groovy.reflection.ParameterTypes; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.ConvertedClosure; import org.codehaus.groovy.runtime.CurriedClosure; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.InvokerInvocationException; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.MethodClosure; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.ConstructorSite; import org.codehaus.groovy.runtime.callsite.MetaClassConstructorSite; import org.codehaus.groovy.runtime.callsite.PogoMetaClassSite; import org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite; import org.codehaus.groovy.runtime.callsite.PojoMetaClassSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.callsite.StaticMetaClassSite; import org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite; import org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod; import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl; import org.codehaus.groovy.runtime.metaclass.MetaMethodIndex; import org.codehaus.groovy.runtime.metaclass.MethodSelectionException; import org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack; import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed; import org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack; import org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaMethod; import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod; import org.codehaus.groovy.runtime.metaclass.NewMetaMethod; import org.codehaus.groovy.runtime.metaclass.NewStaticMetaMethod; import org.codehaus.groovy.runtime.metaclass.TransformMetaMethod; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.typehandling.NumberMathModificationInfo; import org.codehaus.groovy.runtime.wrappers.Wrapper; import org.codehaus.groovy.util.ComplexKeyHashMap; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.util.SingleKeyHashMap; import org.objectweb.asm.ClassVisitor; import java.beans.BeanInfo; import java.beans.EventSetDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; /** * Allows methods to be dynamically added to existing classes at runtime * * @author James Strachan * @author Guillaume Laforge * @author Jochen Theodorou * @author Graeme Rocher * @author Alex Tkachman * @author Roshan Dawrani * @version $Revision$ * @see groovy.lang.MetaClass */ public class MetaClassImpl implements MetaClass, MutableMetaClass { private static final String CLOSURE_CALL_METHOD = "call"; private static final String CLOSURE_DO_CALL_METHOD = "doCall"; protected static final String STATIC_METHOD_MISSING = "$static_methodMissing"; protected static final String STATIC_PROPERTY_MISSING = "$static_propertyMissing"; protected static final String METHOD_MISSING = "methodMissing"; protected static final String PROPERTY_MISSING = "propertyMissing"; private static final String GET_PROPERTY_METHOD = "getProperty"; private static final String SET_PROPERTY_METHOD = "setProperty"; protected static final String INVOKE_METHOD_METHOD = "invokeMethod"; private static final Class[] METHOD_MISSING_ARGS = new Class[]{String.class, Object.class}; private static final Class[] GETTER_MISSING_ARGS = new Class[]{String.class}; private static final Class[] SETTER_MISSING_ARGS = METHOD_MISSING_ARGS; private static final Comparator CACHED_CLASS_NAME_COMPARATOR = new Comparator() { public int compare(final CachedClass o1, final CachedClass o2) { return o1.getName().compareTo(o2.getName()); } }; protected final Class theClass; protected final CachedClass theCachedClass; private static final MetaMethod[] EMPTY = new MetaMethod[0]; protected MetaMethod getPropertyMethod; protected MetaMethod invokeMethodMethod; protected MetaMethod setPropertyMethod; public final CachedClass getTheCachedClass() { return theCachedClass; } protected MetaClassRegistry registry; protected final boolean isGroovyObject; protected final boolean isMap; private ClassNode classNode; private final Index classPropertyIndex = new MethodIndex(); private Index classPropertyIndexForSuper = new MethodIndex(); private final SingleKeyHashMap staticPropertyIndex = new SingleKeyHashMap(); private final Map listeners = new HashMap(); private FastArray constructors; private final List allMethods = new ArrayList(); private boolean initialized; // we only need one of these that can be reused over and over. private final MetaProperty arrayLengthProperty = new MetaArrayLengthProperty(); private static final MetaMethod AMBIGUOUS_LISTENER_METHOD = new DummyMetaMethod(); private static final Object[] EMPTY_ARGUMENTS = {}; private final Set newGroovyMethodsSet = new HashSet(); private MetaMethod genericGetMethod; private MetaMethod genericSetMethod; private MetaMethod propertyMissingGet; private MetaMethod propertyMissingSet; private MetaMethod methodMissing; private MetaMethodIndex.Header mainClassMethodHeader; protected final MetaMethodIndex metaMethodIndex; private final MetaMethod [] myNewMetaMethods; private final MetaMethod [] additionalMetaMethods; public MetaClassImpl(final Class theClass, MetaMethod [] add) { this.theClass = theClass; theCachedClass = ReflectionCache.getCachedClass(theClass); this.isGroovyObject = GroovyObject.class.isAssignableFrom(theClass); this.isMap = Map.class.isAssignableFrom(theClass); this.registry = GroovySystem.getMetaClassRegistry(); metaMethodIndex = new MetaMethodIndex(theCachedClass); final MetaMethod[] metaMethods = theCachedClass.getNewMetaMethods(); if (add != null && !(add.length == 0)) { ArrayList arr = new ArrayList(); arr.addAll(Arrays.asList(metaMethods)); arr.addAll(Arrays.asList(add)); myNewMetaMethods = arr.toArray(new MetaMethod[arr.size()]); additionalMetaMethods = metaMethods; } else { myNewMetaMethods = metaMethods; additionalMetaMethods = EMPTY; } } public MetaClassImpl(final Class theClass) { this(theClass, null); } public MetaClassImpl(MetaClassRegistry registry, final Class theClass, MetaMethod add []) { this(theClass, add); this.registry = registry; this.constructors = new FastArray(theCachedClass.getConstructors()); } public MetaClassImpl(MetaClassRegistry registry, final Class theClass) { this(registry, theClass, null); } /** * @see MetaObjectProtocol#respondsTo(Object, String, Object[]) */ public List respondsTo(Object obj, String name, Object[] argTypes) { Class[] classes = MetaClassHelper.castArgumentsToClassArray(argTypes); MetaMethod m = getMetaMethod(name, classes); List methods = new ArrayList(); if (m != null) { methods.add(m); } return methods; } /** * @see MetaObjectProtocol#respondsTo(Object, String) */ public List respondsTo(final Object obj, final String name) { final Object o = getMethods(getTheClass(), name, false); if (o instanceof FastArray) return ((FastArray) o).toList(); else return Collections.singletonList(o); } /** * @see MetaObjectProtocol#hasProperty(Object,String) */ public MetaProperty hasProperty(Object obj, String name) { return getMetaProperty(name); } /** * @see MetaObjectProtocol#getMetaProperty(String) */ public MetaProperty getMetaProperty(String name) { SingleKeyHashMap propertyMap = classPropertyIndex.getNotNull(theCachedClass); if (propertyMap.containsKey(name)) { return (MetaProperty) propertyMap.get(name); } else if (staticPropertyIndex.containsKey(name)) { return (MetaProperty) staticPropertyIndex.get(name); } else { propertyMap = classPropertyIndexForSuper.getNotNull(theCachedClass); if (propertyMap.containsKey(name)) return (MetaProperty) propertyMap.get(name); else { CachedClass superClass = theCachedClass; while (superClass != null && superClass != ReflectionCache.OBJECT_CLASS) { final MetaBeanProperty property = findPropertyInClassHierarchy(name, superClass); if (property != null) { onSuperPropertyFoundInHierarchy(property); return property; } superClass = superClass.getCachedSuperClass(); } return null; } } } /** * @see MetaObjectProtocol#getStaticMetaMethod(String, Object[]) */ public MetaMethod getStaticMetaMethod(String name, Object[] argTypes) { Class[] classes = MetaClassHelper.castArgumentsToClassArray(argTypes); return pickStaticMethod(name, classes); } /** * @see MetaObjectProtocol#getMetaMethod(String, Object[]) */ public MetaMethod getMetaMethod(String name, Object[] argTypes) { Class[] classes = MetaClassHelper.castArgumentsToClassArray(argTypes); return pickMethod(name, classes); } public Class getTheClass() { return this.theClass; } public boolean isGroovyObject() { return isGroovyObject; } private void fillMethodIndex() { mainClassMethodHeader = metaMethodIndex.getHeader(theClass); LinkedList superClasses = getSuperClasses(); CachedClass firstGroovySuper = calcFirstGroovySuperClass(superClasses); Set interfaces = theCachedClass.getInterfaces(); addInterfaceMethods(interfaces); populateMethods(superClasses, firstGroovySuper); inheritInterfaceNewMetaMethods(interfaces); if (isGroovyObject) { metaMethodIndex.copyMethodsToSuper(); connectMultimethods(superClasses, firstGroovySuper); removeMultimethodsOverloadedWithPrivateMethods(); replaceWithMOPCalls(theCachedClass.mopMethods); } } private void populateMethods(LinkedList superClasses, CachedClass firstGroovySuper) { Iterator iter = superClasses.iterator(); MetaMethodIndex.Header header = metaMethodIndex.getHeader(firstGroovySuper.getTheClass()); CachedClass c; for (; iter.hasNext();) { c = (CachedClass) iter.next(); CachedMethod[] cachedMethods = c.getMethods(); for (CachedMethod metaMethod : cachedMethods) { addToAllMethodsIfPublic(metaMethod); if (!metaMethod.isPrivate() || c == firstGroovySuper) addMetaMethodToIndex(metaMethod, header); } MetaMethod[] cachedMethods1 = getNewMetaMethods(c); for (final MetaMethod method : cachedMethods1) { if (!newGroovyMethodsSet.contains(method)) { newGroovyMethodsSet.add(method); addMetaMethodToIndex(method, header); } } if (c == firstGroovySuper) break; } MetaMethodIndex.Header last = header; for (;iter.hasNext();) { c = (CachedClass) iter.next(); header = metaMethodIndex.getHeader(c.getTheClass()); if (last != null) { metaMethodIndex.copyNonPrivateMethods(last, header); } last = header; for (CachedMethod metaMethod : c.getMethods()) { addToAllMethodsIfPublic(metaMethod); addMetaMethodToIndex(metaMethod, header); } for (final MetaMethod method : getNewMetaMethods(c)) { if (!newGroovyMethodsSet.contains(method)) { newGroovyMethodsSet.add(method); addMetaMethodToIndex(method, header); } } } } private MetaMethod[] getNewMetaMethods(CachedClass c) { if (theCachedClass != c) return c.getNewMetaMethods(); return myNewMetaMethods; } private void addInterfaceMethods(Set interfaces) { MetaMethodIndex.Header header = metaMethodIndex.getHeader(theClass); for (CachedClass c : interfaces) { final CachedMethod[] m = c.getMethods(); for (int i = 0; i != m.length; ++i) { MetaMethod method = m[i]; addMetaMethodToIndex(method, header); } } } protected LinkedList getSuperClasses() { LinkedList superClasses = new LinkedList(); if (theClass.isInterface()) { superClasses.addFirst(ReflectionCache.OBJECT_CLASS); } else { for (CachedClass c = theCachedClass; c != null; c = c.getCachedSuperClass()) { superClasses.addFirst(c); } if (theCachedClass.isArray && theClass != Object[].class && !theClass.getComponentType().isPrimitive()) { superClasses.addFirst(ReflectionCache.OBJECT_ARRAY_CLASS); } } return superClasses; } private void removeMultimethodsOverloadedWithPrivateMethods() { MethodIndexAction mia = new MethodIndexAction() { public boolean skipClass(Class clazz) { return clazz == theClass; } public void methodNameAction(Class clazz, MetaMethodIndex.Entry e) { if (e.methods == null) return; boolean hasPrivate = false; if (e.methods instanceof FastArray) { FastArray methods = (FastArray) e.methods; final int len = methods.size(); final Object[] data = methods.getArray(); for (int i = 0; i != len; ++i) { MetaMethod method = (MetaMethod) data[i]; if (method.isPrivate() && clazz == method.getDeclaringClass().getTheClass()) { hasPrivate = true; break; } } } else { MetaMethod method = (MetaMethod) e.methods; if (method.isPrivate() && clazz == method.getDeclaringClass().getTheClass()) { hasPrivate = true; } } if (!hasPrivate) return; // We have private methods for that name, so remove the // multimethods. That is the same as in our index for // super, so just copy the list from there. It is not // possible to use a pointer here, because the methods // in the index for super are replaced later by MOP // methods like super$5$foo final Object o = e.methodsForSuper; if (o instanceof FastArray) e.methods = ((FastArray) o).copy(); else e.methods = o; } }; mia.iterate(); } private void replaceWithMOPCalls(final CachedMethod[] mopMethods) { // no MOP methods if not a child of GroovyObject if (!isGroovyObject) return; class MOPIter extends MethodIndexAction { boolean useThis; public boolean skipClass(CachedClass clazz) { return !useThis && clazz == theCachedClass; } public void methodNameAction(Class clazz, MetaMethodIndex.Entry e) { if (useThis) { if (e.methods == null) return; if (e.methods instanceof FastArray) { FastArray methods = (FastArray) e.methods; processFastArray(methods); } else { MetaMethod method = (MetaMethod) e.methods; if (method instanceof NewMetaMethod) return; if (useThis ^ Modifier.isPrivate(method.getModifiers())) return; String mopName = method.getMopName(); int index = Arrays.binarySearch(mopMethods, mopName, CachedClass.CachedMethodComparatorWithString.INSTANCE); if (index >= 0) { int from = index; while (from > 0 && mopMethods[from-1].getName().equals(mopName)) from--; int to = index; while (to < mopMethods.length-1 && mopMethods[to+1].getName().equals(mopName)) to++; int matchingMethod = findMatchingMethod(mopMethods, from, to, method); if (matchingMethod != -1) { e.methods = mopMethods[matchingMethod]; } } } } else { if (e.methodsForSuper == null) return; if (e.methodsForSuper instanceof FastArray) { FastArray methods = (FastArray) e.methodsForSuper; processFastArray(methods); } else { MetaMethod method = (MetaMethod) e.methodsForSuper; if (method instanceof NewMetaMethod) return; if (useThis ^ Modifier.isPrivate(method.getModifiers())) return; String mopName = method.getMopName(); int index = Arrays.binarySearch(mopMethods, mopName, CachedClass.CachedMethodComparatorWithString.INSTANCE); if (index >= 0) { int from = index; while (from > 0 && mopMethods[from-1].getName().equals(mopName)) from--; int to = index; while (to < mopMethods.length-1 && mopMethods[to+1].getName().equals(mopName)) to++; int matchingMethod = findMatchingMethod(mopMethods, from, to, method); if (matchingMethod != -1) { e.methodsForSuper = mopMethods[matchingMethod]; } } } } } private void processFastArray(FastArray methods) { final int len = methods.size(); final Object[] data = methods.getArray(); for (int i = 0; i != len; ++i) { MetaMethod method = (MetaMethod) data[i]; if (method instanceof NewMetaMethod) continue; boolean isPrivate = Modifier.isPrivate(method.getModifiers()); if (useThis ^ isPrivate) continue; String mopName = method.getMopName(); int index = Arrays.binarySearch(mopMethods, mopName, CachedClass.CachedMethodComparatorWithString.INSTANCE); if (index >= 0) { int from = index; while (from > 0 && mopMethods[from-1].getName().equals(mopName)) from--; int to = index; while (to < mopMethods.length-1 && mopMethods[to+1].getName().equals(mopName)) to++; int matchingMethod = findMatchingMethod(mopMethods, from, to, method); if (matchingMethod != -1) { methods.set(i, mopMethods[matchingMethod]); } } } } } MOPIter iter = new MOPIter(); // replace all calls for super with the correct MOP method iter.useThis = false; iter.iterate(); // replace all calls for this with the correct MOP method iter.useThis = true; iter.iterate(); } private void inheritInterfaceNewMetaMethods(Set interfaces) { // add methods declared by DGM for interfaces for (CachedClass cls : interfaces) { MetaMethod methods[] = getNewMetaMethods(cls); for (MetaMethod method : methods) { if (!newGroovyMethodsSet.contains(method)) { newGroovyMethodsSet.add(method); } addMetaMethodToIndex(method, mainClassMethodHeader); } } } private void connectMultimethods(List superClasses, CachedClass firstGroovyClass) { superClasses = DefaultGroovyMethods.reverse(superClasses); MetaMethodIndex.Header last = null; for (Iterator iter = superClasses.iterator(); iter.hasNext();) { CachedClass c = (CachedClass) iter.next(); MetaMethodIndex.Header methodIndex = metaMethodIndex.getHeader(c.getTheClass()); // We don't copy DGM methods to superclasses' indexes // The reason we can do that is particular set of DGM methods in use, // if at some point we will define DGM method for some Groovy class or // for a class derived from such, we will need to revise this condition. // It saves us a lot of space and some noticeable time if (last != null) metaMethodIndex.copyNonPrivateNonNewMetaMethods(last, methodIndex); last = methodIndex; if (c == firstGroovyClass) break; } } private CachedClass calcFirstGroovySuperClass(Collection superClasses) { if (theCachedClass.isInterface) return ReflectionCache.OBJECT_CLASS; CachedClass firstGroovy = null; Iterator iter = superClasses.iterator(); for (; iter.hasNext();) { CachedClass c = (CachedClass) iter.next(); if (GroovyObject.class.isAssignableFrom(c.getTheClass())) { firstGroovy = c; break; } } if (firstGroovy == null) firstGroovy = theCachedClass; else { if (firstGroovy.getTheClass() == GroovyObjectSupport.class && iter.hasNext()) { firstGroovy = (CachedClass) iter.next(); if (firstGroovy.getTheClass() == Closure.class && iter.hasNext()) { firstGroovy = (CachedClass) iter.next(); } } } return GroovyObject.class.isAssignableFrom(firstGroovy.getTheClass()) ? firstGroovy.getCachedSuperClass() : firstGroovy; } /** * @return all the normal instance methods available on this class for the * given name */ private Object getMethods(Class sender, String name, boolean isCallToSuper) { Object answer; final MetaMethodIndex.Entry entry = metaMethodIndex.getMethods(sender, name); if (entry == null) answer = FastArray.EMPTY_LIST; else if (isCallToSuper) { answer = entry.methodsForSuper; } else { answer = entry.methods; } if (answer == null) answer = FastArray.EMPTY_LIST; if (!isCallToSuper) { List used = GroovyCategorySupport.getCategoryMethods(name); if (used != null) { FastArray arr; if (answer instanceof MetaMethod) { arr = new FastArray(); arr.add(answer); } else arr = ((FastArray) answer).copy(); for (Iterator iter = used.iterator(); iter.hasNext();) { MetaMethod element = (MetaMethod) iter.next(); if (!element.getDeclaringClass().getTheClass().isAssignableFrom(sender)) continue; filterMatchingMethodForCategory(arr, element); } answer = arr; } } return answer; } /** * @return all the normal static methods available on this class for the * given name */ private Object getStaticMethods(Class sender, String name) { final MetaMethodIndex.Entry entry = metaMethodIndex.getMethods(sender, name); if (entry == null) return FastArray.EMPTY_LIST; Object answer = entry.staticMethods; if (answer == null) return FastArray.EMPTY_LIST; return answer; } public boolean isModified() { return false; // MetaClassImpl not designed for modification, just return false } public void addNewInstanceMethod(Method method) { final CachedMethod cachedMethod = CachedMethod.find(method); NewInstanceMetaMethod newMethod = new NewInstanceMetaMethod(cachedMethod); final CachedClass declaringClass = newMethod.getDeclaringClass(); addNewInstanceMethodToIndex(newMethod, metaMethodIndex.getHeader(declaringClass.getTheClass())); } private void addNewInstanceMethodToIndex(MetaMethod newMethod, MetaMethodIndex.Header header) { if (!newGroovyMethodsSet.contains(newMethod)) { newGroovyMethodsSet.add(newMethod); addMetaMethodToIndex(newMethod, header); } } public void addNewStaticMethod(Method method) { final CachedMethod cachedMethod = CachedMethod.find(method); NewStaticMetaMethod newMethod = new NewStaticMetaMethod(cachedMethod); final CachedClass declaringClass = newMethod.getDeclaringClass(); addNewStaticMethodToIndex(newMethod, metaMethodIndex.getHeader(declaringClass.getTheClass())); } private void addNewStaticMethodToIndex(MetaMethod newMethod, MetaMethodIndex.Header header) { if (!newGroovyMethodsSet.contains(newMethod)) { newGroovyMethodsSet.add(newMethod); addMetaMethodToIndex(newMethod, header); } } public Object invokeMethod(Object object, String methodName, Object arguments) { if (arguments == null) { return invokeMethod(object, methodName, MetaClassHelper.EMPTY_ARRAY); } if (arguments instanceof Tuple) { Tuple tuple = (Tuple) arguments; return invokeMethod(object, methodName, tuple.toArray()); } if (arguments instanceof Object[]) { return invokeMethod(object, methodName, (Object[]) arguments); } else { return invokeMethod(object, methodName, new Object[]{arguments}); } } public Object invokeMissingMethod(Object instance, String methodName, Object[] arguments) { return invokeMissingMethod(instance, methodName, arguments, null, false); } public Object invokeMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) { Class theClass = instance instanceof Class ? (Class)instance : instance.getClass(); CachedClass superClass = theCachedClass; while(superClass != null && superClass != ReflectionCache.OBJECT_CLASS) { final MetaBeanProperty property = findPropertyInClassHierarchy(propertyName, superClass); if(property != null) { onSuperPropertyFoundInHierarchy(property); if(!isGetter) { property.setProperty(instance, optionalValue); return null; } else { return property.getProperty(instance); } } superClass = superClass.getCachedSuperClass(); } // got here to property not found, look for getProperty or setProperty overrides if(isGetter) { final Class[] getPropertyArgs = {String.class}; final MetaMethod method = findMethodInClassHierarchy(instance.getClass(), GET_PROPERTY_METHOD, getPropertyArgs, this); if(method != null && method instanceof ClosureMetaMethod) { onGetPropertyFoundInHierarchy(method); return method.invoke(instance,new Object[]{propertyName}); } } else { final Class[] setPropertyArgs = {String.class, Object.class}; final MetaMethod method = findMethodInClassHierarchy(instance.getClass(), SET_PROPERTY_METHOD, setPropertyArgs, this); if(method != null && method instanceof ClosureMetaMethod) { onSetPropertyFoundInHierarchy(method); return method.invoke(instance, new Object[]{propertyName, optionalValue}); } } try { if (!(instance instanceof Class)) { if (isGetter && propertyMissingGet != null) { return propertyMissingGet.invoke(instance, new Object[]{propertyName}); } else { if (propertyMissingSet != null) return propertyMissingSet.invoke(instance, new Object[]{propertyName, optionalValue}); } } } catch (InvokerInvocationException iie) { boolean shouldHandle = isGetter && propertyMissingGet != null; if (!shouldHandle) shouldHandle = !isGetter && propertyMissingSet != null; if (shouldHandle && iie.getCause() instanceof MissingPropertyException) { throw (MissingPropertyException) iie.getCause(); } throw iie; } if (instance instanceof Class && theClass != Class.class) { final MetaProperty metaProperty = InvokerHelper.getMetaClass(Class.class).hasProperty(instance, propertyName); if (metaProperty != null) if (isGetter) return metaProperty.getProperty(instance); else { metaProperty.setProperty(instance, optionalValue); return null; } } throw new MissingPropertyExceptionNoStack(propertyName, theClass); } private Object invokeMissingMethod(Object instance, String methodName, Object[] arguments, RuntimeException original, boolean isCallToSuper) { if (!isCallToSuper) { Class instanceKlazz = instance.getClass(); if (theClass != instanceKlazz && theClass.isAssignableFrom(instanceKlazz)) instanceKlazz = theClass; Class[] argClasses = MetaClassHelper.castArgumentsToClassArray(arguments); MetaMethod method = findMixinMethod(methodName, argClasses); if(method != null) { onMixinMethodFound(method); return method.invoke(instance, arguments); } method = findMethodInClassHierarchy(instanceKlazz, methodName, argClasses, this); if(method != null) { onSuperMethodFoundInHierarchy(method); return method.invoke(instance, arguments); } // still not method here, so see if there is an invokeMethod method up the hierarchy final Class[] invokeMethodArgs = {String.class, Object[].class}; method = findMethodInClassHierarchy(instanceKlazz, INVOKE_METHOD_METHOD, invokeMethodArgs, this ); if(method != null && method instanceof ClosureMetaMethod) { onInvokeMethodFoundInHierarchy(method); return method.invoke(instance, invokeMethodArgs); } } if (methodMissing != null) { try { return methodMissing.invoke(instance, new Object[]{methodName, arguments}); } catch (InvokerInvocationException iie) { if (methodMissing instanceof ClosureMetaMethod && iie.getCause() instanceof MissingMethodException) { MissingMethodException mme = (MissingMethodException) iie.getCause(); throw new MissingMethodExecutionFailed (mme.getMethod(), mme.getClass(), mme.getArguments(),mme.isStatic(),mme); } throw iie; } catch (MissingMethodException mme) { if (methodMissing instanceof ClosureMetaMethod) throw new MissingMethodExecutionFailed (mme.getMethod(), mme.getClass(), mme.getArguments(),mme.isStatic(),mme); else throw mme; } } else if (original != null) throw original; else throw new MissingMethodExceptionNoStack(methodName, theClass, arguments, false); } protected void onSuperPropertyFoundInHierarchy(MetaBeanProperty property) { } protected void onMixinMethodFound(MetaMethod method) { } protected void onSuperMethodFoundInHierarchy(MetaMethod method) { } protected void onInvokeMethodFoundInHierarchy(MetaMethod method) { } protected void onSetPropertyFoundInHierarchy(MetaMethod method) { } protected void onGetPropertyFoundInHierarchy(MetaMethod method) { } /** * Hook to deal with the case of MissingProperty for static properties. The method will look attempt to look up * "propertyMissing" handlers and invoke them otherwise thrown a MissingPropertyException * * @param instance The instance * @param propertyName The name of the property * @param optionalValue The value in the case of a setter * @param isGetter True if its a getter * @return The value in the case of a getter or a MissingPropertyException */ protected Object invokeStaticMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) { MetaClass mc = instance instanceof Class ? registry.getMetaClass((Class) instance) : this; if (isGetter) { MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, GETTER_MISSING_ARGS); if (propertyMissing != null) { return propertyMissing.invoke(instance, new Object[]{propertyName}); } } else { MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, SETTER_MISSING_ARGS); if (propertyMissing != null) { return propertyMissing.invoke(instance, new Object[]{propertyName, optionalValue}); } } if (instance instanceof Class) { throw new MissingPropertyException(propertyName, (Class) instance); } throw new MissingPropertyException(propertyName, theClass); } /** * Invokes the given method on the object. * TODO: should this be deprecated? If so, we have to propogate to many places. */ public Object invokeMethod(Object object, String methodName, Object[] originalArguments) { return invokeMethod(theClass, object, methodName, originalArguments, false, false); } /** * Invokes the given method on the object. */ public Object invokeMethod(Class sender, Object object, String methodName, Object[] originalArguments, boolean isCallToSuper, boolean fromInsideClass) { checkInitalised(); if (object == null) { throw new NullPointerException("Cannot invoke method: " + methodName + " on null object"); } final Object[] arguments = originalArguments == null ? EMPTY_ARGUMENTS : originalArguments; // final Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); // // unwrap(arguments); MetaMethod method = getMethodWithCaching(sender, methodName, arguments, isCallToSuper); MetaClassHelper.unwrap(arguments); if (method == null) method = tryListParamMetaMethod(sender, methodName, isCallToSuper, arguments); final boolean isClosure = object instanceof Closure; if (isClosure) { final Closure closure = (Closure) object; final Object owner = closure.getOwner(); if (CLOSURE_CALL_METHOD.equals(methodName) || CLOSURE_DO_CALL_METHOD.equals(methodName)) { final Class objectClass = object.getClass(); if (objectClass == MethodClosure.class) { final MethodClosure mc = (MethodClosure) object; methodName = mc.getMethod(); final Class ownerClass = owner instanceof Class ? (Class) owner : owner.getClass(); final MetaClass ownerMetaClass = registry.getMetaClass(ownerClass); return ownerMetaClass.invokeMethod(ownerClass, owner, methodName, arguments, false, false); } else if (objectClass == CurriedClosure.class) { final CurriedClosure cc = (CurriedClosure) object; // change the arguments for an uncurried call final Object[] curriedArguments = cc.getUncurriedArguments(arguments); final Class ownerClass = owner instanceof Class ? (Class) owner : owner.getClass(); final MetaClass ownerMetaClass = registry.getMetaClass(ownerClass); return ownerMetaClass.invokeMethod(owner, methodName, curriedArguments); } if (method==null) invokeMissingMethod(object,methodName,arguments); } final Object delegate = closure.getDelegate(); final boolean isClosureNotOwner = owner != closure; final int resolveStrategy = closure.getResolveStrategy(); final Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); switch (resolveStrategy) { case Closure.TO_SELF: method = closure.getMetaClass().pickMethod(methodName, argClasses); if (method != null) return method.invoke(closure, arguments); break; case Closure.DELEGATE_ONLY: if (method == null && delegate != closure && delegate != null) { MetaClass delegateMetaClass = lookupObjectMetaClass(delegate); method = delegateMetaClass.pickMethod(methodName, argClasses); if (method != null) return delegateMetaClass.invokeMethod(delegate, methodName, originalArguments); else if (delegate != closure && (delegate instanceof GroovyObject)) { return invokeMethodOnGroovyObject(methodName, originalArguments, delegate); } } break; case Closure.OWNER_ONLY: if (method == null && owner != closure) { MetaClass ownerMetaClass = lookupObjectMetaClass(owner); return ownerMetaClass.invokeMethod(owner, methodName, originalArguments); } break; case Closure.DELEGATE_FIRST: if (method == null && delegate != closure && delegate != null) { MetaClass delegateMetaClass = lookupObjectMetaClass(delegate); method = delegateMetaClass.pickMethod(methodName, argClasses); if (method != null) return delegateMetaClass.invokeMethod(delegate, methodName, originalArguments); } if (method == null && owner != closure) { MetaClass ownerMetaClass = lookupObjectMetaClass(owner); method = ownerMetaClass.pickMethod(methodName, argClasses); if (method != null) return ownerMetaClass.invokeMethod(owner, methodName, originalArguments); } if (method == null && resolveStrategy != Closure.TO_SELF) { // still no methods found, test if delegate or owner are GroovyObjects // and invoke the method on them if so. MissingMethodException last = null; if (delegate != closure && (delegate instanceof GroovyObject)) { try { return invokeMethodOnGroovyObject(methodName, originalArguments, delegate); } catch (MissingMethodException mme) { if (last == null) last = mme; } } if (isClosureNotOwner && (owner instanceof GroovyObject)) { try { return invokeMethodOnGroovyObject(methodName, originalArguments, owner); } catch (MissingMethodException mme) { last = mme; } } if (last != null) return invokeMissingMethod(object, methodName, originalArguments, last, isCallToSuper); } break; default: if (method == null && owner != closure) { MetaClass ownerMetaClass = lookupObjectMetaClass(owner); method = ownerMetaClass.pickMethod(methodName, argClasses); if (method != null) return ownerMetaClass.invokeMethod(owner, methodName, originalArguments); } if (method == null && delegate != closure && delegate != null) { MetaClass delegateMetaClass = lookupObjectMetaClass(delegate); method = delegateMetaClass.pickMethod(methodName, argClasses); if (method != null) return delegateMetaClass.invokeMethod(delegate, methodName, originalArguments); } if (method == null && resolveStrategy != Closure.TO_SELF) { // still no methods found, test if delegate or owner are GroovyObjects // and invoke the method on them if so. MissingMethodException last = null; if (isClosureNotOwner && (owner instanceof GroovyObject)) { try { return invokeMethodOnGroovyObject(methodName, originalArguments, owner); } catch (MissingMethodException mme) { if (methodName.equals(mme.getMethod())) { if (last == null) last = mme; } else { throw mme; } } catch (InvokerInvocationException iie) { if (iie.getCause() instanceof MissingMethodException) { MissingMethodException mme = (MissingMethodException) iie.getCause(); if (methodName.equals(mme.getMethod())) { if (last == null) last = mme; } else { throw iie; } } else throw iie; } } if (delegate != closure && (delegate instanceof GroovyObject)) { try { return invokeMethodOnGroovyObject(methodName, originalArguments, delegate); } catch (MissingMethodException mme) { last = mme; } catch (InvokerInvocationException iie) { if (iie.getCause() instanceof MissingMethodException) { last = (MissingMethodException) iie.getCause(); } else throw iie; } } if (last != null) return invokeMissingMethod(object, methodName, originalArguments, last, isCallToSuper); } } } if (method != null) { return method.doMethodInvoke(object, arguments); } else { return invokePropertyOrMissing(object, methodName, originalArguments, fromInsideClass, isCallToSuper); } } private MetaMethod tryListParamMetaMethod(Class sender, String methodName, boolean isCallToSuper, Object[] arguments) { MetaMethod method = null; if (arguments.length == 1 && arguments[0] instanceof List) { Object[] newArguments = ((List) arguments[0]).toArray(); method = getMethodWithCaching(sender, methodName, newArguments, isCallToSuper); if (method != null) { method = new TransformMetaMethod(method) { public Object invoke(Object object, Object[] arguments) { Object firstArgument = arguments[0]; List list = (List) firstArgument; arguments = list.toArray(); return super.invoke(object, arguments); } }; } } return method; } private Object invokePropertyOrMissing(Object object, String methodName, Object[] originalArguments, boolean fromInsideClass, boolean isCallToSuper) { // if no method was found, try to find a closure defined as a field of the class and run it Object value = null; final MetaProperty metaProperty = this.getMetaProperty(methodName, false); if (metaProperty != null) value = metaProperty.getProperty(object); else { if (object instanceof Map) value = ((Map)object).get(methodName); } if (value instanceof Closure) { // This test ensures that value != this If you ever change this ensure that value != this Closure closure = (Closure) value; MetaClass delegateMetaClass = closure.getMetaClass(); return delegateMetaClass.invokeMethod(closure.getClass(), closure, CLOSURE_DO_CALL_METHOD, originalArguments, false, fromInsideClass); } if (object instanceof Script) { Object bindingVar = ((Script) object).getBinding().getVariables().get(methodName); if (bindingVar != null) { MetaClass bindingVarMC = ((MetaClassRegistryImpl) registry).getMetaClass(bindingVar); return bindingVarMC.invokeMethod(bindingVar, CLOSURE_CALL_METHOD, originalArguments); } } return invokeMissingMethod(object, methodName, originalArguments, null, isCallToSuper); } private MetaClass lookupObjectMetaClass(Object object) { if (object instanceof GroovyObject) { GroovyObject go = (GroovyObject) object; return go.getMetaClass(); } Class ownerClass = object.getClass(); if (ownerClass == Class.class) ownerClass = (Class) object; MetaClass metaClass = registry.getMetaClass(ownerClass); return metaClass; } private Object invokeMethodOnGroovyObject(String methodName, Object[] originalArguments, Object owner) { GroovyObject go = (GroovyObject) owner; return go.invokeMethod(methodName, originalArguments); } public MetaMethod getMethodWithCaching(Class sender, String methodName, Object[] arguments, boolean isCallToSuper) { // let's try use the cache to find the method if (!isCallToSuper && GroovyCategorySupport.hasCategoryInCurrentThread()) { return getMethodWithoutCaching(sender, methodName, MetaClassHelper.convertToTypeArray(arguments), isCallToSuper); } else { final MetaMethodIndex.Entry e = metaMethodIndex.getMethods(sender, methodName); if (e == null) return null; return isCallToSuper ? getSuperMethodWithCaching(arguments, e) : getNormalMethodWithCaching(arguments, e); } } private static boolean sameClasses(Class[] params, Class[] arguments) { // we do here a null check because the params field might not have been set yet if (params == null) return false; if (params.length != arguments.length) return false; for (int i = params.length - 1; i >= 0; i--) { Object arg = arguments[i]; if (arg != null) { if (params[i] != arguments[i]) return false; } else return false; } return true; } // This method should be called by CallSite only private MetaMethod getMethodWithCachingInternal (Class sender, CallSite site, Class [] params) { if (GroovyCategorySupport.hasCategoryInCurrentThread()) return getMethodWithoutCaching(sender, site.getName (), params, false); final MetaMethodIndex.Entry e = metaMethodIndex.getMethods(sender, site.getName()); if (e == null) { return null; } MetaMethodIndex.CacheEntry cacheEntry; final Object methods = e.methods; if (methods == null) return null; cacheEntry = e.cachedMethod; if (cacheEntry != null && (sameClasses(cacheEntry.params, params))) { return cacheEntry.method; } cacheEntry = new MetaMethodIndex.CacheEntry (params, (MetaMethod) chooseMethod(e.name, methods, params)); e.cachedMethod = cacheEntry; return cacheEntry.method; } private MetaMethod getSuperMethodWithCaching(Object[] arguments, MetaMethodIndex.Entry e) { MetaMethodIndex.CacheEntry cacheEntry; if (e.methodsForSuper == null) return null; cacheEntry = e.cachedMethodForSuper; if (cacheEntry != null && MetaClassHelper.sameClasses(cacheEntry.params, arguments, e.methodsForSuper instanceof MetaMethod)) { MetaMethod method = cacheEntry.method; if (method!=null) return method; } final Class[] classes = MetaClassHelper.convertToTypeArray(arguments); MetaMethod method = (MetaMethod) chooseMethod(e.name, e.methodsForSuper, classes); cacheEntry = new MetaMethodIndex.CacheEntry (classes, method.isAbstract()?null:method); e.cachedMethodForSuper = cacheEntry; return cacheEntry.method; } private MetaMethod getNormalMethodWithCaching(Object[] arguments, MetaMethodIndex.Entry e) { MetaMethodIndex.CacheEntry cacheEntry; final Object methods = e.methods; if (methods == null) return null; cacheEntry = e.cachedMethod; if (cacheEntry != null && MetaClassHelper.sameClasses(cacheEntry.params, arguments, methods instanceof MetaMethod)) { MetaMethod method = cacheEntry.method; if (method!=null) return method; } final Class[] classes = MetaClassHelper.convertToTypeArray(arguments); cacheEntry = new MetaMethodIndex.CacheEntry (classes, (MetaMethod) chooseMethod(e.name, methods, classes)); e.cachedMethod = cacheEntry; return cacheEntry.method; } public Constructor retrieveConstructor(Class[] arguments) { CachedConstructor constructor = (CachedConstructor) chooseMethod("", constructors, arguments); if (constructor != null) { return constructor.cachedConstructor; } constructor = (CachedConstructor) chooseMethod("", constructors, arguments); if (constructor != null) { return constructor.cachedConstructor; } return null; } public MetaMethod retrieveStaticMethod(String methodName, Object[] arguments) { final MetaMethodIndex.Entry e = metaMethodIndex.getMethods(theClass, methodName); MetaMethodIndex.CacheEntry cacheEntry; if (e != null) { cacheEntry = e.cachedStaticMethod; if (cacheEntry != null && MetaClassHelper.sameClasses(cacheEntry.params, arguments, e.staticMethods instanceof MetaMethod)) { return cacheEntry.method; } final Class[] classes = MetaClassHelper.convertToTypeArray(arguments); cacheEntry = new MetaMethodIndex.CacheEntry (classes, pickStaticMethod(methodName, classes)); e.cachedStaticMethod = cacheEntry; return cacheEntry.method; } else return pickStaticMethod(methodName, MetaClassHelper.convertToTypeArray(arguments)); } public MetaMethod getMethodWithoutCaching(Class sender, String methodName, Class[] arguments, boolean isCallToSuper) { MetaMethod method = null; Object methods = getMethods(sender, methodName, isCallToSuper); if (methods != null) { method = (MetaMethod) chooseMethod(methodName, methods, arguments); } return method; } public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { checkInitalised(); final Class sender = object instanceof Class ? (Class) object : object.getClass(); if (sender != theClass) { MetaClass mc = registry.getMetaClass(sender); return mc.invokeStaticMethod(sender, methodName, arguments); } if (sender == Class.class) { return invokeMethod(object, methodName, arguments); } if (arguments == null) arguments = EMPTY_ARGUMENTS; // Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); MetaMethod method = retrieveStaticMethod(methodName, arguments); // let's try use the cache to find the method if (method != null) { MetaClassHelper.unwrap(arguments); return method.doMethodInvoke(object, arguments); } Object prop = null; try { prop = getProperty(theClass, theClass, methodName, false, false); } catch (MissingPropertyException mpe) { // ignore } if (prop instanceof Closure) { return invokeStaticClosureProperty(arguments, prop); } Object[] originalArguments = (Object[]) arguments.clone(); MetaClassHelper.unwrap(arguments); Class superClass = sender.getSuperclass(); Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); while (superClass != Object.class && superClass != null) { MetaClass mc = registry.getMetaClass(superClass); method = mc.getStaticMetaMethod(methodName, argClasses); if (method != null) return method.doMethodInvoke(object, arguments); try { prop = mc.getProperty(superClass, superClass, methodName, false, false); } catch (MissingPropertyException mpe) { // ignore } if (prop instanceof Closure) { return invokeStaticClosureProperty(originalArguments, prop); } superClass = superClass.getSuperclass(); } if (prop != null) { MetaClass propMC = registry.getMetaClass(prop.getClass()); return propMC.invokeMethod(prop, CLOSURE_CALL_METHOD, arguments); } return invokeStaticMissingMethod(sender, methodName, arguments); } private Object invokeStaticClosureProperty(Object[] originalArguments, Object prop) { Closure closure = (Closure) prop; MetaClass delegateMetaClass = closure.getMetaClass(); return delegateMetaClass.invokeMethod(closure.getClass(), closure, CLOSURE_DO_CALL_METHOD, originalArguments, false, false); } private Object invokeStaticMissingMethod(Class sender, String methodName, Object[] arguments) { MetaMethod metaMethod = getStaticMetaMethod(STATIC_METHOD_MISSING, METHOD_MISSING_ARGS); if (metaMethod != null) { return metaMethod.invoke(sender, new Object[]{methodName, arguments}); } throw new MissingMethodException(methodName, sender, arguments, true); } private MetaMethod pickStaticMethod(String methodName, Class[] arguments) { MetaMethod method = null; MethodSelectionException mse = null; Object methods = getStaticMethods(theClass, methodName); if (!(methods instanceof FastArray) || !((FastArray)methods).isEmpty()) { try { method = (MetaMethod) chooseMethod(methodName, methods, arguments); } catch(MethodSelectionException msex) { mse = msex; } } if (method == null && theClass != Class.class) { MetaClass classMetaClass = registry.getMetaClass(Class.class); method = classMetaClass.pickMethod(methodName, arguments); } if (method == null) { method = (MetaMethod) chooseMethod(methodName, methods, MetaClassHelper.convertToTypeArray(arguments)); } if (method == null && mse != null) { throw mse; } else { return method; } } /** * Warning, this method will be removed * * @deprecated use invokeConstructor instead */ public Object invokeConstructorAt(Class at, Object[] arguments) { return invokeConstructor(arguments); } public Object invokeConstructor(Object[] arguments) { return invokeConstructor(theClass, arguments); } public int selectConstructorAndTransformArguments(int numberOfConstructors, Object[] arguments) { //TODO: that is just a quick prototype, not the real thing! if (numberOfConstructors != constructors.size()) { throw new IncompatibleClassChangeError("the number of constructors during runtime and compile time for " + this.theClass.getName() + " do not match. Expected " + numberOfConstructors + " but got " + constructors.size()); } if (arguments == null) arguments = EMPTY_ARGUMENTS; Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); MetaClassHelper.unwrap(arguments); CachedConstructor constructor = (CachedConstructor) chooseMethod("", constructors, argClasses); if (constructor == null) { constructor = (CachedConstructor) chooseMethod("", constructors, argClasses); } if (constructor == null) { throw new GroovyRuntimeException( "Could not find matching constructor for: " + theClass.getName() + "(" + InvokerHelper.toTypeString(arguments) + ")"); } List l = new ArrayList(constructors.toList()); Comparator comp = new Comparator() { public int compare(Object arg0, Object arg1) { CachedConstructor c0 = (CachedConstructor) arg0; CachedConstructor c1 = (CachedConstructor) arg1; String descriptor0 = BytecodeHelper.getMethodDescriptor(Void.TYPE, c0.getNativeParameterTypes()); String descriptor1 = BytecodeHelper.getMethodDescriptor(Void.TYPE, c1.getNativeParameterTypes()); return descriptor0.compareTo(descriptor1); } }; Collections.sort(l, comp); int found = -1; for (int i = 0; i < l.size(); i++) { if (l.get(i) != constructor) continue; found = i; break; } // NOTE: must be changed to "1 |" if constructor was vargs return 0 | (found << 8); } /** * checks if the initialisation of the class id complete. * This method should be called as a form of assert, it is no * way to test if there is still initialisation work to be done. * Such logic must be implemented in a different way. * * @throws IllegalStateException if the initialisation is incomplete yet */ protected void checkInitalised() { if (!isInitialized()) throw new IllegalStateException( "initialize must be called for meta " + "class of " + theClass + "(" + this.getClass() + ") " + "to complete initialisation process " + "before any invocation or field/property " + "access can be done"); } private Object invokeConstructor(Class at, Object[] arguments) { checkInitalised(); if (arguments == null) arguments = EMPTY_ARGUMENTS; Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); MetaClassHelper.unwrap(arguments); CachedConstructor constructor = (CachedConstructor) chooseMethod("", constructors, argClasses); if (constructor != null) { return constructor.doConstructorInvoke(arguments); } if (arguments.length == 1) { Object firstArgument = arguments[0]; if (firstArgument instanceof Map) { constructor = (CachedConstructor) chooseMethod("", constructors, MetaClassHelper.EMPTY_TYPE_ARRAY); if (constructor != null) { Object bean = constructor.doConstructorInvoke(MetaClassHelper.EMPTY_ARRAY); setProperties(bean, ((Map) firstArgument)); return bean; } } } throw new GroovyRuntimeException( "Could not find matching constructor for: " + theClass.getName() + "(" + InvokerHelper.toTypeString(arguments) + ")"); } /** * Sets a number of bean properties from the given Map where the keys are * the String names of properties and the values are the values of the * properties to set */ public void setProperties(Object bean, Map map) { checkInitalised(); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); Object value = entry.getValue(); setProperty(bean, key, value); } } /** * @return the given property's value on the object */ public Object getProperty(Class sender, Object object, String name, boolean useSuper, boolean fromInsideClass) { //---------------------------------------------------------------------- // handling of static //---------------------------------------------------------------------- boolean isStatic = theClass != Class.class && object instanceof Class; if (isStatic && object != theClass) { MetaClass mc = registry.getMetaClass((Class) object); return mc.getProperty(sender, object, name, useSuper, false); } checkInitalised(); //---------------------------------------------------------------------- // turn getProperty on a Map to get on the Map itself //---------------------------------------------------------------------- if (!isStatic && this.isMap) { return ((Map) object).get(name); } MetaMethod method = null; Object[] arguments = EMPTY_ARGUMENTS; //---------------------------------------------------------------------- // getter //---------------------------------------------------------------------- MetaProperty mp = getMetaProperty(sender, name, useSuper, isStatic); if (mp != null) { if (mp instanceof MetaBeanProperty) { MetaBeanProperty mbp = (MetaBeanProperty) mp; method = mbp.getGetter(); mp = mbp.getField(); } } // check for a category method named like a getter if (!useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread()) { String getterName = GroovyCategorySupport.getPropertyCategoryGetterName(name); if (getterName != null) { MetaMethod categoryMethod = getCategoryMethodGetter(sender, getterName, false); if (categoryMethod != null) method = categoryMethod; } } //---------------------------------------------------------------------- // field //---------------------------------------------------------------------- if (method == null && mp != null) { try { return mp.getProperty(object); } catch (IllegalArgumentException e) { // can't access the field directly but there may be a getter mp = null; } } //---------------------------------------------------------------------- // generic get method //---------------------------------------------------------------------- // check for a generic get method provided through a category if (method == null && !useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread()) { method = getCategoryMethodGetter(sender, "get", true); if (method != null) arguments = new Object[]{name}; } // the generic method is valid, if available (!=null), if static or // if it is not static and we do no static access if (method == null && genericGetMethod != null && !(!genericGetMethod.isStatic() && isStatic)) { arguments = new Object[]{name}; method = genericGetMethod; } //---------------------------------------------------------------------- // special cases //---------------------------------------------------------------------- if (method == null) { /** todo these special cases should be special MetaClasses maybe */ if (theClass != Class.class && object instanceof Class) { MetaClass mc = registry.getMetaClass(Class.class); return mc.getProperty(Class.class, object, name, useSuper, false); } else if (object instanceof Collection) { return DefaultGroovyMethods.getAt((Collection) object, name); } else if (object instanceof Object[]) { return DefaultGroovyMethods.getAt(Arrays.asList((Object[]) object), name); } else { MetaMethod addListenerMethod = (MetaMethod) listeners.get(name); if (addListenerMethod != null) { //TODO: one day we could try return the previously registered Closure listener for easy removal return null; } } } else { //---------------------------------------------------------------------- // executing the getter method //---------------------------------------------------------------------- return method.doMethodInvoke(object, arguments); } //---------------------------------------------------------------------- // error due to missing method/field //---------------------------------------------------------------------- if (isStatic || object instanceof Class) return invokeStaticMissingProperty(object, name, null, true); else return invokeMissingProperty(object, name, null, true); } public MetaProperty getEffectiveGetMetaProperty(final Class sender, final Object object, String name, final boolean useSuper) { //---------------------------------------------------------------------- // handling of static //---------------------------------------------------------------------- boolean isStatic = theClass != Class.class && object instanceof Class; if (isStatic && object != theClass) { return new MetaProperty(name, Object.class) { final MetaClass mc = registry.getMetaClass((Class) object); public Object getProperty(Object object) { return mc.getProperty(sender, object, name, useSuper,false); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } checkInitalised(); //---------------------------------------------------------------------- // turn getProperty on a Map to get on the Map itself //---------------------------------------------------------------------- if (!isStatic && this.isMap) { return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return ((Map) object).get(name); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } MetaMethod method = null; //---------------------------------------------------------------------- // getter //---------------------------------------------------------------------- MetaProperty mp = getMetaProperty(sender, name, useSuper, isStatic); if (mp != null) { if (mp instanceof MetaBeanProperty) { MetaBeanProperty mbp = (MetaBeanProperty) mp; method = mbp.getGetter(); mp = mbp.getField(); } } // check for a category method named like a getter if (!useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread()) { String getterName = GroovyCategorySupport.getPropertyCategoryGetterName(name); if (getterName != null) { MetaMethod categoryMethod = getCategoryMethodGetter(sender, getterName, false); if (categoryMethod != null) method = categoryMethod; } } //---------------------------------------------------------------------- // field //---------------------------------------------------------------------- if (method != null) return new GetBeanMethodMetaProperty(name, method); if (mp != null) { return mp; // try { // return mp.getProperty(object); // } catch (IllegalArgumentException e) { // // can't access the field directly but there may be a getter // mp = null; // } } //---------------------------------------------------------------------- // generic get method //---------------------------------------------------------------------- // check for a generic get method provided through a category if (!useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread()) { method = getCategoryMethodGetter(sender, "get", true); if (method != null) return new GetMethodMetaProperty(name, method); } // the generic method is valid, if available (!=null), if static or // if it is not static and we do no static access if (genericGetMethod != null && !(!genericGetMethod.isStatic() && isStatic)) { method = genericGetMethod; if (method != null) return new GetMethodMetaProperty(name, method); } //---------------------------------------------------------------------- // special cases //---------------------------------------------------------------------- /** todo these special cases should be special MetaClasses maybe */ if (theClass != Class.class && object instanceof Class) { return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { MetaClass mc = registry.getMetaClass(Class.class); return mc.getProperty(Class.class, object, name, useSuper, false); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } else if (object instanceof Collection) { return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return DefaultGroovyMethods.getAt((Collection) object, name); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } else if (object instanceof Object[]) { return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return DefaultGroovyMethods.getAt(Arrays.asList((Object[]) object), name); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } else { MetaMethod addListenerMethod = (MetaMethod) listeners.get(name); if (addListenerMethod != null) { //TODO: one day we could try return the previously registered Closure listener for easy removal return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return null; } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } } //---------------------------------------------------------------------- // error due to missing method/field //---------------------------------------------------------------------- if (isStatic || object instanceof Class) return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return invokeStaticMissingProperty(object, name, null, true); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; else return new MetaProperty(name, Object.class) { public Object getProperty(Object object) { return invokeMissingProperty(object, name, null, true); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } }; } private MetaMethod getCategoryMethodGetter(Class sender, String name, boolean useLongVersion) { List possibleGenericMethods = GroovyCategorySupport.getCategoryMethods(name); if (possibleGenericMethods != null) { for (Iterator iter = possibleGenericMethods.iterator(); iter.hasNext();) { MetaMethod mmethod = (MetaMethod) iter.next(); if (!mmethod.getDeclaringClass().getTheClass().isAssignableFrom(sender)) continue; CachedClass[] paramTypes = mmethod.getParameterTypes(); if (useLongVersion) { if (paramTypes.length == 1 && paramTypes[0].getTheClass() == String.class) { return mmethod; } } else { if (paramTypes.length == 0) return mmethod; } } } return null; } private MetaMethod getCategoryMethodSetter(Class sender, String name, boolean useLongVersion) { List possibleGenericMethods = GroovyCategorySupport.getCategoryMethods(name); if (possibleGenericMethods != null) { for (Iterator iter = possibleGenericMethods.iterator(); iter.hasNext();) { MetaMethod mmethod = (MetaMethod) iter.next(); if (!mmethod.getDeclaringClass().getTheClass().isAssignableFrom(sender)) continue; CachedClass[] paramTypes = mmethod.getParameterTypes(); if (useLongVersion) { if (paramTypes.length == 2 && paramTypes[0].getTheClass() == String.class) { return mmethod; } } else { if (paramTypes.length == 1) return mmethod; } } } return null; } /** * Get all the properties defined for this type * * @return a list of MetaProperty objects */ public List getProperties() { checkInitalised(); SingleKeyHashMap propertyMap = classPropertyIndex.getNullable(theCachedClass); // simply return the values of the metaproperty map as a List List ret = new ArrayList(propertyMap.size()); for (ComplexKeyHashMap.EntryIterator iter = propertyMap.getEntrySetIterator(); iter.hasNext();) { MetaProperty element = (MetaProperty) ((SingleKeyHashMap.Entry) iter.next()).value; if (element instanceof CachedField) continue; // filter out DGM beans if (element instanceof MetaBeanProperty) { MetaBeanProperty mp = (MetaBeanProperty) element; boolean setter = true; boolean getter = true; if (mp.getGetter() == null || mp.getGetter() instanceof GeneratedMetaMethod || mp.getGetter() instanceof NewInstanceMetaMethod) { getter = false; } if (mp.getSetter() == null || mp.getSetter() instanceof GeneratedMetaMethod || mp.getSetter() instanceof NewInstanceMetaMethod) { setter = false; } if (!setter && !getter) continue; // TODO: I (ait) don't know why these strange tricks needed and comment following as it effects some Grails tests // if (!setter && mp.getSetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), mp.getGetter(), null); // } // if (!getter && mp.getGetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), null, mp.getSetter()); // } } ret.add(element); } return ret; } private MetaMethod findPropertyMethod(Object methodOrList, boolean isGetter, boolean booleanGetter) { if (methodOrList == null) return null; Object ret = null; if (methodOrList instanceof MetaMethod) { MetaMethod element = (MetaMethod)methodOrList; if (!isGetter && //(element.getReturnType() == Void.class || element.getReturnType() == Void.TYPE) && element.getParameterTypes().length == 1) { ret = addElementToList(ret, element); } if (isGetter && !(element.getReturnType() == Void.class || element.getReturnType() == Void.TYPE) && (!booleanGetter || element.getReturnType() == Boolean.class || element.getReturnType() == Boolean.TYPE) && element.getParameterTypes().length == 0) { ret = addElementToList(ret, element); } } else { FastArray methods = (FastArray) methodOrList; final int len = methods.size(); final Object[] data = methods.getArray(); for (int i = 0; i != len; ++i) { MetaMethod element = (MetaMethod) data[i]; if (!isGetter && //(element.getReturnType() == Void.class || element.getReturnType() == Void.TYPE) && element.getParameterTypes().length == 1) { ret = addElementToList(ret, element); } if (isGetter && !(element.getReturnType() == Void.class || element.getReturnType() == Void.TYPE) && element.getParameterTypes().length == 0) { ret = addElementToList(ret, element); } } } if (ret == null) return null; if (ret instanceof MetaMethod) return (MetaMethod) ret; // we found multiple matching methods // this is a problem, because we can use only one // if it is a getter, then use the most general return // type to decide which method to use. If it is a setter // we use the type of the first parameter MetaMethod method = null; int distance = -1; for (Iterator iter = ((List) ret).iterator(); iter.hasNext();) { MetaMethod element = (MetaMethod) iter.next(); Class c; if (isGetter) { c = element.getReturnType(); } else { c = element.getParameterTypes()[0].getTheClass(); } int localDistance = distanceToObject(c); //TODO: maybe implement the case localDistance==distance if (distance == -1 || distance > localDistance) { distance = localDistance; method = element; } } return method; } private Object addElementToList(Object ret, MetaMethod element) { if (ret == null) ret = element; else if (ret instanceof List) ((List) ret).add(element); else { List list = new LinkedList(); list.add(ret); list.add(element); ret = list; } return ret; } private static int distanceToObject(Class c) { int count; for (count = 0; c != null; count++) { c = c.getSuperclass(); } return count; } /** * This will build up the property map (Map of MetaProperty objects, keyed on * property name). */ @SuppressWarnings("unchecked") private void setupProperties(PropertyDescriptor[] propertyDescriptors) { if (theCachedClass.isInterface) { LinkedList superClasses = new LinkedList(); superClasses.add(ReflectionCache.OBJECT_CLASS); Set interfaces = theCachedClass.getInterfaces(); LinkedList superInterfaces = new LinkedList(interfaces); // sort interfaces so that we may ensure a deterministic behaviour in case of // ambiguous fields (class implementing two interfaces using the same field) if (superInterfaces.size()>1) { Collections.sort(superInterfaces, CACHED_CLASS_NAME_COMPARATOR); } SingleKeyHashMap iPropertyIndex = classPropertyIndex.getNotNull(theCachedClass); for (CachedClass iclass : superInterfaces) { SingleKeyHashMap sPropertyIndex = classPropertyIndex.getNotNull(iclass); copyNonPrivateFields(sPropertyIndex, iPropertyIndex); addFields(iclass, iPropertyIndex); } addFields(theCachedClass, iPropertyIndex); applyPropertyDescriptors(propertyDescriptors); applyStrayPropertyMethods(superClasses, classPropertyIndex, true); makeStaticPropertyIndex(); } else { LinkedList superClasses = getSuperClasses(); LinkedList interfaces = new LinkedList(theCachedClass.getInterfaces()); // sort interfaces so that we may ensure a deterministic behaviour in case of // ambiguous fields (class implementing two interfaces using the same field) if (interfaces.size()>1) { Collections.sort(interfaces, CACHED_CLASS_NAME_COMPARATOR); } // if this an Array, then add the special read-only "length" property if (theCachedClass.isArray) { SingleKeyHashMap map = new SingleKeyHashMap(); map.put("length", arrayLengthProperty); classPropertyIndex.put(theCachedClass, map); } inheritStaticInterfaceFields(superClasses, new LinkedHashSet(interfaces)); inheritFields(superClasses); applyPropertyDescriptors(propertyDescriptors); applyStrayPropertyMethods(superClasses, classPropertyIndex, true); applyStrayPropertyMethods(superClasses, classPropertyIndexForSuper, false); copyClassPropertyIndexForSuper(classPropertyIndexForSuper); makeStaticPropertyIndex(); } } private void makeStaticPropertyIndex() { SingleKeyHashMap propertyMap = classPropertyIndex.getNotNull(theCachedClass); for (ComplexKeyHashMap.EntryIterator iter = propertyMap.getEntrySetIterator(); iter.hasNext();) { SingleKeyHashMap.Entry entry = ((SingleKeyHashMap.Entry) iter.next()); MetaProperty mp = (MetaProperty) entry.getValue(); if (mp instanceof CachedField) { CachedField mfp = (CachedField) mp; if (!mfp.isStatic()) continue; } else if (mp instanceof MetaBeanProperty) { MetaProperty result = establishStaticMetaProperty(mp); if (result == null) continue; else { mp = result; } } else { continue; // ignore all other types } staticPropertyIndex.put(entry.getKey(), mp); } } private MetaProperty establishStaticMetaProperty(MetaProperty mp) { MetaBeanProperty mbp = (MetaBeanProperty) mp; MetaProperty result = null; final MetaMethod getterMethod = mbp.getGetter(); final MetaMethod setterMethod = mbp.getSetter(); final CachedField metaField = mbp.getField(); boolean getter = getterMethod == null || getterMethod.isStatic(); boolean setter = setterMethod == null || setterMethod.isStatic(); boolean field = metaField == null || metaField.isStatic(); if (!getter && !setter && !field) { return result; } else { final String propertyName = mbp.getName(); final Class propertyType = mbp.getType(); if (setter && getter) { if (field) { result = mbp; // nothing to do } else { result = new MetaBeanProperty(propertyName, propertyType, getterMethod, setterMethod); } } else if (getter && !setter) { if (getterMethod == null) { result = metaField; } else { MetaBeanProperty newmp = new MetaBeanProperty(propertyName, propertyType, getterMethod, null); if (field) newmp.setField(metaField); result = newmp; } } else if (setter && !getter) { if (setterMethod == null) { result = metaField; } else { MetaBeanProperty newmp = new MetaBeanProperty(propertyName, propertyType, null, setterMethod); if (field) newmp.setField(metaField); result = newmp; } } else result = metaField; } return result; } private void copyClassPropertyIndexForSuper(Index dest) { for (ComplexKeyHashMap.EntryIterator iter = classPropertyIndex.getEntrySetIterator(); iter.hasNext();) { SingleKeyHashMap.Entry entry = (SingleKeyHashMap.Entry) iter.next(); SingleKeyHashMap newVal = new SingleKeyHashMap(); dest.put((CachedClass) entry.getKey(), newVal); } } private void inheritStaticInterfaceFields(LinkedList superClasses, Set interfaces) { for (Iterator interfaceIter = interfaces.iterator(); interfaceIter.hasNext();) { CachedClass iclass = (CachedClass) interfaceIter.next(); SingleKeyHashMap iPropertyIndex = classPropertyIndex.getNotNull(iclass); addFields(iclass, iPropertyIndex); for (Iterator classIter = superClasses.iterator(); classIter.hasNext();) { CachedClass sclass = (CachedClass) classIter.next(); if (!iclass.getTheClass().isAssignableFrom(sclass.getTheClass())) continue; SingleKeyHashMap sPropertyIndex = classPropertyIndex.getNotNull(sclass); copyNonPrivateFields(iPropertyIndex, sPropertyIndex); } } } private void inheritFields(LinkedList superClasses) { SingleKeyHashMap last = null; for (CachedClass klass : superClasses) { SingleKeyHashMap propertyIndex = classPropertyIndex.getNotNull(klass); if (last != null) { copyNonPrivateFields(last, propertyIndex); } last = propertyIndex; addFields(klass, propertyIndex); } } private void addFields(final CachedClass klass, SingleKeyHashMap propertyIndex) { CachedField[] fields = klass.getFields(); for (CachedField field : fields) { propertyIndex.put(field.getName(), field); } } private void copyNonPrivateFields(SingleKeyHashMap from, SingleKeyHashMap to) { for (ComplexKeyHashMap.EntryIterator iter = from.getEntrySetIterator(); iter.hasNext();) { SingleKeyHashMap.Entry entry = (SingleKeyHashMap.Entry) iter.next(); CachedField mfp = (CachedField) entry.getValue(); if (!Modifier.isPublic(mfp.getModifiers()) && !Modifier.isProtected(mfp.getModifiers())) continue; to.put(entry.getKey(), mfp); } } private void applyStrayPropertyMethods(LinkedList superClasses, Index classPropertyIndex, boolean isThis) { // now look for any stray getters that may be used to define a property for (CachedClass klass : superClasses) { MetaMethodIndex.Header header = metaMethodIndex.getHeader(klass.getTheClass()); SingleKeyHashMap propertyIndex = classPropertyIndex.getNotNull(klass); for (MetaMethodIndex.Entry e = header.head; e != null; e = e.nextClassEntry) { String methodName = e.name; // name too short? if (methodName.length() < 3 || (!methodName.startsWith("is") && methodName.length() < 4)) continue; // possible getter/setter? boolean isGetter = methodName.startsWith("get") || methodName.startsWith("is"); boolean isBooleanGetter = methodName.startsWith("is"); boolean isSetter = methodName.startsWith("set"); if (!isGetter && !isSetter) continue; MetaMethod propertyMethod = findPropertyMethod(isThis ? e.methods : e.methodsForSuper, isGetter, isBooleanGetter); if (propertyMethod == null) continue; String propName = getPropName(methodName); createMetaBeanProperty(propertyIndex, propName, isGetter, propertyMethod); } } } private static final HashMap propNames = new HashMap(1024); private String getPropName(String methodName) { String name = propNames.get(methodName); if (name != null) return name; synchronized (propNames) { // assume "is" or "[gs]et" String stripped = methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3); String propName = java.beans.Introspector.decapitalize(stripped); propNames.put(methodName, propName); return propName; } } private void createMetaBeanProperty(SingleKeyHashMap propertyIndex, String propName, boolean isGetter, MetaMethod propertyMethod) { // is this property already accounted for? MetaProperty mp = (MetaProperty) propertyIndex.get(propName); if (mp == null) { if (isGetter) { mp = new MetaBeanProperty(propName, propertyMethod.getReturnType(), propertyMethod, null); } else { //isSetter mp = new MetaBeanProperty(propName, propertyMethod.getParameterTypes()[0].getTheClass(), null, propertyMethod); } } else { MetaBeanProperty mbp; CachedField mfp; if (mp instanceof MetaBeanProperty) { mbp = (MetaBeanProperty) mp; mfp = mbp.getField(); } else if (mp instanceof CachedField) { mfp = (CachedField) mp; mbp = new MetaBeanProperty(propName, mfp.getType(), null, null); } else { throw new GroovyBugError("unknown MetaProperty class used. Class is " + mp.getClass()); } // we may have already found one for this name if (isGetter && mbp.getGetter() == null) { mbp.setGetter(propertyMethod); } else if (!isGetter && mbp.getSetter() == null) { mbp.setSetter(propertyMethod); } mbp.setField(mfp); mp = mbp; } propertyIndex.put(propName, mp); } protected void applyPropertyDescriptors(PropertyDescriptor[] propertyDescriptors) { // now iterate over the map of property descriptors and generate // MetaBeanProperty objects for (PropertyDescriptor pd : propertyDescriptors) { // skip if the property type is unknown (this seems to be the case if the // property descriptor is based on a setX() method that has two parameters, // which is not a valid property) if (pd.getPropertyType() == null) continue; // get the getter method Method method = pd.getReadMethod(); MetaMethod getter; if (method != null) { CachedMethod cachedGetter = CachedMethod.find(method); getter = cachedGetter == null ? null : findMethod(cachedGetter); } else { getter = null; } // get the setter method MetaMethod setter; method = pd.getWriteMethod(); if (method != null) { CachedMethod cachedSetter = CachedMethod.find(method); setter = cachedSetter == null ? null : findMethod(cachedSetter); } else { setter = null; } // now create the MetaProperty object MetaBeanProperty mp = new MetaBeanProperty(pd.getName(), pd.getPropertyType(), getter, setter); addMetaBeanProperty(mp); } } /** * Adds a new MetaBeanProperty to this MetaClass * * @param mp The MetaBeanProperty */ public void addMetaBeanProperty(MetaBeanProperty mp) { MetaProperty staticProperty = establishStaticMetaProperty(mp); if (staticProperty != null) { staticPropertyIndex.put(mp.getName(), mp); } else { SingleKeyHashMap propertyMap = classPropertyIndex.getNotNull(theCachedClass); //keep field CachedField field; MetaProperty old = (MetaProperty) propertyMap.get(mp.getName()); if (old != null) { if (old instanceof MetaBeanProperty) { field = ((MetaBeanProperty) old).getField(); } else { field = (CachedField) old; } mp.setField(field); } // put it in the list // this will overwrite a possible field property propertyMap.put(mp.getName(), mp); } } /** * Sets the property value on an object */ public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) { checkInitalised(); //---------------------------------------------------------------------- // handling of static //---------------------------------------------------------------------- boolean isStatic = theClass != Class.class && object instanceof Class; if (isStatic && object != theClass) { MetaClass mc = registry.getMetaClass((Class) object); mc.getProperty(sender, object, name, useSuper, fromInsideClass); return; } //---------------------------------------------------------------------- // Unwrap wrapped values fo now - the new MOP will handle them properly //---------------------------------------------------------------------- if (newValue instanceof Wrapper) newValue = ((Wrapper) newValue).unwrap(); MetaMethod method = null; Object[] arguments = null; //---------------------------------------------------------------------- // setter //---------------------------------------------------------------------- MetaProperty mp = getMetaProperty(sender, name, useSuper, isStatic); MetaProperty field = null; if (mp != null) { if (mp instanceof MetaBeanProperty) { MetaBeanProperty mbp = (MetaBeanProperty) mp; method = mbp.getSetter(); MetaProperty f = mbp.getField(); if (method != null || (f != null && !Modifier.isFinal(f.getModifiers()))) { arguments = new Object[]{newValue}; field = f; } } else { field = mp; } } // check for a category method named like a setter if (!useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread() && name.length() > 0) { String getterName = GroovyCategorySupport.getPropertyCategorySetterName(name); if (getterName != null) { MetaMethod categoryMethod = getCategoryMethodSetter(sender, getterName, false); if (categoryMethod != null) { method = categoryMethod; arguments = new Object[]{newValue}; } } } //---------------------------------------------------------------------- // listener method //---------------------------------------------------------------------- boolean ambiguousListener = false; if (method == null) { method = (MetaMethod) listeners.get(name); ambiguousListener = method == AMBIGUOUS_LISTENER_METHOD; if (method != null && !ambiguousListener && newValue instanceof Closure) { // let's create a dynamic proxy Object proxy = Proxy.newProxyInstance( theClass.getClassLoader(), new Class[]{method.getParameterTypes()[0].getTheClass()}, new ConvertedClosure((Closure) newValue, name)); arguments = new Object[]{proxy}; newValue = proxy; } else { method = null; } } //---------------------------------------------------------------------- // field //---------------------------------------------------------------------- if (method == null && field != null) { if (Modifier.isFinal(field.getModifiers())) { throw new ReadOnlyPropertyException(name, theClass); } if(!(this.isMap && isPrivateOrPkgPrivate(field.getModifiers()))) { field.setProperty(object, newValue); return; } } //---------------------------------------------------------------------- // generic set method //---------------------------------------------------------------------- // check for a generic get method provided through a category if (method == null && !useSuper && !isStatic && GroovyCategorySupport.hasCategoryInCurrentThread()) { method = getCategoryMethodSetter(sender, "set", true); if (method != null) arguments = new Object[]{name, newValue}; } // the generic method is valid, if available (!=null), if static or // if it is not static and we do no static access if (method == null && genericSetMethod != null && !(!genericSetMethod.isStatic() && isStatic)) { arguments = new Object[]{name, newValue}; method = genericSetMethod; } //---------------------------------------------------------------------- // executing the getter method //---------------------------------------------------------------------- if (method != null) { if (arguments.length == 1) { newValue = DefaultTypeTransformation.castToType( newValue, method.getParameterTypes()[0].getTheClass()); arguments[0] = newValue; } else { newValue = DefaultTypeTransformation.castToType( newValue, method.getParameterTypes()[1].getTheClass()); arguments[1] = newValue; } method.doMethodInvoke(object, arguments); return; } //---------------------------------------------------------------------- // turn setProperty on a Map to put on the Map itself //---------------------------------------------------------------------- if (!isStatic && this.isMap) { ((Map) object).put(name, newValue); return; } //---------------------------------------------------------------------- // error due to missing method/field //---------------------------------------------------------------------- if (ambiguousListener) { throw new GroovyRuntimeException("There are multiple listeners for the property " + name + ". Please do not use the bean short form to access this listener."); } if (mp != null) { throw new ReadOnlyPropertyException(name, theClass); } invokeMissingProperty(object, name, newValue, false); } private boolean isPrivateOrPkgPrivate(int mod) { return !Modifier.isProtected(mod) && !Modifier.isPublic(mod); } private MetaProperty getMetaProperty(Class _clazz, String name, boolean useSuper, boolean useStatic) { if (_clazz == theClass) return getMetaProperty(name, useStatic); CachedClass clazz = ReflectionCache.getCachedClass(_clazz); while (true) { SingleKeyHashMap propertyMap; if (useStatic) { propertyMap = staticPropertyIndex; } else if (useSuper) { propertyMap = classPropertyIndexForSuper.getNullable(clazz); } else { propertyMap = classPropertyIndex.getNullable(clazz); } if (propertyMap == null) { if (clazz != theCachedClass) { clazz = theCachedClass; continue; } else { return null; } } return (MetaProperty) propertyMap.get(name); } } private MetaProperty getMetaProperty(String name, boolean useStatic) { CachedClass clazz = theCachedClass; SingleKeyHashMap propertyMap; if (useStatic) { propertyMap = staticPropertyIndex; } else { propertyMap = classPropertyIndex.getNullable(clazz); } if (propertyMap == null) { return null; } return (MetaProperty) propertyMap.get(name); } public Object getAttribute(Class sender, Object receiver, String messageName, boolean useSuper) { return getAttribute(receiver, messageName); } /** * Looks up the given attribute (field) on the given object */ public Object getAttribute(Class sender, Object object, String attribute, boolean useSuper, boolean fromInsideClass) { checkInitalised(); boolean isStatic = theClass != Class.class && object instanceof Class; if (isStatic && object != theClass) { MetaClass mc = registry.getMetaClass((Class) object); return mc.getAttribute(sender, object, attribute, useSuper); } MetaProperty mp = getMetaProperty(sender, attribute, useSuper, isStatic); if (mp != null) { if (mp instanceof MetaBeanProperty) { MetaBeanProperty mbp = (MetaBeanProperty) mp; mp = mbp.getField(); } try { // delegate the get operation to the metaproperty if (mp != null) return mp.getProperty(object); } catch (Exception e) { throw new GroovyRuntimeException("Cannot read field: " + attribute, e); } } throw new MissingFieldException(attribute, theClass); } /** * Sets the given attribute (field) on the given object */ public void setAttribute(Class sender, Object object, String attribute, Object newValue, boolean useSuper, boolean fromInsideClass) { checkInitalised(); boolean isStatic = theClass != Class.class && object instanceof Class; if (isStatic && object != theClass) { MetaClass mc = registry.getMetaClass((Class) object); mc.setAttribute(sender, object, attribute, newValue, useSuper, fromInsideClass); return; } MetaProperty mp = getMetaProperty(sender, attribute, useSuper, isStatic); if (mp != null) { if (mp instanceof MetaBeanProperty) { MetaBeanProperty mbp = (MetaBeanProperty) mp; mp = mbp.getField(); } if (mp != null) { mp.setProperty(object, newValue); return; } } throw new MissingFieldException(attribute, theClass); } public ClassNode getClassNode() { if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) { // let's try load it from the classpath String groovyFile = theClass.getName(); int idx = groovyFile.indexOf('$'); if (idx > 0) { groovyFile = groovyFile.substring(0, idx); } groovyFile = groovyFile.replace('.', '/') + ".groovy"; //System.out.println("Attempting to load: " + groovyFile); URL url = theClass.getClassLoader().getResource(groovyFile); if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(groovyFile); } if (url != null) { try { /** * todo there is no CompileUnit in scope so class name * checking won't work but that mostly affects the bytecode * generation rather than viewing the AST */ CompilationUnit.ClassgenCallback search = new CompilationUnit.ClassgenCallback() { public void call(ClassVisitor writer, ClassNode node) { if (node.getName().equals(theClass.getName())) { MetaClassImpl.this.classNode = node; } } }; final ClassLoader parent = theClass.getClassLoader(); CompilationUnit unit = new CompilationUnit(); unit.setClassgenCallback(search); unit.addSource(url); unit.compile(Phases.CLASS_GENERATION); } catch (Exception e) { throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e); } } } return classNode; } public String toString() { return super.toString() + "[" + theClass + "]"; } // Implementation methods //------------------------------------------------------------------------- /** * adds a MetaMethod to this class. WARNING: this method will not * do the neccessary steps for multimethod logic and using this * method doesn't mean, that a method added here is replacing another * method from a parent class completely. These steps are usually done * by initialize, which means if you need these steps, you have to add * the method before running initialize the first time. * * @param method the MetaMethod * @see #initialize() */ public void addMetaMethod(MetaMethod method) { if (isInitialized()) { throw new RuntimeException("Already initialized, cannot add new method: " + method); } final CachedClass declaringClass = method.getDeclaringClass(); addMetaMethodToIndex(method, metaMethodIndex.getHeader(declaringClass.getTheClass())); } protected void addMetaMethodToIndex(MetaMethod method, MetaMethodIndex.Header header) { checkIfStdMethod(method); String name = method.getName(); MetaMethodIndex.Entry e = metaMethodIndex.getOrPutMethods(name, header); if (method.isStatic()) { e.staticMethods = metaMethodIndex.addMethodToList(e.staticMethods, method); } e.methods = metaMethodIndex.addMethodToList(e.methods, method); } /** * Checks if the metaMethod is a method from the GroovyObject interface such as setProperty, getProperty and invokeMethod * * @param metaMethod The metaMethod instance * @see GroovyObject */ protected final void checkIfGroovyObjectMethod(MetaMethod metaMethod) { if (metaMethod instanceof ClosureMetaMethod || metaMethod instanceof MixinInstanceMetaMethod) { if(isGetPropertyMethod(metaMethod)) { getPropertyMethod = metaMethod; } else if(isInvokeMethod(metaMethod)) { invokeMethodMethod = metaMethod; } else if(isSetPropertyMethod(metaMethod)) { setPropertyMethod = metaMethod; } } } private boolean isSetPropertyMethod(MetaMethod metaMethod) { return SET_PROPERTY_METHOD.equals(metaMethod.getName()) && metaMethod.getParameterTypes().length == 2; } private boolean isGetPropertyMethod(MetaMethod metaMethod) { return GET_PROPERTY_METHOD.equals(metaMethod.getName()); } private boolean isInvokeMethod(MetaMethod metaMethod) { return INVOKE_METHOD_METHOD.equals(metaMethod.getName()) && metaMethod.getParameterTypes().length == 2; } private void checkIfStdMethod(MetaMethod method) { checkIfGroovyObjectMethod(method); if (isGenericGetMethod(method) && genericGetMethod == null) { genericGetMethod = method; } else if (MetaClassHelper.isGenericSetMethod(method) && genericSetMethod == null) { genericSetMethod = method; } if (method.getName().equals(PROPERTY_MISSING)) { CachedClass[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { propertyMissingGet = method; } } if (propertyMissingSet == null && method.getName().equals(PROPERTY_MISSING)) { CachedClass[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 2) { propertyMissingSet = method; } } if (method.getName().equals(METHOD_MISSING)) { CachedClass[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 2 && parameterTypes[0].getTheClass() == String.class && parameterTypes[1].getTheClass() == Object.class) { methodMissing = method; } } if (theCachedClass.isNumber) { NumberMathModificationInfo.instance.checkIfStdMethod (method); } } protected boolean isInitialized() { return initialized; } /** * return false: add method * null: ignore method * true: replace */ private Boolean getMatchKindForCategory(MetaMethod aMethod, MetaMethod categoryMethod) { CachedClass[] params1 = aMethod.getParameterTypes(); CachedClass[] params2 = categoryMethod.getParameterTypes(); if (params1.length != params2.length) return Boolean.FALSE; for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return Boolean.FALSE; } Class aMethodClass = aMethod.getDeclaringClass().getTheClass(); Class categoryMethodClass = categoryMethod.getDeclaringClass().getTheClass(); if (aMethodClass==categoryMethodClass) return Boolean.TRUE; boolean match = aMethodClass.isAssignableFrom(categoryMethodClass); if (match) return Boolean.TRUE; return null; } private void filterMatchingMethodForCategory(FastArray list, MetaMethod method) { int len = list.size(); if (len==0) { list.add(method); return; } Object data[] = list.getArray(); for (int j = 0; j != len; ++j) { MetaMethod aMethod = (MetaMethod) data[j]; Boolean match = getMatchKindForCategory(aMethod, method); // true == replace if (match==Boolean.TRUE) { list.set(j, method); return; // null == ignore (we have a better method already) } else if (match==null) { return; } } // the casese true and null for a match are through, the // remaining case is false and that means adding the method // to our list list.add(method); } private int findMatchingMethod(CachedMethod[] data, int from, int to, MetaMethod method) { for (int j = from; j <= to; ++j) { CachedMethod aMethod = data[j]; CachedClass[] params1 = aMethod.getParameterTypes(); CachedClass[] params2 = method.getParameterTypes(); if (params1.length == params2.length) { boolean matches = true; for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) { matches = false; break; } } if (matches) { return j; } } } return -1; } /** * @return the matching method which should be found */ private MetaMethod findMethod(CachedMethod aMethod) { Object methods = getMethods(theClass, aMethod.getName(), false); if (methods instanceof FastArray) { FastArray m = (FastArray) methods; final int len = m.size; final Object data[] = m.getArray(); for (int i = 0; i != len; ++i) { MetaMethod method = (MetaMethod) data[i]; if (method.isMethod(aMethod)) { return method; } } } else { MetaMethod method = (MetaMethod) methods; if (method.getName().equals(aMethod.getName()) // TODO: should be better check for case when only diff in modifiers can be SYNTHETIC flag // && method.getModifiers() == aMethod.getModifiers() && method.getReturnType().equals(aMethod.getReturnType()) && MetaMethod.equal(method.getParameterTypes(), aMethod.getParameterTypes())) { return method; } } //log.warning("Creating reflection based dispatcher for: " + aMethod); synchronized (aMethod.cachedClass) { return aMethod; } } /** * Chooses the correct method to use from a list of methods which match by * name. * * @param methodOrList the possible methods to choose from * @param arguments */ protected Object chooseMethod(String methodName, Object methodOrList, Class[] arguments) { Object method = chooseMethodInternal(methodName, methodOrList, arguments); if (method instanceof GeneratedMetaMethod.Proxy) return ((GeneratedMetaMethod.Proxy)method).proxy (); return method; } private Object chooseMethodInternal(String methodName, Object methodOrList, Class[] arguments) { if (methodOrList instanceof MetaMethod) { if (((ParameterTypes) methodOrList).isValidMethod(arguments)) { return methodOrList; } return null; } FastArray methods = (FastArray) methodOrList; if (methods==null) return null; int methodCount = methods.size(); if (methodCount <= 0) { return null; } else if (methodCount == 1) { Object method = methods.get(0); if (((ParameterTypes) method).isValidMethod(arguments)) { return method; } return null; } Object answer; if (arguments == null || arguments.length == 0) { answer = MetaClassHelper.chooseEmptyMethodParams(methods); } else if (arguments.length == 1 && arguments[0] == null) { answer = MetaClassHelper.chooseMostGeneralMethodWith1NullParam(methods); } else { Object matchingMethods = null; final int len = methods.size; Object data[] = methods.getArray(); for (int i = 0; i != len; ++i) { Object method = data[i]; // making this false helps find matches if (((ParameterTypes) method).isValidMethod(arguments)) { if (matchingMethods == null) matchingMethods = method; else if (matchingMethods instanceof ArrayList) ((ArrayList)matchingMethods).add(method); else { ArrayList arr = new ArrayList(4); arr.add(matchingMethods); arr.add(method); matchingMethods = arr; } } } if (matchingMethods == null) { return null; } else if (!(matchingMethods instanceof ArrayList)) { return matchingMethods; } return chooseMostSpecificParams(methodName, (List) matchingMethods, arguments); } if (answer != null) { return answer; } throw new MethodSelectionException(methodName, methods, arguments); } private Object chooseMostSpecificParams(String name, List matchingMethods, Class[] arguments) { long matchesDistance = -1; LinkedList matches = new LinkedList(); for (Iterator iter = matchingMethods.iterator(); iter.hasNext();) { Object method = iter.next(); ParameterTypes paramTypes = (ParameterTypes) method; long dist = MetaClassHelper.calculateParameterDistance(arguments, paramTypes); if (dist == 0) return method; if (matches.size() == 0) { matches.add(method); matchesDistance = dist; } else if (dist < matchesDistance) { matchesDistance = dist; matches.clear(); matches.add(method); } else if (dist == matchesDistance) { matches.add(method); } } if (matches.size() == 1) { return matches.getFirst(); } if (matches.size() == 0) { return null; } //more than one matching method found --> ambiguous! String msg = "Ambiguous method overloading for method "; msg += theClass.getName() + "#" + name; msg += ".\nCannot resolve which method to invoke for "; msg += InvokerHelper.toString(arguments); msg += " due to overlapping prototypes between:"; for (Iterator iter = matches.iterator(); iter.hasNext();) { Class[] types = ((ParameterTypes) iter.next()).getNativeParameterTypes(); msg += "\n\t" + InvokerHelper.toString(types); } throw new GroovyRuntimeException(msg); } private boolean isGenericGetMethod(MetaMethod method) { if (method.getName().equals("get")) { CachedClass[] parameterTypes = method.getParameterTypes(); return parameterTypes.length == 1 && parameterTypes[0].getTheClass() == String.class; } return false; } public synchronized void initialize() { if (!isInitialized()) { fillMethodIndex(); addProperties(); initialized = true; } } private void addProperties() { BeanInfo info; final Class stopClass; // introspect try { if (isBeanDerivative(theClass)) { info = (BeanInfo) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IntrospectionException { return Introspector.getBeanInfo(theClass, Introspector.IGNORE_ALL_BEANINFO); } }); } else { info = (BeanInfo) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IntrospectionException { return Introspector.getBeanInfo(theClass); } }); } } catch (PrivilegedActionException pae) { throw new GroovyRuntimeException("exception during bean introspection", pae.getException()); } PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); // build up the metaproperties based on the public fields, property descriptors, // and the getters and setters setupProperties(descriptors); EventSetDescriptor[] eventDescriptors = info.getEventSetDescriptors(); for (EventSetDescriptor descriptor : eventDescriptors) { Method[] listenerMethods = descriptor.getListenerMethods(); for (Method listenerMethod : listenerMethods) { final MetaMethod metaMethod = CachedMethod.find(descriptor.getAddListenerMethod()); // GROOVY-5202 // there might be a non public listener of some kind // we skip that here if (metaMethod==null) continue; addToAllMethodsIfPublic(metaMethod); String name = listenerMethod.getName(); if (listeners.containsKey(name)) { listeners.put(name, AMBIGUOUS_LISTENER_METHOD); } else { listeners.put(name, metaMethod); } } } } private boolean isBeanDerivative(Class theClass) { Class next = theClass; while (next != null) { if (Arrays.asList(next.getInterfaces()).contains(BeanInfo.class)) return true; next = next.getSuperclass(); } return false; } private void addToAllMethodsIfPublic(MetaMethod metaMethod) { if (Modifier.isPublic(metaMethod.getModifiers())) allMethods.add(metaMethod); } public List getMethods() { return allMethods; } public List getMetaMethods() { return new ArrayList(newGroovyMethodsSet); } protected void dropStaticMethodCache(String name) { metaMethodIndex.clearCaches(name); } protected void dropMethodCache(String name) { metaMethodIndex.clearCaches(name); } public CallSite createPojoCallSite(CallSite site, Object receiver, Object[] args) { if (!(this instanceof AdaptingMetaClass)) { Class [] params = MetaClassHelper.convertToTypeArray(args); MetaMethod metaMethod = getMethodWithCachingInternal(getTheClass(), site, params); if (metaMethod != null) return PojoMetaMethodSite.createPojoMetaMethodSite(site, this, metaMethod, params, receiver, args); } return new PojoMetaClassSite(site, this); } public CallSite createStaticSite(CallSite site, Object[] args) { if (!(this instanceof AdaptingMetaClass)) { Class [] params = MetaClassHelper.convertToTypeArray(args); MetaMethod metaMethod = retrieveStaticMethod(site.getName(), args); if (metaMethod != null) return StaticMetaMethodSite.createStaticMetaMethodSite(site, this, metaMethod, params, args); } return new StaticMetaClassSite(site, this); } public CallSite createPogoCallSite(CallSite site, Object[] args) { if (!GroovyCategorySupport.hasCategoryInCurrentThread() && !(this instanceof AdaptingMetaClass)) { Class [] params = MetaClassHelper.convertToTypeArray(args); MetaMethod metaMethod = getMethodWithCachingInternal(theClass, site, params); if (metaMethod != null) return PogoMetaMethodSite.createPogoMetaMethodSite(site, this, metaMethod, params, args); } return new PogoMetaClassSite(site, this); } public CallSite createPogoCallCurrentSite(CallSite site, Class sender, Object[] args) { if (!GroovyCategorySupport.hasCategoryInCurrentThread() && !(this instanceof AdaptingMetaClass)) { Class [] params = MetaClassHelper.convertToTypeArray(args); MetaMethod metaMethod = getMethodWithCachingInternal(sender, site, params); if (metaMethod != null) return PogoMetaMethodSite.createPogoMetaMethodSite(site, this, metaMethod, params, args); } return new PogoMetaClassSite(site, this); } public CallSite createConstructorSite(CallSite site, Object[] args) { if (!(this instanceof AdaptingMetaClass)) { Class[] params = MetaClassHelper.convertToTypeArray(args); CachedConstructor constructor = (CachedConstructor) chooseMethod("", constructors, params); if (constructor != null) { return ConstructorSite.createConstructorSite(site, this,constructor,params, args); } else { if (args.length == 1 && args[0] instanceof Map) { constructor = (CachedConstructor) chooseMethod("", constructors, MetaClassHelper.EMPTY_TYPE_ARRAY); if (constructor != null) { return new ConstructorSite.NoParamSite(site, this,constructor,params); } } else if (args.length == 2 && theClass.getEnclosingClass() != null && args[1] instanceof Map) { Class enclosingClass = theClass.getEnclosingClass(); String enclosingInstanceParamType = args[0] != null ? args[0].getClass().getName() : ""; if(enclosingClass.getName().equals(enclosingInstanceParamType)) { constructor = (CachedConstructor) chooseMethod("", constructors, new Class[]{enclosingClass}); if (constructor != null) { return new ConstructorSite.NoParamSiteInnerClass(site, this,constructor,params); } } } } } return new MetaClassConstructorSite(site, this); } public ClassInfo getClassInfo() { return theCachedClass.classInfo; } public int getVersion() { return theCachedClass.classInfo.getVersion(); } public void incVersion() { theCachedClass.classInfo.incVersion(); } public MetaMethod[] getAdditionalMetaMethods() { return additionalMetaMethods; } protected MetaBeanProperty findPropertyInClassHierarchy(String propertyName, CachedClass theClass) { MetaBeanProperty property= null; if (theClass == null) return null; final CachedClass superClass = theClass.getCachedSuperClass(); if (superClass == null) return null; MetaClass metaClass = this.registry.getMetaClass(superClass.getTheClass()); if(metaClass instanceof MutableMetaClass) { property = getMetaPropertyFromMutableMetaClass(propertyName,metaClass); if(property == null) { if(superClass != ReflectionCache.OBJECT_CLASS) { property = findPropertyInClassHierarchy(propertyName, superClass); } if(property == null) { final Class[] interfaces = theClass.getTheClass().getInterfaces(); property = searchInterfacesForMetaProperty(propertyName, interfaces); } } } return property; } private MetaBeanProperty searchInterfacesForMetaProperty(String propertyName, Class[] interfaces) { MetaBeanProperty property = null; for (Class anInterface : interfaces) { MetaClass metaClass = registry.getMetaClass(anInterface); if (metaClass instanceof MutableMetaClass) { property = getMetaPropertyFromMutableMetaClass(propertyName, metaClass); if (property != null) break; } Class[] superInterfaces = anInterface.getInterfaces(); if (superInterfaces.length > 0) { property = searchInterfacesForMetaProperty(propertyName, superInterfaces); if (property != null) break; } } return property; } private MetaBeanProperty getMetaPropertyFromMutableMetaClass(String propertyName, MetaClass metaClass) { final boolean isModified = ((MutableMetaClass) metaClass).isModified(); if (isModified) { final MetaProperty metaProperty = metaClass.getMetaProperty(propertyName); if(metaProperty instanceof MetaBeanProperty) return (MetaBeanProperty)metaProperty; } return null; } protected MetaMethod findMixinMethod(String methodName, Class[] arguments) { return null; } protected static MetaMethod findMethodInClassHierarchy(Class instanceKlazz, String methodName, Class[] arguments, MetaClass metaClass) { if (metaClass instanceof MetaClassImpl) { boolean check = false; for (ClassInfo ci : ((MetaClassImpl)metaClass).theCachedClass.getHierarchy ()) { final MetaClass aClass = ci.getStrongMetaClass(); if (aClass instanceof MutableMetaClass && ((MutableMetaClass)aClass).isModified()) { check = true; break; } } if (!check) return null; } MetaMethod method = null; Class superClass; if (metaClass.getTheClass().isArray() && !metaClass.getTheClass().getComponentType().isPrimitive() && metaClass.getTheClass().getComponentType() != Object.class) { superClass = Object[].class; } else { superClass = metaClass.getTheClass().getSuperclass(); } if (superClass != null) { MetaClass superMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(superClass); method = findMethodInClassHierarchy(instanceKlazz, methodName, arguments, superMetaClass); } else { if (metaClass.getTheClass().isInterface()) { MetaClass superMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(Object.class); method = findMethodInClassHierarchy(instanceKlazz, methodName, arguments, superMetaClass); } } method = findSubClassMethod(instanceKlazz, methodName, arguments, metaClass, method); MetaMethod infMethod = searchInterfacesForMetaMethod(instanceKlazz, methodName, arguments, metaClass); if (infMethod != null) { if (method == null) method = infMethod; else method = mostSpecific(method, infMethod, instanceKlazz); } method = findOwnMethod(instanceKlazz, methodName, arguments, metaClass, method); return method; } private static MetaMethod findSubClassMethod(Class instanceKlazz, String methodName, Class[] arguments, MetaClass metaClass, MetaMethod method) { if (metaClass instanceof MetaClassImpl) { Object list = ((MetaClassImpl) metaClass).getSubclassMetaMethods(methodName); if (list != null) { if (list instanceof MetaMethod) { MetaMethod m = (MetaMethod) list; if (m.getDeclaringClass().getTheClass().isAssignableFrom(instanceKlazz)) { if (m.isValidExactMethod(arguments)) { if (method == null) method = m; else { method = mostSpecific (method, m, instanceKlazz); } } } } else { FastArray arr = (FastArray) list; for (int i = 0; i != arr.size(); ++i) { MetaMethod m = (MetaMethod) arr.get(i); if (m.getDeclaringClass().getTheClass().isAssignableFrom(instanceKlazz)) { if (m.isValidExactMethod(arguments)) { if (method == null) method = m; else { method = mostSpecific (method, m, instanceKlazz); } } } } } } } return method; } private static MetaMethod mostSpecific(MetaMethod method, MetaMethod newMethod, Class instanceKlazz) { Class newMethodC = newMethod.getDeclaringClass().getTheClass(); Class methodC = method.getDeclaringClass().getTheClass(); if (!newMethodC.isAssignableFrom(instanceKlazz)) return method; if (newMethodC == methodC) return newMethod; if (newMethodC.isAssignableFrom(methodC)) { return method; } if (methodC.isAssignableFrom(newMethodC)) { return newMethod; } return newMethod; } private static MetaMethod searchInterfacesForMetaMethod(Class instanceKlazz, String methodName, Class[] arguments, MetaClass metaClass) { Class[] interfaces = metaClass.getTheClass().getInterfaces(); MetaMethod method = null; for (Class anInterface : interfaces) { MetaClass infMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(anInterface); MetaMethod infMethod = searchInterfacesForMetaMethod(instanceKlazz, methodName, arguments, infMetaClass); if (infMethod != null) { if (method == null) method = infMethod; else method = mostSpecific(method, infMethod, instanceKlazz); } } method = findSubClassMethod(instanceKlazz, methodName, arguments, metaClass, method); method = findOwnMethod(instanceKlazz, methodName, arguments, metaClass, method); return method; } protected static MetaMethod findOwnMethod(Class instanceKlazz, String methodName, Class[] arguments, MetaClass metaClass, MetaMethod method) { // we trick ourselves here if (instanceKlazz == metaClass.getTheClass()) return method; MetaMethod ownMethod = metaClass.pickMethod(methodName, arguments); if (ownMethod != null) { if (method == null) method = ownMethod; else method = mostSpecific(method, ownMethod, instanceKlazz); } return method; } protected Object getSubclassMetaMethods(String methodName) { return null; } private abstract class MethodIndexAction { public void iterate() { final ComplexKeyHashMap.Entry[] table = metaMethodIndex.methodHeaders.getTable(); int len = table.length; for (int i = 0; i != len; ++i) { for (SingleKeyHashMap.Entry classEntry = (SingleKeyHashMap.Entry) table[i]; classEntry != null; classEntry = (SingleKeyHashMap.Entry) classEntry.next) { Class clazz = (Class) classEntry.getKey(); if (skipClass(clazz)) continue; MetaMethodIndex.Header header = (MetaMethodIndex.Header) classEntry.getValue(); for (MetaMethodIndex.Entry nameEntry = header.head; nameEntry != null; nameEntry = nameEntry.nextClassEntry) { methodNameAction(clazz, nameEntry); } } } } public abstract void methodNameAction(Class clazz, MetaMethodIndex.Entry methods); public boolean skipClass(Class clazz) { return false; } } public Object getProperty(Object object, String property) { return getProperty(theClass, object, property, false, false); } public void setProperty(Object object, String property, Object newValue) { setProperty(theClass, object, property, newValue, false, false); } public Object getAttribute(Object object, String attribute) { return getAttribute(theClass, object, attribute, false, false); } public void setAttribute(Object object, String attribute, Object newValue) { setAttribute(theClass, object, attribute, newValue, false, false); } public MetaMethod pickMethod(String methodName, Class[] arguments) { return getMethodWithoutCaching(theClass, methodName, arguments, false); } /** * @deprecated use pickMethod instead */ protected MetaMethod retrieveMethod(String methodName, Class[] arguments) { return pickMethod(methodName, arguments); } /** * remove all method call cache entries. This should be done if a * method is added during runtime, but not by using a category. */ protected void clearInvocationCaches() { metaMethodIndex.clearCaches (); } private static final SingleKeyHashMap.Copier NAME_INDEX_COPIER = new SingleKeyHashMap.Copier() { public Object copy(Object value) { if (value instanceof FastArray) return ((FastArray) value).copy(); else return value; } }; private static final SingleKeyHashMap.Copier METHOD_INDEX_COPIER = new SingleKeyHashMap.Copier() { public Object copy(Object value) { return SingleKeyHashMap.copy(new SingleKeyHashMap(false), (SingleKeyHashMap) value, NAME_INDEX_COPIER); } }; class MethodIndex extends Index { public MethodIndex(boolean b) { super(false); } public MethodIndex(int size) { super(size); } public MethodIndex() { super(); } MethodIndex copy() { return (MethodIndex) SingleKeyHashMap.copy(new MethodIndex(false), this, METHOD_INDEX_COPIER); } protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public static class Index extends SingleKeyHashMap { public Index(int size) { } public Index() { } public Index(boolean size) { super(false); } public SingleKeyHashMap getNotNull(CachedClass key) { Entry res = getOrPut(key); if (res.value == null) { res.value = new SingleKeyHashMap(); } return (SingleKeyHashMap) res.value; } public void put(CachedClass key, SingleKeyHashMap value) { ((Entry) getOrPut(key)).value = value; } public SingleKeyHashMap getNullable(CachedClass clazz) { return (SingleKeyHashMap) get(clazz); } public boolean checkEquals(ComplexKeyHashMap.Entry e, Object key) { return ((Entry) e).key.equals(key); } } private static class DummyMetaMethod extends MetaMethod { public int getModifiers() { return 0; } public String getName() { return null; } public Class getReturnType() { return null; } public CachedClass getDeclaringClass() { return null; } public ParameterTypes getParamTypes() { return null; } public Object invoke(Object object, Object[] arguments) { return null; } } private static class GetMethodMetaProperty extends MetaProperty { private final MetaMethod theMethod; public GetMethodMetaProperty(String name, MetaMethod theMethod) { super(name, Object.class); this.theMethod = theMethod; } public Object getProperty(Object object) { return theMethod.doMethodInvoke(object, new Object[]{name}); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } } private static class GetBeanMethodMetaProperty extends MetaProperty { private final MetaMethod theMethod; public GetBeanMethodMetaProperty(String name, MetaMethod theMethod) { super(name, Object.class); this.theMethod = theMethod; } public Object getProperty(Object object) { return theMethod.doMethodInvoke(object, EMPTY_ARGUMENTS); } public void setProperty(Object object, Object newValue) { throw new UnsupportedOperationException(); } } } groovy-1.8.6/src/main/groovy/lang/MetaProperty.java0000644001501200150120000000441711627206700021657 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.reflect.Modifier; import org.codehaus.groovy.runtime.MetaClassHelper; /** * Represents a property on a bean which may have a getter and/or a setter * * @author James Strachan * @version $Revision$ */ public abstract class MetaProperty { protected final String name; protected Class type; public static final String PROPERTY_SET_PREFIX = "set"; public MetaProperty(String name, Class type) { this.name = name; this.type = type; } /** * @return the property of the given object * @throws Exception if the property could not be evaluated */ public abstract Object getProperty(Object object); /** * Sets the property on the given object to the new value * * @param object on which to set the property * @param newValue the new value of the property * @throws RuntimeException if the property could not be set */ public abstract void setProperty(Object object, Object newValue); public String getName() { return name; } /** * @return the type of the property */ public Class getType() { return type; } public int getModifiers() { return Modifier.PUBLIC; } public static String getGetterName(String propertyName, Class type) { String prefix = type == boolean.class || type == Boolean.class ? "is" : "get"; return prefix + MetaClassHelper.capitalize(propertyName); } public static String getSetterName(String propertyName) { return PROPERTY_SET_PREFIX + MetaClassHelper.capitalize(propertyName); } } groovy-1.8.6/src/main/groovy/lang/MetaClass.java0000644001501200150120000002132611627206700021076 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.ast.ClassNode; import java.util.List; /** * A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass * interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface * and the contract with the Groovy runtime system. * * In general the compiler and Groovy runtime engine interact with methods on this class whilst MetaClass * clients interact with the method defined by the MetaObjectProtocol interface * * @see MetaClassImpl * @see groovy.lang.MetaObjectProtocol * * @author John Wilson * @author Graeme Rocher */ public interface MetaClass extends MetaObjectProtocol { /** *

    Invokes a method on the given receiver for the specified arguments. The sender is the class that invoked the method on the object. * The MetaClass will attempt to establish the method to invoke based on the name and arguments provided. * *

    The isCallToSuper and fromInsideClass help the Groovy runtime perform optimisations on the call to go directly * to the super class if necessary * * @param sender The java.lang.Class instance that invoked the method * @param receiver The object which the method was invoked on * @param methodName The name of the method * @param arguments The arguments to the method * @param isCallToSuper Whether the method is a call to a super class method * @param fromInsideClass Whether the call was invoked from the inside or the outside of the class * * @return The return value of the method */ Object invokeMethod(Class sender, Object receiver, String methodName, Object[] arguments, boolean isCallToSuper, boolean fromInsideClass); /** *

    Retrieves a property on the given receiver for the specified arguments. The sender is the class that is requesting the property from the object. * The MetaClass will attempt to establish the method to invoke based on the name and arguments provided. * *

    The isCallToSuper and fromInsideClass help the Groovy runtime perform optimisations on the call to go directly * to the super class if necessary * * @param sender The java.lang.Class instance that requested the property * @param receiver The Object which the property is being retrieved from * @param property The name of the property * @param isCallToSuper Whether the call is to a super class property * @param fromInsideClass ?? * * @return The properties value */ Object getProperty(Class sender, Object receiver, String property, boolean isCallToSuper, boolean fromInsideClass); /** *

    Retrieves a property on the given receiver for the specified arguments. The sender is the class that is requesting the property from the object. * The MetaClass will attempt to establish the method to invoke based on the name and arguments provided. * *

    The isCallToSuper and fromInsideClass help the Groovy runtime perform optimisations on the call to go directly * to the super class if necessary * * @param sender The java.lang.Class instance that is mutating the property * @param receiver The Object which the property is being set on * @param property The name of the property * @param value The new value of the property to set * @param isCallToSuper Whether the call is to a super class property * @param fromInsideClass ?? */ void setProperty(Class sender, Object receiver, String property, Object value, boolean isCallToSuper, boolean fromInsideClass); /** * *

    Attempts to invoke the methodMissing method otherwise throws a MissingMethodException * * @see groovy.lang.MissingMethodException * * @param instance The instance to invoke methodMissing on * @param methodName The name of the method * @param arguments The arguments to the method * @return The results of methodMissing or throws MissingMethodException */ Object invokeMissingMethod(Object instance, String methodName, Object[] arguments); /** * Invokes the propertyMissing method otherwise throws a MissingPropertyException * * @param instance The instance of the class * @param propertyName The name of the property * @param optionalValue The value of the property which could be null in the case of a getter * @param isGetter Whether the missing property event was the result of a getter or a setter * * @return The result of the propertyMissing method or throws MissingPropertyException */ Object invokeMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter); /** * Retrieves the value of an attribute (field). This method is to support the Groovy runtime and not for general client API usage. * * @param sender The class of the object that requested the attribute * @param receiver The instance * @param messageName The name of the attribute * @param useSuper Whether to look-up on the super class or not * @return The attribute value */ Object getAttribute(Class sender, Object receiver, String messageName, boolean useSuper); /** * Sets the value of an attribute (field). This method is to support the Groovy runtime and not for general client API usage. * * @param sender The class of the object that requested the attribute * @param receiver The instance * @param messageName The name of the attribute * @param messageValue The value of the attribute * @param useSuper Whether to look-up on the super class or not * @param fromInsideClass Whether the call happened from the inside or the outside of a class */ void setAttribute(Class sender, Object receiver, String messageName, Object messageValue, boolean useSuper, boolean fromInsideClass); /** * complete the initialisation process. After this method * is called no methods should be added to the meta class. * Invocation of methods or access to fields/properties is * forbidden unless this method is called. This method * should contain any initialisation code, taking a longer * time to complete. An example is the creation of the * Reflector. It is suggested to synchronize this * method. */ void initialize(); /** * Retrieves a list of MetaProperty instances that the MetaClass has * * @see MetaProperty * * @return A list of MetaProperty instances */ List getProperties(); /** * Retrieves a list of MetaMethods held by the class * * @return A list of MetaMethods */ List getMethods(); /** * Obtains a reference to the original AST for the MetaClass if it is available at runtime * * @return The original AST or null if it cannot be returned */ ClassNode getClassNode(); /** * Retrieves a list of MetaMethods held by this class * * @return A list of MetaMethods */ List getMetaMethods(); /** * * Internal method to support Groovy runtime. Not for client usage. * * @param numberOfConstructors The number of constructors * @param arguments The arguments * * @return selected index */ int selectConstructorAndTransformArguments(int numberOfConstructors, Object[] arguments); /** * Selects a method by name and argument classes. This method * does not search for an exact match, it searches for a compatible * method. For this the method selection mechanism is used as provided * by the implementation of this MetaClass. pickMethod may or may * not be used during the method selection process when invoking a method. * There is no warranty for that. * * @return a matching MetaMethod or null * @throws GroovyRuntimeException if there is more than one matching method * @param methodName the name of the method to pick * @param arguments the method arguments */ MetaMethod pickMethod(String methodName, Class[] arguments); } groovy-1.8.6/src/main/groovy/lang/PropertyValue.java0000644001501200150120000000226511627206700022044 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; public class PropertyValue { // the owner of the property private Object bean; // the description of the property private MetaProperty mp; public PropertyValue(Object bean, MetaProperty mp) { this.bean = bean; this.mp = mp; } public String getName() { return mp.getName(); } public Class getType() { return mp.getType(); } public Object getValue() { return mp.getProperty(bean); } public void setValue(Object value) { mp.setProperty(bean, value); } } groovy-1.8.6/src/main/groovy/lang/GrabExclude.java0000644001501200150120000000335411707612044021411 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to exclude an indirectly referenced artifact from the classpath. *

    * Further information about customising grape behavior can be found on the Grape documentation page: * http://groovy.codehaus.org/Grape. */ @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) public @interface GrabExclude { /** * The organisation or group, e.g.: "org.apache.ant" */ String group() default ""; /** * The module or artifact, e.g.: "ant-junit" */ String module(); /** * Allows a more compact convenience format in one of two formats, * e.g.: "org.apache.ant:ant-junit" or "org.apache.ant#ant-junit". */ String value() default ""; }groovy-1.8.6/src/main/groovy/lang/MetaClassRegistry.java0000644001501200150120000001536111707612044022632 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.GeneratedClosure; import org.codehaus.groovy.runtime.metaclass.ClosureMetaClass; import java.lang.reflect.Constructor; import java.util.Iterator; /** * A MetaClassRegistry is an object that is responsible for managing the a cache of MetaClass instances. Each * java.lang.Class instance has an associated MetaClass and client code can query this interface for the MetaClass for * a given associated java.lang.Class * * @see groovy.lang.MetaClass * * @author John Wilson * @author Graeme Rocher * @author Jochen Theodorou * */ public interface MetaClassRegistry { /* * The main function of the registry * If a meta class exists then return it * otherwise create one, put it in the registry and return it */ MetaClass getMetaClass(Class theClass); /* * Do we really want these two? */ void setMetaClass(Class theClass, MetaClass theMetaClass); /** * Removes a cached MetaClass from the registry * @param theClass The Java class of the MetaClass to remove */ void removeMetaClass(Class theClass); /** * Retrieves the MetaClassCreationHandle that is responsible for constructing MetaClass instances * * @return The MetaClassCreationHandle instance */ MetaClassCreationHandle getMetaClassCreationHandler(); /** * Sets the MetaClassCreationHandle instance that is responsible for constructing instances * * @param handle The handle instance */ void setMetaClassCreationHandle(MetaClassCreationHandle handle); /** * adds a ConstantMetaClassChangeListener * * @param listener - the update listener */ void addMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener); /** * removes a ConstantMetaClassChangeListener * * @param listener - the update listener */ void removeMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener); /** * Returns all registered ConstantMetaClassChangeListener objects. * * @return an array containing all change listener */ MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners(); /** * gets a snapshot of the current constant meta classes and returns it as Iterator. * Modifications done using this Iterator will not cause a ConcurrentModificationException. * If a MetaClass is removed using this Iterator, then the MetaClass will only * be removed if the MetaClass was not replaced by another MetaClass in the meantime. * If a MetaClass is added while using this Iterator, then it will be part of the Iteration. * If a MetaClass replaces another constant meta class, then the Iteration might show two * meta classes for the same class.
    * This Iterator may not used in multiple threads. * * @return Iterator for the constant meta classes */ Iterator iterator(); /** * Class used as base for the creation of MetaClass implementations. * The Class defaults to MetaClassImpl, if the class loading fails to * find a special meta class. The name for such a meta class would be * the class name it is created for with the prefix * "groovy.runtime.metaclass." By replacing the handle in the registry * you can have any control over the creation of what MetaClass is used * for a class that you want to have. * WARNING: experimental code, likely to change soon * @author Jochen Theodorou */ class MetaClassCreationHandle { private boolean disableCustomMetaClassLookup; public final MetaClass create(Class theClass, MetaClassRegistry registry) { if (disableCustomMetaClassLookup) return createNormalMetaClass(theClass, registry); return createWithCustomLookup(theClass, registry); } private MetaClass createWithCustomLookup(Class theClass, MetaClassRegistry registry) { try { final Class customMetaClass = Class.forName("groovy.runtime.metaclass." + theClass.getName() + "MetaClass"); if (DelegatingMetaClass.class.isAssignableFrom(customMetaClass)) { final Constructor customMetaClassConstructor = customMetaClass.getConstructor(MetaClass.class); MetaClass normalMetaClass = createNormalMetaClass(theClass, registry); return (MetaClass)customMetaClassConstructor.newInstance(normalMetaClass); } else { final Constructor customMetaClassConstructor = customMetaClass.getConstructor(MetaClassRegistry.class, Class.class); return (MetaClass)customMetaClassConstructor.newInstance(registry, theClass); } } catch (final ClassNotFoundException e) { return createNormalMetaClass(theClass, registry); } catch (final Exception e) { throw new GroovyRuntimeException("Could not instantiate custom Metaclass for class: " + theClass.getName() + ". Reason: " + e, e); } } protected MetaClass createNormalMetaClass(Class theClass,MetaClassRegistry registry) { if (GeneratedClosure.class.isAssignableFrom(theClass)) { return new ClosureMetaClass(registry,theClass); } else { return new MetaClassImpl(registry, theClass); } } public boolean isDisableCustomMetaClassLookup() { return disableCustomMetaClassLookup; } /** * Set flag saying to disable lookup of custom meta classes * It's enough to call this method only once in your application for handle which was set in to registry * as every new handle will inherit this property * @param disableCustomMetaClassLookup flag saying to disable lookup of custom meta classes */ public void setDisableCustomMetaClassLookup(boolean disableCustomMetaClassLookup) { this.disableCustomMetaClassLookup = disableCustomMetaClassLookup; } } } groovy-1.8.6/src/main/groovy/lang/MissingPropertyException.java0000644001501200150120000000520311627206700024253 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.MethodRankHelper; /** * An exception occurred if a dynamic property dispatch fails with an unknown property. * * Note that the Missing*Exception classes were named for consistency and * to avoid conflicts with JDK exceptions of the same name. * * @author James Strachan * @version $Revision$ */ public class MissingPropertyException extends GroovyRuntimeException { public static final Object MPE = new Object(); private final String property; private final Class type; public MissingPropertyException(String property, Class type) { this.property = property; this.type = type; } public MissingPropertyException(String property, Class type, Throwable t) { super(t); this.property = property; this.type = type; } public MissingPropertyException(String message) { super(message); this.property = null; this.type = null; } public MissingPropertyException(String message, String property, Class type) { super(message); this.property = property; this.type = type; } public String getMessageWithoutLocationText() { final Throwable cause = getCause(); if (cause == null) { if (super.getMessageWithoutLocationText() != null) { return super.getMessageWithoutLocationText(); } return "No such property: " + property + " for class: " + type.getName() + MethodRankHelper.getPropertySuggestionString(property, type); } return "No such property: " + property + " for class: " + type.getName() + ". Reason: " + cause; } /** * @return the name of the property that could not be found */ public String getProperty() { return property; } /** * * @return The type on which the property was attempted to be called */ public Class getType() { return type; } } groovy-1.8.6/src/main/groovy/lang/Writable.java0000644001501200150120000000433111627206700020770 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.io.IOException; import java.io.Writer; /** *

    Represents an object which is capable of writing itself to a text stream * in a more efficient format than just creating a toString() representation * of itself. This mechanism is particularly useful for templates and such like. *

    * *

    It is worth noting that writable implementations often override their * toString() implementation as well to allow rendering the same result * directly to a String; however this is not required.

    * * @author James Strachan * @version $Revision$ */ public interface Writable { /** *

    Writes this object to the given writer.

    * *

    This is used to defer content creation until the point when it is * streamed to the output destination. Oftentimes, content will be defined * but not necessarily created (as is may be the case with a Closure * definition.) In that case, the output is then 'deferred' to the point * when it is serialized to the writer. This class may be used whenever an * object should be responsible for creating its own textual representation, * but creating the entire output as a single String would be inefficient * (such as outputting a multi-gigabyte XML document.)

    * * @param out the Writer to which this Writable should output its data. * @return the Writer that was passed * @throws IOException if an error occurred while outputting data to the * writer */ Writer writeTo(Writer out) throws IOException; } groovy-1.8.6/src/main/groovy/lang/Tuple.java0000644001501200150120000000470311627206700020313 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import java.util.AbstractList; import java.util.List; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Represents a list of Integer objects from a specified int up to but not including * a given and to. * * @author James Strachan * @version $Revision$ */ public class Tuple extends AbstractList { private Object[] contents; private int hashCode; public Tuple(Object[] contents) { this.contents = contents; } public Object get(int index) { return contents[index]; } public int size() { return contents.length; } public boolean equals(Object that) { if (that instanceof Tuple) { return equals((Tuple) that); } return false; } public boolean equals(Tuple that) { if (contents.length == that.contents.length) { for (int i = 0; i < contents.length; i++) { if (! DefaultTypeTransformation.compareEqual(this.contents[i], that.contents[i])) { return false; } } return true; } return false; } public int hashCode() { if (hashCode == 0) { for (int i = 0; i < contents.length; i++ ) { Object value = contents[i]; int hash = (value != null) ? value.hashCode() : 0xbabe; hashCode ^= hash; } if (hashCode == 0) { hashCode = 0xbabe; } } return hashCode; } public List subList(int fromIndex, int toIndex) { int size = toIndex - fromIndex; Object[] newContent = new Object[size]; System.arraycopy(contents, fromIndex, newContent, 0, size); return new Tuple(newContent); } } groovy-1.8.6/src/main/groovy/lang/Singleton.java0000644001501200150120000000303311707612044021160 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class annotation to make class singleton. * * Singleton can be initialized in static initialization of the class or lazily (on first access) * To make singleton lazy it is enough to use {@code @Singleton(lazy=true)} * Lazy singletons implemented with double check locking and volatile field * * @author Alex Tkachman */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.SingletonASTTransformation") public @interface Singleton { /** * @return if this singleton should be lazy */ boolean lazy () default false; } groovy-1.8.6/src/main/groovy/lang/Script.java0000644001501200150120000001626111627206700020470 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.lang; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.File; import java.io.IOException; /** * This object represents a Groovy script * * @author James Strachan * @author Guillaume Laforge * @version $Revision$ */ public abstract class Script extends GroovyObjectSupport { private Binding binding; protected Script() { this(new Binding()); } protected Script(Binding binding) { this.binding = binding; } public Binding getBinding() { return binding; } public void setBinding(Binding binding) { this.binding = binding; } public Object getProperty(String property) { try { return binding.getVariable(property); } catch (MissingPropertyException e) { return super.getProperty(property); } } public void setProperty(String property, Object newValue) { if ("binding".equals(property)) setBinding((Binding) newValue); else if("metaClass".equals(property)) setMetaClass((MetaClass)newValue); else binding.setVariable(property, newValue); } /** * Invoke a method (or closure in the binding) defined. * * @param name method to call * @param args arguments to pass to the method * @return value */ public Object invokeMethod(String name, Object args) { try { return super.invokeMethod(name, args); } // if the method was not found in the current scope (the script's methods) // let's try to see if there's a method closure with the same name in the binding catch (MissingMethodException mme) { try { if (name.equals(mme.getMethod())) { Object boundClosure = binding.getVariable(name); if (boundClosure != null && boundClosure instanceof Closure) { return ((Closure) boundClosure).call((Object[])args); } else { throw mme; } } else { throw mme; } } catch (MissingPropertyException mpe) { throw mme; } } } /** * The main instance method of a script which has variables in scope * as defined by the current {@link Binding} instance. */ public abstract Object run(); // println helper methods /** * Prints a newline to the current 'out' variable which should be a PrintWriter * or at least have a println() method defined on it. * If there is no 'out' property then print to standard out. */ public void println() { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { System.out.println(); return; } InvokerHelper.invokeMethod(object, "println", ArgumentListExpression.EMPTY_ARRAY); } /** * Prints the value to the current 'out' variable which should be a PrintWriter * or at least have a print() method defined on it. * If there is no 'out' property then print to standard out. */ public void print(Object value) { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.print(System.out,value); return; } InvokerHelper.invokeMethod(object, "print", new Object[]{value}); } /** * Prints the value and a newline to the current 'out' variable which should be a PrintWriter * or at least have a println() method defined on it. * If there is no 'out' property then print to standard out. */ public void println(Object value) { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.println(System.out,value); return; } InvokerHelper.invokeMethod(object, "println", new Object[]{value}); } /** * Prints a formatted string using the specified format string and argument. * * @param format the format to follow * @param value the value to be formatted */ public void printf(String format, Object value) { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.printf(System.out, format, value); return; } InvokerHelper.invokeMethod(object, "printf", new Object[] { format, value }); } /** * Prints a formatted string using the specified format string and arguments. * * @param format the format to follow * @param values an array of values to be formatted */ public void printf(String format, Object[] values) { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.printf(System.out, format, values); return; } InvokerHelper.invokeMethod(object, "printf", new Object[] { format, values }); } /** * A helper method to allow the dynamic evaluation of groovy expressions using this * scripts binding as the variable scope * * @param expression is the Groovy script expression to evaluate */ public Object evaluate(String expression) throws CompilationFailedException { GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding); return shell.evaluate(expression); } /** * A helper method to allow the dynamic evaluation of groovy expressions using this * scripts binding as the variable scope * * @param file is the Groovy script to evaluate */ public Object evaluate(File file) throws CompilationFailedException, IOException { GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding); return shell.evaluate(file); } /** * A helper method to allow scripts to be run taking command line arguments */ public void run(File file, String[] arguments) throws CompilationFailedException, IOException { GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding); shell.run(file, arguments); } } groovy-1.8.6/src/main/groovy/servlet/0000755001501200150120000000000011713766062017126 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/servlet/GroovyServlet.java0000644001501200150120000001477511627206700022631 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.servlet; import groovy.lang.Closure; import groovy.util.GroovyScriptEngine; import groovy.util.ResourceException; import groovy.util.ScriptException; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.groovy.runtime.GroovyCategorySupport; /** * This servlet will run Groovy scripts as Groovlets. Groovlets are scripts * with these objects implicit in their scope: * *
      *
    • request - the HttpServletRequest
    • *
    • response - the HttpServletResponse
    • *
    • application - the ServletContext associated with the servlet
    • *
    • session - the HttpSession associated with the HttpServletRequest
    • *
    • out - the PrintWriter associated with the ServletRequest
    • *
    * *

    Your script sources can be placed either in your web application's normal * web root (allows for subdirectories) or in /WEB-INF/groovy/* (also allows * subdirectories). * *

    To make your web application more groovy, you must add the GroovyServlet * to your application's web.xml configuration using any mapping you like, so * long as it follows the pattern *.* (more on this below). Here is the * web.xml entry: * *

     *    <servlet>
     *      <servlet-name>Groovy</servlet-name>
     *      <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
     *    </servlet>
     *
     *    <servlet-mapping>
     *      <servlet-name>Groovy</servlet-name>
     *      <url-pattern>*.groovy</url-pattern>
     *      <url-pattern>*.gdo</url-pattern>
     *    </servlet-mapping>
     * 
    * *

    The URL pattern does not require the "*.groovy" mapping. You can, for * example, make it more Struts-like but groovy by making your mapping "*.gdo". * * @author Sam Pullara * @author Mark Turansky (markturansky at hotmail.com) * @author Guillaume Laforge * @author Christian Stein * @author Marcel Overdijk * * @see groovy.servlet.ServletBinding */ public class GroovyServlet extends AbstractHttpServlet { /** * The script engine executing the Groovy scripts for this servlet */ private GroovyScriptEngine gse; /** * Initialize the GroovyServlet. * * @throws ServletException * if this method encountered difficulties */ public void init(ServletConfig config) throws ServletException { super.init(config); // Set up the scripting engine gse = createGroovyScriptEngine(); servletContext.log("Groovy servlet initialized on " + gse + "."); } /** * Handle web requests to the GroovyServlet */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { // Get the script path from the request - include aware (GROOVY-815) final String scriptUri = getScriptUri(request); // Set it to HTML by default response.setContentType("text/html; charset="+encoding); // Set up the script context final ServletBinding binding = new ServletBinding(request, response, servletContext); setVariables(binding); // Run the script try { Closure closure = new Closure(gse) { public Object call() { try { return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding); } catch (ResourceException e) { throw new RuntimeException(e); } catch (ScriptException e) { throw new RuntimeException(e); } } }; GroovyCategorySupport.use(ServletCategory.class, closure); } catch (RuntimeException runtimeException) { StringBuffer error = new StringBuffer("GroovyServlet Error: "); error.append(" script: '"); error.append(scriptUri); error.append("': "); Throwable e = runtimeException.getCause(); /* * Null cause?! */ if (e == null) { error.append(" Script processing failed."); error.append(runtimeException.getMessage()); if (runtimeException.getStackTrace().length > 0) error.append(runtimeException.getStackTrace()[0].toString()); servletContext.log(error.toString()); System.err.println(error.toString()); runtimeException.printStackTrace(System.err); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error.toString()); return; } /* * Resource not found. */ if (e instanceof ResourceException) { error.append(" Script not found, sending 404."); servletContext.log(error.toString()); System.err.println(error.toString()); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } /* * Other internal error. Perhaps syntax?! */ servletContext.log("An error occurred processing the request", runtimeException); error.append(e.getMessage()); if (e.getStackTrace().length > 0) error.append(e.getStackTrace()[0].toString()); servletContext.log(e.toString()); System.err.println(e.toString()); runtimeException.printStackTrace(System.err); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } } /** * Hook method to setup the GroovyScriptEngine to use.
    * Subclasses may override this method to provide a custom * engine. */ protected GroovyScriptEngine createGroovyScriptEngine(){ return new GroovyScriptEngine(this); } } groovy-1.8.6/src/main/groovy/servlet/AbstractHttpServlet.java0000644001501200150120000003746711713766062023762 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.servlet; import groovy.util.ResourceConnector; import groovy.util.ResourceException; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; /** * A base class dealing with common HTTP servlet API housekeeping aspects. *

    *

    Resource name mangling (pattern replacement)

    *

    *

    * Also implements Groovy's {@link groovy.util.ResourceConnector} in a dynamic * manner. It allows you to modify the resource name that is searched for with a * replace all operation. See {@link java.util.regex.Pattern} and * {@link java.util.regex.Matcher} for details. * The servlet init parameter names are: *

     * resource.name.regex = empty - defaults to null
     * resource.name.replacement = empty - defaults to null
     * resource.name.replace.all = true (default) | false means replaceFirst()
     * 
    * Note: If you specify a regex, you have to specify a replacement string too! * Otherwise an exception gets raised. *

    *

    Logging and bug-hunting options

    *

    *

    * This implementation provides a verbosity flag switching log statements. * The servlet init parameter name is: *

     * verbose = false(default) | true
     * 
    *

    *

    * In order to support class-loading-troubles-debugging with Tomcat 4 or * higher, you can log the class loader responsible for loading some classes. * See GROOVY-861 for details. * The servlet init parameter name is: *

     * log.GROOVY861 = false(default) | true
     * 
    *

    *

    * If you experience class-loading-troubles with Tomcat 4 (or higher) or any * other servlet container using custom class loader setups, you can fallback * to use (slower) reflection in Groovy's MetaClass implementation. Please * contact the dev team with your problem! Thanks. * The servlet init parameter name is: *

     * reflection = false(default) | true
     * 
    * * @author Christian Stein * @author Roshan Dawrani (roshandawrani) */ public abstract class AbstractHttpServlet extends HttpServlet implements ResourceConnector { /** * Content type of the HTTP response. */ public static final String CONTENT_TYPE_TEXT_HTML = "text/html"; /** * Servlet API include key name: path_info */ public static final String INC_PATH_INFO = "javax.servlet.include.path_info"; /* *** Not used, yet. See comments in getScriptUri(HttpServletRequest). *** * Servlet API include key name: request_uri */ public static final String INC_REQUEST_URI = "javax.servlet.include.request_uri"; /** * Servlet API include key name: servlet_path */ public static final String INC_SERVLET_PATH = "javax.servlet.include.servlet_path"; /** * Servlet (or the web application) context. */ protected ServletContext servletContext; /** * Either null or a compiled pattern matcher read from "{@code resource.name.regex}" * and used in {@link AbstractHttpServlet#getScriptUri(HttpServletRequest)}. */ protected Matcher resourceNameMatcher; /** * The replacement used by the resource name matcher. */ protected String resourceNameReplacement; /** * The replace method to use on the matcher. *
         * true - replaceAll(resourceNameReplacement); (default)
         * false - replaceFirst(resourceNameReplacement);
         * 
    */ protected boolean resourceNameReplaceAll; /** * Controls almost all log output. */ protected boolean verbose; /** * Encoding to use, becomes charset part of contentType. */ protected String encoding = "UTF-8"; /** * Mirrors the static value of the reflection flag in MetaClass. * See AbstractHttpServlet#logGROOVY861 */ protected boolean reflection; /** * Debug flag logging the class the class loader of the request. */ private boolean logGROOVY861; /** * Initializes all fields with default values. */ public AbstractHttpServlet() { this.servletContext = null; this.resourceNameMatcher = null; this.resourceNameReplacement = null; this.resourceNameReplaceAll = true; this.verbose = false; this.reflection = false; this.logGROOVY861 = false; } /** * Interface method for ResourceContainer. This is used by the GroovyScriptEngine. */ public URLConnection getResourceConnection(String name) throws ResourceException { String basePath = servletContext.getRealPath("/"); if (name.startsWith(basePath)) name = name.substring(basePath.length()); name = name.replaceAll("\\\\", "/"); //remove the leading / as we are trying with a leading / now if (name.startsWith("/")) name = name.substring(1); /* * Try to locate the resource and return an opened connection to it. */ try { String tryScriptName = "/" + name; URL url = servletContext.getResource(tryScriptName); if (url == null) { tryScriptName = "/WEB-INF/groovy/" + name; url = servletContext.getResource("/WEB-INF/groovy/" + name); } if (url == null) { throw new ResourceException("Resource \"" + name + "\" not found!"); } else { url = new URL("file", "", servletContext.getRealPath(tryScriptName)); } return url.openConnection(); } catch (IOException e) { throw new ResourceException("Problems getting resource named \"" + name + "\"!", e); } } private boolean isFile(URL ret) { return ret != null && ret.getProtocol().equals("file"); } /** * Returns the include-aware uri of the script or template file. * * @param request the http request to analyze * @return the include-aware uri either parsed from request attributes or * hints provided by the servlet container */ protected String getScriptUri(HttpServletRequest request) { /* * Log some debug information for http://jira.codehaus.org/browse/GROOVY-861 */ if (logGROOVY861) { log("Logging request class and its class loader:"); log(" c = request.getClass() :\"" + request.getClass() + "\""); log(" l = c.getClassLoader() :\"" + request.getClass().getClassLoader() + "\""); log(" l.getClass() :\"" + request.getClass().getClassLoader().getClass() + "\""); /* * Keep logging, if we're verbose. Else turn it off. */ logGROOVY861 = verbose; } // // NOTE: This piece of code is heavily inspired by Apaches Jasper2! // // http://cvs.apache.org/viewcvs.cgi/jakarta-tomcat-jasper/jasper2/ \ // src/share/org/apache/jasper/servlet/JspServlet.java?view=markup // // Why doesn't it use request.getRequestURI() or INC_REQUEST_URI? // String uri = null; String info = null; // // Check to see if the requested script/template source file has been the // target of a RequestDispatcher.include(). // uri = (String) request.getAttribute(INC_SERVLET_PATH); if (uri != null) { // // Requested script/template file has been target of // RequestDispatcher.include(). Its path is assembled from the relevant // javax.servlet.include.* request attributes and returned! // info = (String) request.getAttribute(INC_PATH_INFO); if (info != null) { uri += info; } return applyResourceNameMatcher(uri); } // // Requested script/template file has not been the target of a // RequestDispatcher.include(). Reconstruct its path from the request's // getServletPath() and getPathInfo() results. // uri = request.getServletPath(); info = request.getPathInfo(); if (info != null) { uri += info; } /* * TODO : Enable auto ".groovy" extension replacing here! * http://cvs.groovy.codehaus.org/viewrep/groovy/groovy/groovy-core/src/main/groovy/servlet/GroovyServlet.java?r=1.10#l259 */ return applyResourceNameMatcher(uri); } private String applyResourceNameMatcher(final String aUri) { /* * mangle resource name with the compiled pattern. */ String uri = aUri; Matcher matcher = resourceNameMatcher; if (matcher != null) { matcher.reset(uri); String replaced; if (resourceNameReplaceAll) { replaced = matcher.replaceAll(resourceNameReplacement); } else { replaced = matcher.replaceFirst(resourceNameReplacement); } if (!uri.equals(replaced)) { if (verbose) { log("Replaced resource name \"" + uri + "\" with \"" + replaced + "\"."); } uri = replaced; } } return uri; } /** * Parses the http request for the real script or template source file. * * @param request * the http request to analyze * @return a file object using an absolute file path name, or null if the * servlet container cannot translate the virtual path to a real * path for any reason (such as when the content is being made * available from a .war archive). */ protected File getScriptUriAsFile(HttpServletRequest request) { String uri = getScriptUri(request); String real = servletContext.getRealPath(uri); if (real == null) { return null; } return new File(real).getAbsoluteFile(); } /** * Overrides the generic init method to set some debug flags. * * @param config the servlet configuration provided by the container * @throws ServletException if init() method defined in super class * javax.servlet.GenericServlet throws it */ public void init(ServletConfig config) throws ServletException { /* * Never forget super.init()! */ super.init(config); /* * Grab the servlet context. */ this.servletContext = config.getServletContext(); // Get verbosity hint. String value = config.getInitParameter("verbose"); if (value != null) { this.verbose = Boolean.valueOf(value); } // get encoding value = config.getInitParameter("encoding"); if (value != null) { this.encoding = value; } // And now the real init work... if (verbose) { log("Parsing init parameters..."); } String regex = config.getInitParameter("resource.name.regex"); if (regex != null) { String replacement = config.getInitParameter("resource.name.replacement"); if (replacement == null) { Exception npex = new NullPointerException("resource.name.replacement"); String message = "Init-param 'resource.name.replacement' not specified!"; log(message, npex); throw new ServletException(message, npex); } int flags = 0; // TODO : Parse pattern compile flags. this.resourceNameMatcher = Pattern.compile(regex, flags).matcher(""); this.resourceNameReplacement = replacement; String all = config.getInitParameter("resource.name.replace.all"); if (all != null) { this.resourceNameReplaceAll = Boolean.valueOf(all); } } value = config.getInitParameter("logGROOVY861"); if (value != null) { this.logGROOVY861 = Boolean.valueOf(value); // nothing else to do here } /* * If verbose, log the parameter values. */ if (verbose) { log("(Abstract) init done. Listing some parameter name/value pairs:"); log("verbose = " + verbose); // this *is* verbose! ;) log("reflection = " + reflection); log("logGROOVY861 = " + logGROOVY861); if (resourceNameMatcher != null) { log("resource.name.regex = " + resourceNameMatcher.pattern().pattern()); } else { log("resource.name.regex = null"); } log("resource.name.replacement = " + resourceNameReplacement); } } /** * Override this method to set your variables to the Groovy binding. *

    * All variables bound the binding are passed to the template source text, * e.g. the HTML file, when the template is merged. *

    *

    * The binding provided by TemplateServlet does already include some default * variables. As of this writing, they are (copied from * {@link groovy.servlet.ServletBinding}): *

      *
    • "request" : HttpServletRequest
    • *
    • "response" : HttpServletResponse
    • *
    • "context" : ServletContext
    • *
    • "application" : ServletContext
    • *
    • "session" : request.getSession(false)
    • *
    *

    *

    * And via implicit hard-coded keywords: *

      *
    • "out" : response.getWriter()
    • *
    • "sout" : response.getOutputStream()
    • *
    • "html" : new MarkupBuilder(response.getWriter())
    • *
    *

    *

    * The binding also provides convenient methods: *

      *
    • "forward(String path)" : request.getRequestDispatcher(path).forward(request, response);
    • *
    • "include(String path)" : request.getRequestDispatcher(path).include(request, response);
    • *
    • "redirect(String location)" : response.sendRedirect(location);
    • *
    *

    *

    *

    Example binding all servlet context variables: *

    
         * class MyServlet extends TemplateServlet {
         * 

    * protected void setVariables(ServletBinding binding) { * // Bind a simple variable * binding.setVariable("answer", new Long(42)); *

    * // Bind all servlet context attributes... * ServletContext context = (ServletContext) binding.getVariable("context"); * Enumeration enumeration = context.getAttributeNames(); * while (enumeration.hasMoreElements()) { * String name = (String) enumeration.nextElement(); * binding.setVariable(name, context.getAttribute(name)); * } * } *

    * } *

    *

    * * @param binding to be modified */ protected void setVariables(ServletBinding binding) { // empty } } groovy-1.8.6/src/main/groovy/servlet/ServletCategory.java0000644001501200150120000000536311627206700023112 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; /** * Servlet support. */ public class ServletCategory { public static Object get(ServletContext context, String key) { return context.getAttribute(key); } public static Object get(HttpSession session, String key) { return session.getAttribute(key); } public static Object get(ServletRequest request, String key) { return request.getAttribute(key); } public static Object get(PageContext context, String key) { return context.getAttribute(key); } public static Object getAt(ServletContext context, String key) { return context.getAttribute(key); } public static Object getAt(HttpSession session, String key) { return session.getAttribute(key); } public static Object getAt(ServletRequest request, String key) { return request.getAttribute(key); } public static Object getAt(PageContext context, String key) { return context.getAttribute(key); } public static void set(ServletContext context, String key, Object value) { context.setAttribute(key, value); } public static void set(HttpSession session, String key, Object value) { session.setAttribute(key, value); } public static void set(ServletRequest request, String key, Object value) { request.setAttribute(key, value); } public static void set(PageContext context, String key, Object value) { context.setAttribute(key, value); } public static void putAt(ServletContext context, String key, Object value) { context.setAttribute(key, value); } public static void putAt(HttpSession session, String key, Object value) { session.setAttribute(key, value); } public static void putAt(ServletRequest request, String key, Object value) { request.setAttribute(key, value); } public static void putAt(PageContext context, String key, Object value) { context.setAttribute(key, value); } } groovy-1.8.6/src/main/groovy/servlet/package.html0000644001501200150120000000030411627206700021374 0ustar miguelmiguel package groovy.servlet.*

    Support for Groovlets which are Servlets written as a simple Groovy script.

    groovy-1.8.6/src/main/groovy/servlet/TemplateServlet.java0000644001501200150120000004331211713766062023114 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.servlet; import groovy.text.SimpleTemplateEngine; import groovy.text.Template; import groovy.text.TemplateEngine; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.util.Date; import java.util.Map; import java.util.WeakHashMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A generic servlet for serving (mostly HTML) templates. *

    *

    * It delegates work to a groovy.text.TemplateEngine implementation * processing HTTP requests. *

    *

    Usage

    *

    * helloworld.html is a headless HTML-like template *

    
     *  <html>
     *    <body>
     *      <% 3.times { %>
     *        Hello World!
     *      <% } %>
     *      <br>
     *    </body>
     *  </html>
     * 
    *

    * Minimal web.xml example serving HTML-like templates *

    
     * <web-app>
     *   <servlet>
     *     <servlet-name>template</servlet-name>
     *     <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
     *   </servlet>
     *   <servlet-mapping>
     *     <servlet-name>template</servlet-name>
     *     <url-pattern>*.html</url-pattern>
     *   </servlet-mapping>
     * </web-app>
     * 
    *

    *

    Template engine configuration

    *

    *

    * By default, the TemplateServer uses the {@link groovy.text.SimpleTemplateEngine} * which interprets JSP-like templates. The init parameter template.engine * defines the fully qualified class name of the template to use: *

     *   template.engine = [empty] - equals groovy.text.SimpleTemplateEngine
     *   template.engine = groovy.text.SimpleTemplateEngine
     *   template.engine = groovy.text.GStringTemplateEngine
     *   template.engine = groovy.text.XmlTemplateEngine
     * 
    *

    *

    Servlet Init Parameters

    *

    *

    Logging and extra-output options

    *

    *

    * This implementation provides a verbosity flag switching log statements. * The servlet init parameter name is: *

     *   generated.by = true(default) | false
     * 
    *

    *

    Groovy Source Encoding Parameter

    *

    *

    * The following servlet init parameter name can be used to specify the encoding TemplateServlet will use * to read the template groovy source files: *

     *   groovy.source.encoding
     * 
    * * @author Christian Stein * @author Guillaume Laforge * @version 2.0 * @see TemplateServlet#setVariables(ServletBinding) */ public class TemplateServlet extends AbstractHttpServlet { /** * Simple cache entry. If a file is supplied, then the entry is validated against * last modified and length attributes of the specified file. * * @author Christian Stein */ private static class TemplateCacheEntry { Date date; long hit; long lastModified; long length; Template template; public TemplateCacheEntry(File file, Template template) { this(file, template, false); // don't get time millis for sake of speed } public TemplateCacheEntry(File file, Template template, boolean timestamp) { if (template == null) { throw new NullPointerException("template"); } if (timestamp) { this.date = new Date(System.currentTimeMillis()); } else { this.date = null; } this.hit = 0; if (file != null) { this.lastModified = file.lastModified(); this.length = file.length(); } this.template = template; } /** * Checks the passed file attributes against those cached ones. * * @param file Other file handle to compare to the cached values. May be null in which case the validation is skipped. * @return true if all measured values match, else false */ public boolean validate(File file) { if (file != null) { if (file.lastModified() != this.lastModified) { return false; } if (file.length() != this.length) { return false; } } hit++; return true; } public String toString() { if (date == null) { return "Hit #" + hit; } return "Hit #" + hit + " since " + date; } } /** * Simple file name to template cache map. */ private final Map cache; /** * Underlying template engine used to evaluate template source files. */ private TemplateEngine engine; /** * Flag that controls the appending of the "Generated by ..." comment. */ private boolean generateBy; private String fileEncodingParamVal; private static final String GROOVY_SOURCE_ENCODING = "groovy.source.encoding"; /** * Create new TemplateServlet. */ public TemplateServlet() { this.cache = new WeakHashMap(); this.engine = null; // assigned later by init() this.generateBy = true; // may be changed by init() this.fileEncodingParamVal = null; // may be changed by init() } /** * Find a cached template for a given key. If a File is passed then * any cached object is validated against the File to determine if it is out of * date * @param key a unique key for the template, such as a file's absolutePath or a URL. * @param file a file to be used to determine if the cached template is stale. May be null. * @return The cached template, or null if there was no cached entry, or the entry was stale. */ private Template findCachedTemplate(String key, File file) { Template template = null; /* * Test cache for a valid template bound to the key. */ if (verbose) { log("Looking for cached template by key \"" + key + "\""); } TemplateCacheEntry entry = (TemplateCacheEntry) cache.get(key); if (entry != null) { if (entry.validate(file)) { if (verbose) { log("Cache hit! " + entry); } template = entry.template; } else { if (verbose) { log("Cached template " + key + " needs recompiliation! " + entry); } } } else { if (verbose) { log("Cache miss for " + key); } } return template; } /** * Compile the template and store it in the cache. * @param key a unique key for the template, such as a file's absolutePath or a URL. * @param reader a reader for the template's source. * @param file a file to be used to determine if the cached template is stale. May be null. * @return the created template. * @throws Exception Any exception when creating the template. */ private Template createAndStoreTemplate(String key, InputStream inputStream, File file) throws Exception { if (verbose) { log("Creating new template from " + key + "..."); } Reader reader = null; try { String fileEncoding = (fileEncodingParamVal != null) ? fileEncodingParamVal : System.getProperty(GROOVY_SOURCE_ENCODING); reader = fileEncoding == null ? new InputStreamReader(inputStream) : new InputStreamReader(inputStream, fileEncoding); Template template = engine.createTemplate(reader); cache.put(key, new TemplateCacheEntry(file, template, verbose)); if (verbose) { log("Created and added template to cache. [key=" + key + "] " + cache.get(key)); } // // Last sanity check. // if (template == null) { throw new ServletException("Template is null? Should not happen here!"); } return template; } finally { if (reader != null) { reader.close(); } else if (inputStream != null) { inputStream.close(); } } } /** * Gets the template created by the underlying engine parsing the request. * *

    * This method looks up a simple (weak) hash map for an existing template * object that matches the source file. If the source file didn't change in * length and its last modified stamp hasn't changed compared to a precompiled * template object, this template is used. Otherwise, there is no or an * invalid template object cache entry, a new one is created by the underlying * template engine. This new instance is put to the cache for consecutive * calls. *

    * * @return The template that will produce the response text. * @param file * The file containing the template source. * * @throws ServletException * If the request specified an invalid template source file */ protected Template getTemplate(File file) throws ServletException { String key = file.getAbsolutePath(); Template template = findCachedTemplate(key, file); // // Template not cached or the source file changed - compile new template! // if (template == null) { try { template = createAndStoreTemplate(key, new FileInputStream(file), file); } catch (Exception e) { throw new ServletException("Creation of template failed: " + e, e); } } return template; } /** * Gets the template created by the underlying engine parsing the request. * *

    * This method looks up a simple (weak) hash map for an existing template * object that matches the source URL. If there is no cache entry, a new one is * created by the underlying template engine. This new instance is put * to the cache for consecutive calls. *

    * * @return The template that will produce the response text. * @param url * The URL containing the template source.. * @throws ServletException * If the request specified an invalid template source URL */ protected Template getTemplate(URL url) throws ServletException { String key = url.toString(); Template template = findCachedTemplate(key, null); // Template not cached or the source file changed - compile new template! if (template == null) { try { template = createAndStoreTemplate(key, url.openConnection().getInputStream(), null); } catch (Exception e) { throw new ServletException("Creation of template failed: " + e, e); } } return template; } /** * Initializes the servlet from hints the container passes. *

    * Delegates to sub-init methods and parses the following parameters: *

      *
    • "generatedBy" : boolean, appends "Generated by ..." to the * HTML response text generated by this servlet. *
    • *
    * * @param config Passed by the servlet container. * @throws ServletException if this method encountered difficulties * @see TemplateServlet#initTemplateEngine(ServletConfig) */ public void init(ServletConfig config) throws ServletException { super.init(config); this.engine = initTemplateEngine(config); if (engine == null) { throw new ServletException("Template engine not instantiated."); } String value = config.getInitParameter("generated.by"); if (value != null) { this.generateBy = Boolean.valueOf(value); } value = config.getInitParameter(GROOVY_SOURCE_ENCODING); if (value != null) { this.fileEncodingParamVal = value; } log("Servlet " + getClass().getName() + " initialized on " + engine.getClass()); } /** * Creates the template engine. *

    * Called by {@link TemplateServlet#init(ServletConfig)} and returns just * new groovy.text.SimpleTemplateEngine() if the init parameter * template.engine is not set by the container configuration. * * @param config Current servlet configuration passed by the container. * @return The underlying template engine or null on error. */ protected TemplateEngine initTemplateEngine(ServletConfig config) { String name = config.getInitParameter("template.engine"); if (name == null) { return new SimpleTemplateEngine(); } try { return (TemplateEngine) Class.forName(name).newInstance(); } catch (InstantiationException e) { log("Could not instantiate template engine: " + name, e); } catch (IllegalAccessException e) { log("Could not access template engine class: " + name, e); } catch (ClassNotFoundException e) { log("Could not find template engine class: " + name, e); } return null; } /** * Services the request with a response. *

    * First the request is parsed for the source file uri. If the specified file * could not be found or can not be read an error message is sent as response. *

    *

    * * @param request The http request. * @param response The http response. * @throws IOException if an input or output error occurs while the servlet is * handling the HTTP request * @throws ServletException if the HTTP request cannot be handled */ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (verbose) { log("Creating/getting cached template..."); } // // Get the template source file handle. // Template template; long getMillis; String name; File file = super.getScriptUriAsFile(request); if (file != null) { name = file.getName(); if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; // throw new IOException(file.getAbsolutePath()); } if (!file.canRead()) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read \"" + name + "\"!"); return; // throw new IOException(file.getAbsolutePath()); } getMillis = System.currentTimeMillis(); template = getTemplate(file); getMillis = System.currentTimeMillis() - getMillis; } else { name = super.getScriptUri(request); URL url = servletContext.getResource(name); getMillis = System.currentTimeMillis(); template = getTemplate(url); getMillis = System.currentTimeMillis() - getMillis; } // // Create new binding for the current request. // ServletBinding binding = new ServletBinding(request, response, servletContext); setVariables(binding); // // Prepare the response buffer content type _before_ getting the writer. // and set status code to ok // response.setContentType(CONTENT_TYPE_TEXT_HTML + "; charset=" + encoding); response.setStatus(HttpServletResponse.SC_OK); // // Get the output stream writer from the binding. // Writer out = (Writer) binding.getVariable("out"); if (out == null) { out = response.getWriter(); } // // Evaluate the template. // if (verbose) { log("Making template \"" + name + "\"..."); } // String made = template.make(binding.getVariables()).toString(); // log(" = " + made); long makeMillis = System.currentTimeMillis(); template.make(binding.getVariables()).writeTo(out); makeMillis = System.currentTimeMillis() - makeMillis; if (generateBy) { StringBuffer sb = new StringBuffer(100); sb.append("\n\n"); out.write(sb.toString()); } // // flush the response buffer. // response.flushBuffer(); if (verbose) { log("Template \"" + name + "\" request responded. [create/get=" + getMillis + " ms, make=" + makeMillis + " ms]"); } } } groovy-1.8.6/src/main/groovy/servlet/ServletBinding.java0000644001501200150120000003406311707612044022707 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.servlet; import groovy.lang.Binding; import groovy.xml.MarkupBuilder; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.runtime.MethodClosure; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * Servlet-specific binding extension to lazy load the writer or the output * stream from the response. *

    *

    Eager variables

    *
      *
    • "request" : the HttpServletRequest object
    • *
    • "response" : the HttpServletRequest object
    • *
    • "context" : the ServletContext object
    • *
    • "application" : same as context
    • *
    • "session" : shorthand for request.getSession(false) - can be null!
    • *
    • "params" : map of all form parameters - can be empty
    • *
    • "headers" : map of all request header fields
    • *
    *

    *

    Lazy variables

    *
      *
    • "out" : response.getWriter()
    • *
    • "sout" : response.getOutputStream()
    • *
    • "html" : new MarkupBuilder(response.getWriter()) - expandEmptyElements flag is set to true
    • *
    * As per the Servlet specification, a call to response.getWriter() should not be * done if a call to response.getOutputStream() has already occurred or the other way * around. You may wonder then how the above lazy variables can possibly be provided - since * setting them up would involve calling both of the above methods. The trick is catered for * behind the scenes using lazy variables. Lazy bound variables can be requested without side * effects; under the covers the writer and stream are wrapped. That means * response.getWriter() is never directly called until some output is done using * 'out' or 'html'. Once a write method call is done using either of these variable, then an attempt * to write using 'sout' will cause an IllegalStateException. Similarly, if a write method * call on 'sout' has been done already, then any further write method call on 'out' or 'html' will cause an * IllegalStateException. *

    *

    Reserved internal variable names (see "Methods" below)

    *
      *
    • "forward"
    • *
    • "include"
    • *
    • "redirect"
    • *
    *

    * If response.getWriter() is called directly (without using out), then a write method * call on 'sout' will not cause the IllegalStateException, but it will still be invalid. * It is the responsibility of the user of this class, to not to mix these different usage * styles. The same applies to calling response.getOutputStream() and using 'out' or 'html'. *

    *

    Methods

    *
      *
    • "forward(String path)" : request.getRequestDispatcher(path).forward(request, response)
    • *
    • "include(String path)" : request.getRequestDispatcher(path).include(request, response)
    • *
    • "redirect(String location)" : response.sendRedirect(location)
    • *
    *

    * * @author Guillaume Laforge * @author Christian Stein * @author Jochen Theodorou */ public class ServletBinding extends Binding { /** * A OutputStream dummy that will throw a GroovyBugError for any * write method call to it. * * @author Jochen Theodorou */ private static class InvalidOutputStream extends OutputStream { /** * Will always throw a GroovyBugError * @see java.io.OutputStream#write(int) */ public void write(int b) { throw new GroovyBugError("Any write calls to this stream are invalid!"); } } /** * A class to manage the response output stream and writer. * If the stream have been 'used', then using the writer will cause * a IllegalStateException. If the writer have been 'used', then * using the stream will cause a IllegalStateException. 'used' means * any write method has been called. Simply requesting the objects will * not cause an exception. * * @author Jochen Theodorou */ private static class ServletOutput { private HttpServletResponse response; private ServletOutputStream outputStream; private PrintWriter writer; public ServletOutput(HttpServletResponse response) { this.response = response; } private ServletOutputStream getResponseStream() throws IOException { if (writer!=null) throw new IllegalStateException("The variable 'out' or 'html' have been used already. Use either out/html or sout, not both."); if (outputStream==null) outputStream = response.getOutputStream(); return outputStream; } public ServletOutputStream getOutputStream() { return new ServletOutputStream() { public void write(int b) throws IOException { getResponseStream().write(b); } public void close() throws IOException { getResponseStream().close(); } public void flush() throws IOException { getResponseStream().flush(); } public void write(byte[] b) throws IOException { getResponseStream().write(b); } public void write(byte[] b, int off, int len) throws IOException { getResponseStream().write(b, off, len); } }; } private PrintWriter getResponseWriter() { if (outputStream!=null) throw new IllegalStateException("The variable 'sout' have been used already. Use either out/html or sout, not both."); if (writer==null) { try { writer = response.getWriter(); } catch (IOException ioe) { writer = new PrintWriter(new ByteArrayOutputStream()); throw new IllegalStateException("unable to get response writer",ioe); } } return writer; } public PrintWriter getWriter() { return new PrintWriter(new InvalidOutputStream()) { public boolean checkError() { return getResponseWriter().checkError(); } public void close() { getResponseWriter().close(); } public void flush() { getResponseWriter().flush(); } public void write(char[] buf) { getResponseWriter().write(buf); } public void write(char[] buf, int off, int len) { getResponseWriter().write(buf, off, len); } public void write(int c) { getResponseWriter().write(c); } public void write(String s, int off, int len) { getResponseWriter().write(s, off, len); } public void println() { getResponseWriter().println(); } public PrintWriter format(String format, Object... args) { getResponseWriter().format(format, args); return this; } public PrintWriter format(Locale l, String format, Object... args) { getResponseWriter().format(l, format, args); return this; } }; } } private boolean initialized; /** * Initializes a servlet binding. * * @param request the HttpServletRequest object * @param response the HttpServletRequest object * @param context the ServletContext object */ public ServletBinding(HttpServletRequest request, HttpServletResponse response, ServletContext context) { /* * Bind the default variables. */ super.setVariable("request", request); super.setVariable("response", response); super.setVariable("context", context); super.setVariable("application", context); /* * Bind the HTTP session object - if there is one. * Note: we don't create one here! */ super.setVariable("session", request.getSession(false)); /* * Bind form parameter key-value hash map. * * If there are multiple, they are passed as an array. */ Map params = collectParams(request); super.setVariable("params", params); /* * Bind request header key-value hash map. */ Map headers = new LinkedHashMap(); for (Enumeration names = request.getHeaderNames(); names.hasMoreElements();) { String headerName = (String) names.nextElement(); String headerValue = request.getHeader(headerName); headers.put(headerName, headerValue); } super.setVariable("headers", headers); } @SuppressWarnings("unchecked") private Map collectParams(HttpServletRequest request) { Map params = new LinkedHashMap(); for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) { String name = (String) names.nextElement(); if (!super.getVariables().containsKey(name)) { String[] values = request.getParameterValues(name); if (values.length == 1) { params.put(name, values[0]); } else { params.put(name, values); } } } return params; } @Override public void setVariable(String name, Object value) { lazyInit(); validateArgs(name, "Can't bind variable to"); excludeReservedName(name, "out"); excludeReservedName(name, "sout"); excludeReservedName(name, "html"); excludeReservedName(name, "forward"); excludeReservedName(name, "include"); excludeReservedName(name, "redirect"); super.setVariable(name, value); } @Override public Map getVariables() { lazyInit(); return super.getVariables(); } /** * @return a writer, an output stream, a markup builder or another requested object */ @Override public Object getVariable(String name) { lazyInit(); validateArgs(name, "No variable with"); return super.getVariable(name); } private void lazyInit() { if (initialized) return; initialized = true; HttpServletResponse response = (HttpServletResponse) super.getVariable("response"); ServletOutput output = new ServletOutput(response); super.setVariable("out", output.getWriter()); super.setVariable("sout", output.getOutputStream()); MarkupBuilder builder = new MarkupBuilder(output.getWriter()); builder.setExpandEmptyElements(true); super.setVariable("html", builder); // bind forward method MethodClosure c = new MethodClosure(this, "forward"); super.setVariable("forward", c); // bind include method c = new MethodClosure(this, "include"); super.setVariable("include", c); // bind redirect method c = new MethodClosure(this, "redirect"); super.setVariable("redirect", c); } private void validateArgs(String name, String message) { if (name == null) { throw new IllegalArgumentException(message + " null key."); } if (name.length() == 0) { throw new IllegalArgumentException(message + " blank key name. [length=0]"); } } private void excludeReservedName(String name, String reservedName) { if (reservedName.equals(name)) { throw new IllegalArgumentException("Can't bind variable to key named '" + name + "'."); } } public void forward(String path) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) super.getVariable("request"); HttpServletResponse response = (HttpServletResponse) super.getVariable("response"); RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } public void include(String path) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) super.getVariable("request"); HttpServletResponse response = (HttpServletResponse) super.getVariable("response"); RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.include(request, response); } public void redirect(String location) throws IOException { HttpServletResponse response = (HttpServletResponse) super.getVariable("response"); response.sendRedirect(location); } } groovy-1.8.6/src/main/groovy/beans/0000755001501200150120000000000011713766062016532 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/beans/PropertyReader.java0000644001501200150120000000137511707612044022343 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; /** * @author Andres Almiray */ public interface PropertyReader { Object read(Object owner, String propertyName); }groovy-1.8.6/src/main/groovy/beans/ListenerListASTTransformation.groovy0000644001501200150120000004020411707612044025712 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.control.messages.SyntaxErrorMessage import org.codehaus.groovy.syntax.SyntaxException import org.codehaus.groovy.syntax.Token import org.codehaus.groovy.syntax.Types import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.transform.GroovyASTTransformation import org.objectweb.asm.Opcodes import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.* import org.codehaus.groovy.ast.stmt.* /** * Handles generation of code for the {@code @ListenerList} annotation. *

    * Generally, it adds the needed add<Listener>, remove<Listener> and * get<Listener>s methods to support the Java Beans API. *

    * Additionally it adds corresponding fire<Event> methods. *

    * * @author Alexander Klein * @author Hamlet D'Arcy */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) class ListenerListASTTransformation implements ASTTransformation, Opcodes { private static final Class MY_CLASS = groovy.beans.ListenerList.class private static final ClassNode COLLECTION_TYPE = ClassHelper.make(Collection) public void visit(ASTNode[] nodes, SourceUnit source) { if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: wrong types: ${node.class} / ${parent.class}") } AnnotationNode node = nodes[0] FieldNode field = nodes[1] ClassNode declaringClass = nodes[1].declaringClass ClassNode parentClass = field.type boolean isCollection = parentClass.isDerivedFrom(COLLECTION_TYPE) || parentClass.implementsInterface(COLLECTION_TYPE) if (!isCollection) { addError(node, source, '@' + MY_CLASS.name + ' can only annotate collection properties.') return } def types = field.type.genericsTypes if (!types) { addError(node, source, '@' + MY_CLASS.name + ' fields must have a generic type.') return } if (types[0].wildcard) { addError(node, source, '@' + MY_CLASS.name + ' fields with generic wildcards not yet supported.') return } def listener = types[0].type if (!field.initialValueExpression) { field.initialValueExpression = new ListExpression() } def name = node.getMember('name')?.value ?: listener.nameWithoutPackage def fireList = listener.methods.findAll { MethodNode m -> m.isPublic() && !m.isSynthetic() && !m.isStatic() } def synchronize = node.getMember('synchronize')?.value ?: false addAddListener(source, node, declaringClass, field, listener, name, synchronize) addRemoveListener(source, node, declaringClass, field, listener, name, synchronize) addGetListeners(source, node, declaringClass, field, listener, name, synchronize) fireList.each { MethodNode method -> addFireMethods(source, node, declaringClass, field, types, synchronize, method) } } private static def addError(AnnotationNode node, SourceUnit source, String message) { source.errorCollector.addError( new SyntaxErrorMessage(new SyntaxException( message, node.lineNumber, node.columnNumber), source)) } /** * Adds the add<Listener> method like: *

    *

         * synchronized void add${name.capitalize}(${listener.name} listener) {
         *     if (listener == null)
         *         return
         *     if (${field.name} == null)
         *        ${field.name} = []
         *     ${field.name}.add(listener)
         * }
         * 
    */ void addAddListener(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field, ClassNode listener, String name, synchronize) { def methodModifiers = synchronize ? ACC_PUBLIC | ACC_SYNCHRONIZED : ACC_PUBLIC def methodReturnType = ClassHelper.make(Void.TYPE) def methodName = "add${name.capitalize()}" def cn = ClassHelper.makeWithoutCaching(listener.name) cn.redirect = listener def methodParameter = [new Parameter(cn,'listener')] as Parameter[] if (declaringClass.hasMethod(methodName, methodParameter)) { addError node, source, "Conflict using @${MY_CLASS.name}. Class $declaringClass.name already has method $methodName" return } BlockStatement block = new BlockStatement() block.addStatements([ new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression('listener'), Token.newSymbol(Types.COMPARE_EQUAL, 0, 0), ConstantExpression.NULL ) ), new ReturnStatement(ConstantExpression.NULL), new EmptyStatement() ), new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.COMPARE_EQUAL, 0, 0), ConstantExpression.NULL ) ), new ExpressionStatement( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.EQUAL, 0, 0), new ListExpression() ) ), new EmptyStatement() ), new ExpressionStatement( new MethodCallExpression(new VariableExpression(field.name), new ConstantExpression('add'), new ArgumentListExpression(new VariableExpression('listener'))) ) ]) declaringClass.addMethod(new MethodNode(methodName, methodModifiers, methodReturnType, methodParameter, [] as ClassNode[], block)) } /** * Adds the remove method like: *

    *

         * synchronized void remove${name.capitalize}(${listener.name} listener) {
         *     if (listener == null)
         *         return
         *     if (${field.name} == null)
         *         ${field.name} = []
         *     ${field.name}.remove(listener)
         * }
         * 
    */ void addRemoveListener(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field, ClassNode listener, String name, synchronize) { def methodModifiers = synchronize ? ACC_PUBLIC | ACC_SYNCHRONIZED : ACC_PUBLIC def methodReturnType = ClassHelper.make(Void.TYPE) def methodName = "remove${name.capitalize()}" def cn = ClassHelper.makeWithoutCaching(listener.name) cn.redirect = listener def methodParameter = [new Parameter(cn,'listener')] as Parameter[] if (declaringClass.hasMethod(methodName, methodParameter)) { addError node, source, "Conflict using @${MY_CLASS.name}. Class $declaringClass.name already has method $methodName" return } BlockStatement block = new BlockStatement() block.addStatements([ new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression('listener'), Token.newSymbol(Types.COMPARE_EQUAL, 0, 0), ConstantExpression.NULL ) ), new ReturnStatement(ConstantExpression.NULL), new EmptyStatement() ), new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.COMPARE_EQUAL, 0, 0), ConstantExpression.NULL ) ), new ExpressionStatement( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.EQUAL, 0, 0), new ListExpression() ) ), new EmptyStatement() ), new ExpressionStatement( new MethodCallExpression(new VariableExpression(field.name), new ConstantExpression('remove'), new ArgumentListExpression(new VariableExpression("listener"))) ) ]) declaringClass.addMethod(new MethodNode(methodName, methodModifiers, methodReturnType, methodParameter, [] as ClassNode[], block)) } /** * Adds the get<Listener>s method like: *

    *

         * synchronized ${name.capitalize}[] get${name.capitalize}s() {
         *     def __result = []
         *     if (${field.name} != null)
         *         __result.addAll(${field.name})
         *     return __result as ${name.capitalize}[]
         * }
         * 
    */ void addGetListeners(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field, ClassNode listener, String name, synchronize) { def methodModifiers = synchronize ? ACC_PUBLIC | ACC_SYNCHRONIZED : ACC_PUBLIC def methodReturnType = listener.makeArray() def methodName = "get${name.capitalize()}s" def methodParameter = [] as Parameter[] if (declaringClass.hasMethod(methodName, methodParameter)) { addError node, source, "Conflict using @${MY_CLASS.name}. Class $declaringClass.name already has method $methodName" return } BlockStatement block = new BlockStatement() block.addStatements([ new ExpressionStatement( new DeclarationExpression( new VariableExpression("__result", ClassHelper.DYNAMIC_TYPE), Token.newSymbol(Types.EQUALS, 0, 0), new ListExpression() )), new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.COMPARE_NOT_EQUAL, 0, 0), ConstantExpression.NULL ) ), new ExpressionStatement( new MethodCallExpression(new VariableExpression('__result'), new ConstantExpression('addAll'), new ArgumentListExpression(new VariableExpression(field.name))) ), new EmptyStatement() ), new ReturnStatement( new CastExpression( methodReturnType, new VariableExpression('__result') ) ) ]) declaringClass.addMethod(new MethodNode(methodName, methodModifiers, methodReturnType, methodParameter, [] as ClassNode[], block)) } /** * Adds the fire<Event> methods like: *

    *

         * void fire${fireMethod.capitalize()}(${parameterList.join(', ')}) {
         *     if (${field.name} != null) {
         *         def __list = new ArrayList(${field.name})
         *         __list.each { listener ->
         *             listener.$eventMethod(${evt})
         *         }
         *     }
         * }
         * 
    */ void addFireMethods(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field, GenericsType[] types, boolean synchronize, MethodNode method) { def methodReturnType = ClassHelper.make(Void.TYPE) def methodName = "fire${method.name.capitalize()}" def methodModifiers = synchronize ? ACC_PUBLIC | ACC_SYNCHRONIZED : ACC_PUBLIC if (declaringClass.hasMethod(methodName, method.parameters)) { addError node, source, "Conflict using @${MY_CLASS.name}. Class $declaringClass.name already has method $methodName" return } def args = new ArgumentListExpression(method.parameters) BlockStatement block = new BlockStatement() def listenerListType = ClassHelper.make(ArrayList) listenerListType.setGenericsTypes(types) block.addStatements([ new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression(field.name), Token.newSymbol(Types.COMPARE_NOT_EQUAL, 0, 0), ConstantExpression.NULL ) ), new BlockStatement([ new ExpressionStatement( new DeclarationExpression( new VariableExpression('__list', listenerListType), Token.newSymbol(Types.EQUALS, 0, 0), new ConstructorCallExpression(listenerListType, new ArgumentListExpression( new VariableExpression(field.name) )) ) ), new ForStatement( new Parameter(ClassHelper.DYNAMIC_TYPE, 'listener'), new VariableExpression('__list'), new BlockStatement([ new ExpressionStatement( new MethodCallExpression( new VariableExpression('listener'), method.name, args ) ) ], new VariableScope()) ) ], new VariableScope()), new EmptyStatement() ) ]) def params = method.parameters.collect { def paramType = ClassHelper.getWrapper(it.type) def cn = ClassHelper.makeWithoutCaching(paramType.name) cn.setRedirect(paramType) new Parameter(cn, it.name) } declaringClass.addMethod(methodName, methodModifiers, methodReturnType, params as Parameter[], [] as ClassNode[], block) } } groovy-1.8.6/src/main/groovy/beans/DefaultPropertyWriter.java0000644001501200150120000000177011707612044023721 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.runtime.InvokerHelper; /** * @author Andres Almiray */ public class DefaultPropertyWriter implements PropertyWriter { public static final PropertyWriter INSTANCE = new DefaultPropertyWriter(); public void write(Object owner, String propertyName, Object value) { InvokerHelper.setProperty(owner, propertyName, value); } } groovy-1.8.6/src/main/groovy/beans/ListenerList.groovy0000644001501200150120000001067611707612044022425 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import org.codehaus.groovy.transform.GroovyASTTransformationClass /** * This annotation adds Java-style listener support to a class based on an annotated Collection-property.

    * * For any given Collection property, several methods will be written into the enclosing class during the compile phase. These * changes are visible from Java or other languages. The List is intended to hold listeners of some sort, and the methods * addListener, removeListener, and getListeners are all added to the class. The actual methods names depend on the generic * type of the collection. * * Given the following example:
    *
     * class MyClass {
     *     @groovy.beans.ListenerList
     *     List<java.awt.event.ActionListener> listeners
     * }
     * 
    * The following code is generated: *
     * public class MyClass extends java.lang.Object {
     *
     *     @groovy.beans.ListenerList
     *     private java.util.List<java.awt.event.ActionListener> listeners
     *
     *     public void addActionListener(java.awt.event.ActionListener listener) {
     *         if ( listener == null) {
     *             return null
     *         }
     *         if ( listeners == null) {
     *             listeners = []
     *         }
     *         listeners.add(listener)
     *     }
     *
     *     public void removeActionListener(java.awt.event.ActionListener listener) {
     *         if ( listener == null) {
     *             return null
     *         }
     *         if ( listeners == null) {
     *             listeners = []
     *         }
     *         listeners.remove(listener)
     *     }
     *
     *     public java.awt.event.ActionListener[] getActionListeners() {
     *         java.lang.Object __result = []
     *         if ( listeners != null) {
     *             __result.addAll(listeners)
     *         }
     *         return (( __result ) as java.awt.event.ActionListener[])
     *     }
     *
     *     public void fireActionPerformed(java.awt.event.ActionEvent param0) {
     *         if ( listeners != null) {
     *             def __list = new java.util.ArrayList(listeners)
     *             for (java.lang.Object listener : __list ) {
     *                 listener.actionPerformed(param0)
     *             }
     *         }
     *     }
     * }
     * 
    * A fire method is created for each public method in the target class. In this case, ActionListener only has one * method. For a four method interface, four fire methods would be created.

    * * The annotation can take the following parameters: *
     * name        = a suffix for creating the add, remove, and get methods.
     *               Default: Name of the listener type
     *               In the above example, if name is set to MyListener, then the class will have an addMyListener,
     *               removeMyListener, and getMyListeners methods. 
     *
     * synchronize = Whether or not the methods created should be synchronized at the method level. 
     *               Default: false
     * 
    * * Compilation Errors - Using this annotation incorrectly results in compilation errors rather * than runtime errors. A list of potential problems includes: *
      *
    • This annotation can only be applied to a field of type Collection
    • *
    • The annotated Collection field must have a generic type
    • *
    • The annotated Collection field must not have a generic wildcard declared
    • *
    • The generated methods must not already exist
    • *
    * @see ListenerListASTTransformation * * @author Alexander Klein * @author Hamlet D'Arcy */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target(ElementType.FIELD) @GroovyASTTransformationClass('groovy.beans.ListenerListASTTransformation') @interface ListenerList { String name() default "" boolean synchronize() default false } groovy-1.8.6/src/main/groovy/beans/VetoableASTTransformation.java0000644001501200150120000006076011707612044024437 0ustar miguelmiguel/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.objectweb.asm.Opcodes; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; /** * Handles generation of code for the {@code @Vetoable} annotation, and {@code @Bindable} * if also present. *

    * Generally, it adds (if needed) a VetoableChangeSupport field and * the needed add/removeVetoableChangeListener methods to support the * listeners. *

    * It also generates the setter and wires the setter through the * VetoableChangeSupport. *

    * If a {@link Bindable} annotation is detected it also adds support similar * to what {@link BindableASTTransformation} would do. * * @author Danno Ferrin (shemnon) * @author Chris Reeves */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class VetoableASTTransformation extends BindableASTTransformation { protected static ClassNode constrainedClassNode = ClassHelper.make(Vetoable.class); protected ClassNode vcsClassNode = ClassHelper.make(VetoableChangeSupport.class); /** * Convenience method to see if an annotated node is {@code @Vetoable}. * * @param node the node to check * @return true if the node is constrained */ public static boolean hasVetoableAnnotation(AnnotatedNode node) { for (AnnotationNode annotation : node.getAnnotations()) { if (constrainedClassNode.equals(annotation.getClassNode())) { return true; } } return false; } /** * Handles the bulk of the processing, mostly delegating to other methods. * * @param nodes the AST nodes * @param source the source unit for the nodes */ public void visit(ASTNode[] nodes, SourceUnit source) { if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class"); } AnnotationNode node = (AnnotationNode) nodes[0]; if (nodes[1] instanceof ClassNode) { addListenerToClass(source, node, (ClassNode) nodes[1]); } else { if ((((FieldNode)nodes[1]).getModifiers() & Opcodes.ACC_FINAL) != 0) { source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Vetoable cannot annotate a final property.", node.getLineNumber(), node.getColumnNumber()), source)); } addListenerToProperty(source, node, (AnnotatedNode) nodes[1]); } } private void addListenerToProperty(SourceUnit source, AnnotationNode node, AnnotatedNode parent) { ClassNode declaringClass = parent.getDeclaringClass(); FieldNode field = ((FieldNode) parent); String fieldName = field.getName(); for (PropertyNode propertyNode : declaringClass.getProperties()) { boolean bindable = BindableASTTransformation.hasBindableAnnotation(parent) || BindableASTTransformation.hasBindableAnnotation(parent.getDeclaringClass()); if (propertyNode.getName().equals(fieldName)) { if (field.isStatic()) { //noinspection ThrowableInstanceNeverThrown source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Vetoable cannot annotate a static property.", node.getLineNumber(), node.getColumnNumber()), source)); } else { createListenerSetter(source, node, bindable, declaringClass, propertyNode); } return; } } //noinspection ThrowableInstanceNeverThrown source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Vetoable must be on a property, not a field. Try removing the private, protected, or public modifier.", node.getLineNumber(), node.getColumnNumber()), source)); } private void addListenerToClass(SourceUnit source, AnnotationNode node, ClassNode classNode) { boolean bindable = BindableASTTransformation.hasBindableAnnotation(classNode); for (PropertyNode propertyNode : classNode.getProperties()) { if (!hasVetoableAnnotation(propertyNode.getField()) && !((propertyNode.getField().getModifiers() & Opcodes.ACC_FINAL) != 0) && !propertyNode.getField().isStatic()) { createListenerSetter(source, node, bindable || BindableASTTransformation.hasBindableAnnotation(propertyNode.getField()), classNode, propertyNode); } } } /** * Wrap an existing setter. */ private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) { String getterName = "get" + MetaClassHelper.capitalize(propertyName); MethodNode setter = classNode.getSetterMethod("set" + MetaClassHelper.capitalize(propertyName)); if (setter != null) { // Get the existing code block Statement code = setter.getCode(); VariableExpression oldValue = new VariableExpression("$oldValue"); VariableExpression newValue = new VariableExpression("$newValue"); VariableExpression proposedValue = new VariableExpression(setter.getParameters()[0].getName()); BlockStatement block = new BlockStatement(); // create a local variable to hold the old value from the getter block.addStatement(new ExpressionStatement( new DeclarationExpression(oldValue, Token.newSymbol(Types.EQUALS, 0, 0), new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, ArgumentListExpression.EMPTY_ARGUMENTS)))); // add the fireVetoableChange method call block.addStatement(new ExpressionStatement(new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "fireVetoableChange", new ArgumentListExpression( new Expression[]{ new ConstantExpression(propertyName), oldValue, proposedValue})))); // call the existing block, which will presumably set the value properly block.addStatement(code); if (bindable) { // get the new value to emit in the event block.addStatement(new ExpressionStatement( new DeclarationExpression(newValue, Token.newSymbol(Types.EQUALS, 0, 0), new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, ArgumentListExpression.EMPTY_ARGUMENTS)))); // add the firePropertyChange method call block.addStatement(new ExpressionStatement(new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "firePropertyChange", new ArgumentListExpression( new Expression[]{ new ConstantExpression(propertyName), oldValue, newValue})))); } // replace the existing code block with our new one setter.setCode(block); } } private void createListenerSetter(SourceUnit source, AnnotationNode node, boolean bindable, ClassNode declaringClass, PropertyNode propertyNode) { if (bindable && needsPropertyChangeSupport(declaringClass, source)) { addPropertyChangeSupport(declaringClass); } if (needsVetoableChangeSupport(declaringClass, source)) { addVetoableChangeSupport(declaringClass); } String setterName = "set" + MetaClassHelper.capitalize(propertyNode.getName()); if (declaringClass.getMethods(setterName).isEmpty()) { Expression fieldExpression = new FieldExpression(propertyNode.getField()); BlockStatement setterBlock = new BlockStatement(); setterBlock.addStatement(createConstrainedStatement(propertyNode, fieldExpression)); if (bindable) { setterBlock.addStatement(createBindableStatement(propertyNode, fieldExpression)); } else { setterBlock.addStatement(createSetStatement(fieldExpression)); } // create method void ( fieldName) createSetterMethod(declaringClass, propertyNode, setterName, setterBlock); } else { wrapSetterMethod(declaringClass, bindable, propertyNode.getName()); } } /** * Creates a statement body similar to: * this.fireVetoableChange("field", field, field = value) * * @param propertyNode the field node for the property * @param fieldExpression a field expression for setting the property value * @return the created statement */ protected Statement createConstrainedStatement(PropertyNode propertyNode, Expression fieldExpression) { return new ExpressionStatement( new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "fireVetoableChange", new ArgumentListExpression( new Expression[]{ new ConstantExpression(propertyNode.getName()), fieldExpression, new VariableExpression("value")}))); } /** * Creates a statement body similar to: * field = value. *

    * Used when the field is not also @Bindable * * @param fieldExpression a field expression for setting the property value * @return the created statement */ protected Statement createSetStatement(Expression fieldExpression) { return new ExpressionStatement( new BinaryExpression( fieldExpression, Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("value"))); } /** * Snoops through the declaring class and all parents looking for a field * of type VetoableChangeSupport. Remembers the field and returns false * if found otherwise returns true to indicate that such support should * be added. * * @param declaringClass the class to search * @return true if vetoable change support should be added */ protected boolean needsVetoableChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) { boolean foundAdd = false, foundRemove = false, foundFire = false; ClassNode consideredClass = declaringClass; while (consideredClass!= null) { for (MethodNode method : consideredClass.getMethods()) { // just check length, MOP will match it up foundAdd = foundAdd || method.getName().equals("addVetoableChangeListener") && method.getParameters().length == 1; foundRemove = foundRemove || method.getName().equals("removeVetoableChangeListener") && method.getParameters().length == 1; foundFire = foundFire || method.getName().equals("fireVetoableChange") && method.getParameters().length == 3; if (foundAdd && foundRemove && foundFire) { return false; } } consideredClass = consideredClass.getSuperClass(); } // check if a super class has @Vetoable annotations consideredClass = declaringClass.getSuperClass(); while (consideredClass!=null) { if (hasVetoableAnnotation(consideredClass)) return false; for (FieldNode field : consideredClass.getFields()) { if (hasVetoableAnnotation(field)) return false; } consideredClass = consideredClass.getSuperClass(); } if (foundAdd || foundRemove || foundFire) { sourceUnit.getErrorCollector().addErrorAndContinue( new SimpleMessage("@Vetoable cannot be processed on " + declaringClass.getName() + " because some but not all of addVetoableChangeListener, removeVetoableChange, and fireVetoableChange were declared in the current or super classes.", sourceUnit) ); return false; } return true; } /** * Creates a setter method with the given body. *

    * This differs from normal setters in that we need to add a declared * exception java.beans.PropertyVetoException * * @param declaringClass the class to which we will add the setter * @param propertyNode the field to back the setter * @param setterName the name of the setter * @param setterBlock the statement representing the setter block */ protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) { Parameter[] setterParameterTypes = {new Parameter(propertyNode.getType(), "value")}; ClassNode[] exceptions = {ClassHelper.make(PropertyVetoException.class)}; MethodNode setter = new MethodNode(setterName, propertyNode.getModifiers(), ClassHelper.VOID_TYPE, setterParameterTypes, exceptions, setterBlock); setter.setSynthetic(true); // add it to the class declaringClass.addMethod(setter); } /** * Adds the necessary field and methods to support vetoable change support. *

    * Adds a new field: * "protected final java.beans.VetoableChangeSupport this$vetoableChangeSupport = new java.beans.VetoableChangeSupport(this)" *

    * Also adds support methods: * public void addVetoableChangeListener(java.beans.VetoableChangeListener) * public void addVetoableChangeListener(String, java.beans.VetoableChangeListener) * public void removeVetoableChangeListener(java.beans.VetoableChangeListener) * public void removeVetoableChangeListener(String, java.beans.VetoableChangeListener) * public java.beans.VetoableChangeListener[] getVetoableChangeListeners() * * @param declaringClass the class to which we add the support field and methods */ protected void addVetoableChangeSupport(ClassNode declaringClass) { ClassNode vcsClassNode = ClassHelper.make(VetoableChangeSupport.class); ClassNode vclClassNode = ClassHelper.make(VetoableChangeListener.class); // add field: // protected static VetoableChangeSupport this$vetoableChangeSupport = new java.beans.VetoableChangeSupport(this) FieldNode vcsField = declaringClass.addField( "this$vetoableChangeSupport", ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, vcsClassNode, new ConstructorCallExpression(vcsClassNode, new ArgumentListExpression(new Expression[]{new VariableExpression("this")}))); // add method: // void addVetoableChangeListener(listener) { // this$vetoableChangeSupport.addVetoableChangeListener(listener) // } declaringClass.addMethod( new MethodNode( "addVetoableChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(vclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "addVetoableChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("listener")}))))); // add method: // void addVetoableChangeListener(name, listener) { // this$vetoableChangeSupport.addVetoableChangeListener(name, listener) // } declaringClass.addMethod( new MethodNode( "addVetoableChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(vclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "addVetoableChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("name"), new VariableExpression("listener")}))))); // add method: // boolean removeVetoableChangeListener(listener) { // return this$vetoableChangeSupport.removeVetoableChangeListener(listener); // } declaringClass.addMethod( new MethodNode( "removeVetoableChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(vclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "removeVetoableChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("listener")}))))); // add method: void removeVetoableChangeListener(name, listener) declaringClass.addMethod( new MethodNode( "removeVetoableChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(vclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "removeVetoableChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("name"), new VariableExpression("listener")}))))); // add method: // void fireVetoableChange(String name, Object oldValue, Object newValue) // throws PropertyVetoException // { // this$vetoableChangeSupport.fireVetoableChange(name, oldValue, newValue) // } declaringClass.addMethod( new MethodNode( "fireVetoableChange", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "oldValue"), new Parameter(ClassHelper.OBJECT_TYPE, "newValue")}, new ClassNode[] {ClassHelper.make(PropertyVetoException.class)}, new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "fireVetoableChange", new ArgumentListExpression( new Expression[]{ new VariableExpression("name"), new VariableExpression("oldValue"), new VariableExpression("newValue")}))))); // add method: // VetoableChangeListener[] getVetoableChangeListeners() { // return this$vetoableChangeSupport.getVetoableChangeListeners // } declaringClass.addMethod( new MethodNode( "getVetoableChangeListeners", ACC_PUBLIC | ACC_SYNTHETIC, vclClassNode.makeArray(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement( new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "getVetoableChangeListeners", ArgumentListExpression.EMPTY_ARGUMENTS))))); // add method: // VetoableChangeListener[] getVetoableChangeListeners(String name) { // return this$vetoableChangeSupport.getVetoableChangeListeners(name) // } declaringClass.addMethod( new MethodNode( "getVetoableChangeListeners", ACC_PUBLIC | ACC_SYNTHETIC, vclClassNode.makeArray(), new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name")}, ClassNode.EMPTY_ARRAY, new ReturnStatement( new ExpressionStatement( new MethodCallExpression( new FieldExpression(vcsField), "getVetoableChangeListeners", new ArgumentListExpression( new Expression[]{new VariableExpression("name")})))))); } } groovy-1.8.6/src/main/groovy/beans/Bindable.java0000644001501200150120000001056411707612044021074 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates a groovy property or a class. * * When annotating a property it indicates that the property should be a * bound property according to the JavaBeans spec, announcing to listeners * that the value has changed.

    * * When annotating a class it indicates that all groovy properties in that * class should be bound as though each property had the annotation (even * if it already has it explicitly).

    * * It is a compilation error to place this annotation on a field (that is * not a property, i.e. has scope visibility modifiers).

    * * If a property with a user defined setter method is annotated the code * block is wrapped with the needed code to fire off the event.

    * * The following example shows how you can use this annotation on fields * of a class: *

     * class Person {
     *    @groovy.beans.Bindable
     *    String firstName
     *
     *    @groovy.beans.Bindable
     *    def zipCode
     * }
     * 
    * The above example will generate code that is similar to the next snippet. * Notice the difference between a String property and a def/Object property: *
     * public class Person { 
     * 
     *     @groovy.beans.Bindable
     *     private java.lang.String firstName 
     *     @groovy.beans.Bindable
     *     private java.lang.Object zipCode 
     *     final private java.beans.PropertyChangeSupport this$propertyChangeSupport 
     * 
     *     public Person() {
     *         this$propertyChangeSupport = new java.beans.PropertyChangeSupport(this)
     *     }
     * 
     *     public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) {
     *         this$propertyChangeSupport.addPropertyChangeListener(listener)
     *     }
     * 
     *     public void addPropertyChangeListener(java.lang.String name, java.beans.PropertyChangeListener listener) {
     *         this$propertyChangeSupport.addPropertyChangeListener(name, listener)
     *     }
     * 
     *     public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) {
     *         this$propertyChangeSupport.removePropertyChangeListener(listener)
     *     }
     * 
     *     public void removePropertyChangeListener(java.lang.String name, java.beans.PropertyChangeListener listener) {
     *         this$propertyChangeSupport.removePropertyChangeListener(name, listener)
     *     }
     * 
     *     public void firePropertyChange(java.lang.String name, java.lang.Object oldValue, java.lang.Object newValue) {
     *         this$propertyChangeSupport.firePropertyChange(name, oldValue, newValue)
     *     }
     * 
     *     public java.beans.PropertyChangeListener[] getPropertyChangeListeners() {
     *         return this$propertyChangeSupport.getPropertyChangeListeners()
     *     }
     * 
     *     public java.beans.PropertyChangeListener[] getPropertyChangeListeners(java.lang.String name) {
     *         return this$propertyChangeSupport.getPropertyChangeListeners(name)
     *     }
     * 
     *     public void setFirstName(java.lang.String value) {
     *         this.firePropertyChange('firstName', firstName, firstName = value )
     *     }
     * 
     *     public void setZipCode(java.lang.Object value) {
     *         this.firePropertyChange('zipCode', zipCode, zipCode = value )
     *     }
     * }
     * 
    * @see BindableASTTransformation * @author Danno Ferrin (shemnon) */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD, ElementType.TYPE}) @GroovyASTTransformationClass("groovy.beans.BindableASTTransformation") public @interface Bindable { } groovy-1.8.6/src/main/groovy/beans/DefaultPropertyAccessor.java0000644001501200150120000000214311707612044024202 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; /** * @author Andres Almiray */ public class DefaultPropertyAccessor implements PropertyAccessor { public static final PropertyAccessor INSTANCE = new DefaultPropertyAccessor(); public Object read(Object owner, String propertyName) { return DefaultPropertyReader.INSTANCE.read(owner, propertyName); } public void write(Object owner, String propertyName, Object value) { DefaultPropertyWriter.INSTANCE.write(owner, propertyName, value); } }groovy-1.8.6/src/main/groovy/beans/BindableASTTransformation.java0000644001501200150120000005712511713766062024406 0ustar miguelmiguel/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.objectweb.asm.Opcodes; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * Handles generation of code for the {@code @Bindable} annotation when {@code @Vetoable} * is not present. *

    * Generally, it adds (if needed) a PropertyChangeSupport field and * the needed add/removePropertyChangeListener methods to support the * listeners. *

    * It also generates the setter and wires the setter through the * PropertyChangeSupport. *

    * If a {@link Vetoable} annotation is detected it does nothing and * lets the {@link VetoableASTTransformation} handle all the changes. * * @author Danno Ferrin (shemnon) * @author Chris Reeves */ @GroovyASTTransformation(phase= CompilePhase.CANONICALIZATION) public class BindableASTTransformation implements ASTTransformation, Opcodes { protected static ClassNode boundClassNode = ClassHelper.make(Bindable.class); protected ClassNode pcsClassNode = ClassHelper.make(PropertyChangeSupport.class); /** * Convenience method to see if an annotated node is {@code @Bindable}. * * @param node the node to check * @return true if the node is bindable */ public static boolean hasBindableAnnotation(AnnotatedNode node) { for (AnnotationNode annotation : node.getAnnotations()) { if (boundClassNode.equals(annotation.getClassNode())) { return true; } } return false; } /** * Handles the bulk of the processing, mostly delegating to other methods. * * @param nodes the ast nodes * @param source the source unit for the nodes */ public void visit(ASTNode[] nodes, SourceUnit source) { if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class"); } AnnotationNode node = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (VetoableASTTransformation.hasVetoableAnnotation(parent)) { // VetoableASTTransformation will handle both @Bindable and @Vetoable return; } ClassNode declaringClass = parent.getDeclaringClass(); if (parent instanceof FieldNode) { if ((((FieldNode)parent).getModifiers() & Opcodes.ACC_FINAL) != 0) { source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Bindable cannot annotate a final property.", node.getLineNumber(), node.getColumnNumber()), source)); } if (VetoableASTTransformation.hasVetoableAnnotation(parent.getDeclaringClass())) { // VetoableASTTransformation will handle both @Bindable and @Vetoable return; } addListenerToProperty(source, node, declaringClass, (FieldNode) parent); } else if (parent instanceof ClassNode) { addListenerToClass(source, node, (ClassNode) parent); } } private void addListenerToProperty(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field) { String fieldName = field.getName(); for (PropertyNode propertyNode : declaringClass.getProperties()) { if (propertyNode.getName().equals(fieldName)) { if (field.isStatic()) { //noinspection ThrowableInstanceNeverThrown source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Bindable cannot annotate a static property.", node.getLineNumber(), node.getColumnNumber()), source)); } else { if (needsPropertyChangeSupport(declaringClass, source)) { addPropertyChangeSupport(declaringClass); } createListenerSetter(source, node, declaringClass, propertyNode); } return; } } //noinspection ThrowableInstanceNeverThrown source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.beans.Bindable must be on a property, not a field. Try removing the private, protected, or public modifier.", node.getLineNumber(), node.getColumnNumber()), source)); } private void addListenerToClass(SourceUnit source, AnnotationNode node, ClassNode classNode) { if (needsPropertyChangeSupport(classNode, source)) { addPropertyChangeSupport(classNode); } for (PropertyNode propertyNode : classNode.getProperties()) { FieldNode field = propertyNode.getField(); // look to see if per-field handlers will catch this one... if (hasBindableAnnotation(field) || ((field.getModifiers() & Opcodes.ACC_FINAL) != 0) || field.isStatic() || VetoableASTTransformation.hasVetoableAnnotation(field)) { // explicitly labeled properties are already handled, // don't transform final properties // don't transform static properties // VetoableASTTransformation will handle both @Bindable and @Vetoable continue; } createListenerSetter(source, node, classNode, propertyNode); } } /* * Wrap an existing setter. */ private void wrapSetterMethod(ClassNode classNode, String propertyName) { String getterName = "get" + MetaClassHelper.capitalize(propertyName); MethodNode setter = classNode.getSetterMethod("set" + MetaClassHelper.capitalize(propertyName)); if (setter != null) { // Get the existing code block Statement code = setter.getCode(); VariableExpression oldValue = new VariableExpression("$oldValue"); VariableExpression newValue = new VariableExpression("$newValue"); BlockStatement block = new BlockStatement(); // create a local variable to hold the old value from the getter block.addStatement(new ExpressionStatement( new DeclarationExpression(oldValue, Token.newSymbol(Types.EQUALS, 0, 0), new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, ArgumentListExpression.EMPTY_ARGUMENTS)))); // call the existing block, which will presumably set the value properly block.addStatement(code); // get the new value to emit in the event block.addStatement(new ExpressionStatement( new DeclarationExpression(newValue, Token.newSymbol(Types.EQUALS, 0, 0), new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, ArgumentListExpression.EMPTY_ARGUMENTS)))); // add the firePropertyChange method call block.addStatement(new ExpressionStatement(new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "firePropertyChange", new ArgumentListExpression( new Expression[]{ new ConstantExpression(propertyName), oldValue, newValue})))); // replace the existing code block with our new one setter.setCode(block); } } private void createListenerSetter(SourceUnit source, AnnotationNode node, ClassNode classNode, PropertyNode propertyNode) { String setterName = "set" + MetaClassHelper.capitalize(propertyNode.getName()); if (classNode.getMethods(setterName).isEmpty()) { Expression fieldExpression = new FieldExpression(propertyNode.getField()); Statement setterBlock = createBindableStatement(propertyNode, fieldExpression); // create method void ( fieldName) createSetterMethod(classNode, propertyNode, setterName, setterBlock); } else { wrapSetterMethod(classNode, propertyNode.getName()); } } /** * Creates a statement body similar to: * this.firePropertyChange("field", field, field = value) * * @param propertyNode the field node for the property * @param fieldExpression a field expression for setting the property value * @return the created statement */ protected Statement createBindableStatement(PropertyNode propertyNode, Expression fieldExpression) { // create statementBody return new ExpressionStatement( new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "firePropertyChange", new ArgumentListExpression( new Expression[]{ new ConstantExpression(propertyNode.getName()), fieldExpression, new BinaryExpression( fieldExpression, Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("value"))}))); } /** * Creates a setter method with the given body. * * @param declaringClass the class to which we will add the setter * @param propertyNode the field to back the setter * @param setterName the name of the setter * @param setterBlock the statement representing the setter block */ protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) { Parameter[] setterParameterTypes = {new Parameter(propertyNode.getType(), "value")}; MethodNode setter = new MethodNode(setterName, propertyNode.getModifiers(), ClassHelper.VOID_TYPE, setterParameterTypes, ClassNode.EMPTY_ARRAY, setterBlock); setter.setSynthetic(true); // add it to the class declaringClass.addMethod(setter); } /** * Snoops through the declaring class and all parents looking for methods * void addPropertyChangeListener(PropertyChangeListener), * void removePropertyChangeListener(PropertyChangeListener), and * void firePropertyChange(String, Object, Object). If any are defined all * must be defined or a compilation error results. * * @param declaringClass the class to search * @param sourceUnit the source unit, for error reporting. {@code @NotNull}. * @return true if property change support should be added */ protected boolean needsPropertyChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) { boolean foundAdd = false, foundRemove = false, foundFire = false; ClassNode consideredClass = declaringClass; while (consideredClass!= null) { for (MethodNode method : consideredClass.getMethods()) { // just check length, MOP will match it up foundAdd = foundAdd || method.getName().equals("addPropertyChangeListener") && method.getParameters().length == 1; foundRemove = foundRemove || method.getName().equals("removePropertyChangeListener") && method.getParameters().length == 1; foundFire = foundFire || method.getName().equals("firePropertyChange") && method.getParameters().length == 3; if (foundAdd && foundRemove && foundFire) { return false; } } consideredClass = consideredClass.getSuperClass(); } // check if a super class has @Bindable annotations consideredClass = declaringClass.getSuperClass(); while (consideredClass!=null) { if (hasBindableAnnotation(consideredClass)) return false; for (FieldNode field : consideredClass.getFields()) { if (hasBindableAnnotation(field)) return false; } consideredClass = consideredClass.getSuperClass(); } if (foundAdd || foundRemove || foundFire) { sourceUnit.getErrorCollector().addErrorAndContinue( new SimpleMessage("@Bindable cannot be processed on " + declaringClass.getName() + " because some but not all of addPropertyChangeListener, removePropertyChange, and firePropertyChange were declared in the current or super classes.", sourceUnit) ); return false; } return true; } /** * Adds the necessary field and methods to support property change support. *

    * Adds a new field: *

         * protected final java.beans.PropertyChangeSupport this$PropertyChangeSupport = new java.beans.PropertyChangeSupport(this)"
         * 
    *

    * Also adds support methods: *

         * public void addPropertyChangeListener(java.beans.PropertyChangeListener)
         * public void addPropertyChangeListener(String, java.beans.PropertyChangeListener)
         * public void removePropertyChangeListener(java.beans.PropertyChangeListener)
         * public void removePropertyChangeListener(String, java.beans.PropertyChangeListener)
         * public java.beans.PropertyChangeListener[] getPropertyChangeListeners()
         * 
    * * @param declaringClass the class to which we add the support field and methods */ protected void addPropertyChangeSupport(ClassNode declaringClass) { ClassNode pcsClassNode = ClassHelper.make(PropertyChangeSupport.class); ClassNode pclClassNode = ClassHelper.make(PropertyChangeListener.class); //String pcsFieldName = "this$propertyChangeSupport"; // add field: // protected final PropertyChangeSupport this$propertyChangeSupport = new java.beans.PropertyChangeSupport(this) FieldNode pcsField = declaringClass.addField( "this$propertyChangeSupport", ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, pcsClassNode, new ConstructorCallExpression(pcsClassNode, new ArgumentListExpression(new Expression[]{new VariableExpression("this")}))); // add method: // void addPropertyChangeListener(listener) { // this$propertyChangeSupport.addPropertyChangeListener(listener) // } declaringClass.addMethod( new MethodNode( "addPropertyChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(pclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "addPropertyChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("listener")}))))); // add method: // void addPropertyChangeListener(name, listener) { // this$propertyChangeSupport.addPropertyChangeListener(name, listener) // } declaringClass.addMethod( new MethodNode( "addPropertyChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(pclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "addPropertyChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("name"), new VariableExpression("listener")}))))); // add method: // boolean removePropertyChangeListener(listener) { // return this$propertyChangeSupport.removePropertyChangeListener(listener); // } declaringClass.addMethod( new MethodNode( "removePropertyChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(pclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "removePropertyChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("listener")}))))); // add method: void removePropertyChangeListener(name, listener) declaringClass.addMethod( new MethodNode( "removePropertyChangeListener", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(pclClassNode, "listener")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "removePropertyChangeListener", new ArgumentListExpression( new Expression[]{new VariableExpression("name"), new VariableExpression("listener")}))))); // add method: // void firePropertyChange(String name, Object oldValue, Object newValue) { // this$propertyChangeSupport.firePropertyChange(name, oldValue, newValue) // } declaringClass.addMethod( new MethodNode( "firePropertyChange", ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "oldValue"), new Parameter(ClassHelper.OBJECT_TYPE, "newValue")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "firePropertyChange", new ArgumentListExpression( new Expression[]{ new VariableExpression("name"), new VariableExpression("oldValue"), new VariableExpression("newValue")}))))); // add method: // PropertyChangeListener[] getPropertyChangeListeners() { // return this$propertyChangeSupport.getPropertyChangeListeners // } declaringClass.addMethod( new MethodNode( "getPropertyChangeListeners", ACC_PUBLIC | ACC_SYNTHETIC, pclClassNode.makeArray(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement( new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "getPropertyChangeListeners", ArgumentListExpression.EMPTY_ARGUMENTS))))); // add method: // PropertyChangeListener[] getPropertyChangeListeners(String name) { // return this$propertyChangeSupport.getPropertyChangeListeners(name) // } declaringClass.addMethod( new MethodNode( "getPropertyChangeListeners", ACC_PUBLIC | ACC_SYNTHETIC, pclClassNode.makeArray(), new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "name")}, ClassNode.EMPTY_ARRAY, new ReturnStatement( new ExpressionStatement( new MethodCallExpression( new FieldExpression(pcsField), "getPropertyChangeListeners", new ArgumentListExpression( new Expression[]{new VariableExpression("name")})))))); } } groovy-1.8.6/src/main/groovy/beans/Vetoable.java0000644001501200150120000001071111707612044021127 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates a groovy property or a class.

    * * When annotating a property it indicates that the property should be a * constrained property according to the JavaBeans spec, subject to * listeners vetoing the property change.

    * * When annotating a class it indicates that all groovy properties in that * class should be bound as though each property had the annotation (even * if it already has it explicitly).

    * * It is a compilation error to place this annotation on a field (that is * not a property, i.e. has scope visibility modifiers).

    * * If a property with a user defined setter method is annotated the code * block is wrapped with the needed code to fire off the event.

    * * Here is a simple example of how to annotate a class with Vetoable: *
     * @groovy.beans.Vetoable
     * class Person {
     *     String firstName
     *     def zipCode
     * }
     * 
    * This code is transformed by the compiler into something resembling the following * snippet. Notice the difference between a String and a def/Object property: *
     * public class Person implements groovy.lang.GroovyObject { 
     * 
     *     private java.lang.String firstName 
     *     private java.lang.Object zipCode 
     *     final private java.beans.VetoableChangeSupport this$vetoableChangeSupport 
     * 
     *     public Person() {
     *         this$vetoableChangeSupport = new java.beans.VetoableChangeSupport(this)
     *     }
     * 
     *     public void addVetoableChangeListener(java.beans.VetoableChangeListener listener) {
     *         this$vetoableChangeSupport.addVetoableChangeListener(listener)
     *     }
     * 
     *     public void addVetoableChangeListener(java.lang.String name, java.beans.VetoableChangeListener listener) {
     *         this$vetoableChangeSupport.addVetoableChangeListener(name, listener)
     *     }
     * 
     *     public void removeVetoableChangeListener(java.beans.VetoableChangeListener listener) {
     *         this$vetoableChangeSupport.removeVetoableChangeListener(listener)
     *     }
     * 
     *     public void removeVetoableChangeListener(java.lang.String name, java.beans.VetoableChangeListener listener) {
     *         this$vetoableChangeSupport.removeVetoableChangeListener(name, listener)
     *     }
     * 
     *     public void fireVetoableChange(java.lang.String name, java.lang.Object oldValue, java.lang.Object newValue) throws java.beans.PropertyVetoException {
     *         this$vetoableChangeSupport.fireVetoableChange(name, oldValue, newValue)
     *     }
     * 
     *     public java.beans.VetoableChangeListener[] getVetoableChangeListeners() {
     *         return this$vetoableChangeSupport.getVetoableChangeListeners()
     *     }
     * 
     *     public java.beans.VetoableChangeListener[] getVetoableChangeListeners(java.lang.String name) {
     *         return this$vetoableChangeSupport.getVetoableChangeListeners(name)
     *     }
     * 
     *     public void setFirstName(java.lang.String value) throws java.beans.PropertyVetoException {
     *         this.fireVetoableChange('firstName', firstName, value)
     *         firstName = value 
     *     }
     * 
     *     public void setZipCode(java.lang.Object value) throws java.beans.PropertyVetoException {
     *         this.fireVetoableChange('zipCode', zipCode, value)
     *         zipCode = value 
     *     }
     * }
     * 
    * @see VetoableASTTransformation * * @author Danno Ferrin (shemnon) */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD, ElementType.TYPE}) @GroovyASTTransformationClass("groovy.beans.VetoableASTTransformation") public @interface Vetoable { } groovy-1.8.6/src/main/groovy/beans/PropertyAccessor.java0000644001501200150120000000136211707612044022677 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; /** * @author Andres Almiray */ public interface PropertyAccessor extends PropertyReader, PropertyWriter { }groovy-1.8.6/src/main/groovy/beans/DefaultPropertyReader.java0000644001501200150120000000175711707612044023654 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; import org.codehaus.groovy.runtime.InvokerHelper; /** * @author Andres Almiray */ public class DefaultPropertyReader implements PropertyReader { public static final PropertyReader INSTANCE = new DefaultPropertyReader(); public Object read(Object owner, String propertyName) { return InvokerHelper.getPropertySafe(owner, propertyName); } } groovy-1.8.6/src/main/groovy/beans/PropertyWriter.java0000644001501200150120000000141211707612044022405 0ustar miguelmiguel/* * Copyright 2007-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.beans; /** * @author Andres Almiray */ public interface PropertyWriter { void write(Object owner, String propertyName, Object value); }groovy-1.8.6/src/main/groovy/model/0000755001501200150120000000000011627206700016532 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/model/package.html0000644001501200150120000000033711627206700021016 0ustar miguelmiguel package groovy.model.*

    An MVC model package for working with user interfaces and data structures and arbitrary Java and Groovy objects

    groovy-1.8.6/src/main/groovy/model/ClosureModel.java0000644001501200150120000000447611627206700022005 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import groovy.lang.Closure; /** * Represents a value model using a closure to extract * the value from some source model and an optional write closure * for updating the value. * * @author James Strachan * @version $Revision$ */ public class ClosureModel implements ValueModel, NestedValueModel { private final ValueModel sourceModel; private final Closure readClosure; private final Closure writeClosure; private final Class type; public ClosureModel(ValueModel sourceModel, Closure readClosure) { this(sourceModel, readClosure, null); } public ClosureModel(ValueModel sourceModel, Closure readClosure, Closure writeClosure) { this(sourceModel, readClosure, writeClosure, Object.class); } public ClosureModel(ValueModel sourceModel, Closure readClosure, Closure writeClosure, Class type) { this.sourceModel = sourceModel; this.readClosure = readClosure; this.writeClosure = writeClosure; this.type = type; } public ValueModel getSourceModel() { return sourceModel; } public Object getValue() { Object source = sourceModel.getValue(); if (source != null) { return readClosure.call(source); } return null; } public void setValue(Object value) { if (writeClosure != null) { Object source = sourceModel.getValue(); if (source != null) { writeClosure.call(new Object[] { source, value }); } } } public Class getType() { return type; } public boolean isEditable() { return writeClosure != null; } } groovy-1.8.6/src/main/groovy/model/DefaultTableModel.java0000644001501200150120000001523711627206700022722 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import groovy.lang.Closure; import org.codehaus.groovy.runtime.InvokerHelper; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.util.Collections; import java.util.List; /** * A default table model made up of PropertyModels on a Value model. * * @author James Strachan * @version $Revision$ */ public class DefaultTableModel extends AbstractTableModel { private ValueModel rowModel; private ValueModel rowsModel; private MyTableColumnModel columnModel = new MyTableColumnModel(); public DefaultTableModel(ValueModel rowsModel) { this(rowsModel, new ValueHolder()); } public DefaultTableModel(ValueModel rowsModel, ValueModel rowModel) { this.rowModel = rowModel; this.rowsModel = rowsModel; } /** * @return the column definitions. */ public List getColumnList() { return columnModel.getColumnList(); } public TableColumnModel getColumnModel() { return columnModel; } /** * Adds a property model column to the table */ public DefaultTableColumn addPropertyColumn(Object headerValue, String property, Class type) { return addColumn(headerValue, property, new PropertyModel(rowModel, property, type)); } /** * Adds a property model column to the table */ public DefaultTableColumn addPropertyColumn(Object headerValue, String property, Class type, boolean editable) { return addColumn(headerValue, property, new PropertyModel(rowModel, property, type, editable)); } /** * Adds a closure based column to the table */ public DefaultTableColumn addClosureColumn(Object headerValue, Closure readClosure, Closure writeClosure, Class type) { return addColumn(headerValue, new ClosureModel(rowModel, readClosure, writeClosure, type)); } public DefaultTableColumn addColumn(Object headerValue, ValueModel columnValueModel) { return addColumn(headerValue, headerValue, columnValueModel); } public DefaultTableColumn addColumn(Object headerValue, Object identifier, ValueModel columnValueModel) { DefaultTableColumn answer = new DefaultTableColumn(headerValue, identifier, columnValueModel); addColumn(answer); return answer; } /** * Adds a new column definition to the table */ public void addColumn(DefaultTableColumn column) { column.setModelIndex(columnModel.getColumnCount()); columnModel.addColumn(column); } /** * Removes a column definition from the table */ public void removeColumn(DefaultTableColumn column) { columnModel.removeColumn(column); } public int getRowCount() { return getRows().size(); } public int getColumnCount() { return columnModel.getColumnCount(); } public String getColumnName(int columnIndex) { String answer = null; if (columnIndex < 0 || columnIndex >= columnModel.getColumnCount()) { return answer; } Object value = columnModel.getColumn(columnIndex).getHeaderValue(); if (value != null) { return value.toString(); } return answer; } public Class getColumnClass(int columnIndex) { return getColumnModel(columnIndex).getType(); } public boolean isCellEditable(int rowIndex, int columnIndex) { return getColumnModel(columnIndex).isEditable(); } public Object getValueAt(int rowIndex, int columnIndex) { List rows = getRows(); Object answer = null; if (rowIndex < 0 || rowIndex >= rows.size()) { return answer; } if (columnIndex < 0 || columnIndex >= columnModel.getColumnCount()) { return answer; } Object row = getRows().get(rowIndex); rowModel.setValue(row); DefaultTableColumn column = (DefaultTableColumn) columnModel.getColumn(columnIndex); if (row == null || column == null) { return answer; } return column.getValue(row, rowIndex, columnIndex); } public void setValueAt(Object value, int rowIndex, int columnIndex) { List rows = getRows(); if (rowIndex < 0 || rowIndex >= rows.size()) { return; } if (columnIndex < 0 || columnIndex >= columnModel.getColumnCount()) { return; } Object row = getRows().get(rowIndex); rowModel.setValue(row); DefaultTableColumn column = (DefaultTableColumn) columnModel.getColumn(columnIndex); if (row == null || column == null) { return; } column.setValue(row, value, rowIndex, columnIndex); } protected ValueModel getColumnModel(int columnIndex) { DefaultTableColumn column = (DefaultTableColumn) columnModel.getColumn(columnIndex); return column.getValueModel(); } protected List getRows() { Object value = rowsModel.getValue(); if (value == null) { return Collections.EMPTY_LIST; } return InvokerHelper.asList(value); } protected static class MyTableColumnModel extends DefaultTableColumnModel { public List getColumnList() { return tableColumns; } public void removeColumn(TableColumn column) { super.removeColumn(column); renumberTableColumns(); } public void moveColumn(int columnIndex, int newIndex) { super.moveColumn(columnIndex, newIndex); renumberTableColumns(); } public void renumberTableColumns() { for (int i = tableColumns.size() - 1; i >= 0; i--) { ((DefaultTableColumn)tableColumns.get(i)).setModelIndex(i); } } } public ValueModel getRowModel() { return rowModel; } public ValueModel getRowsModel() { return rowsModel; } }groovy-1.8.6/src/main/groovy/model/ValueModel.java0000644001501200150120000000162611627206700021437 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; /** * Represents a model of a value * * @author James Strachan * @version $Revision$ */ public interface ValueModel { Object getValue(); void setValue(Object value); Class getType(); boolean isEditable(); } groovy-1.8.6/src/main/groovy/model/PropertyModel.java0000644001501200150120000000444311627206700022207 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import org.codehaus.groovy.runtime.InvokerHelper; /** * Represents a property of a value as a model. * * @author James Strachan * @version $Revision$ */ public class PropertyModel implements ValueModel, NestedValueModel { private ValueModel sourceModel; private String property; private Class type; boolean editable; public PropertyModel(ValueModel sourceModel, String property) { this(sourceModel, property, Object.class, true); } public PropertyModel(ValueModel sourceModel, String property, Class type) { this(sourceModel, property, type, true); } public PropertyModel(ValueModel sourceModel, String property, Class type, boolean editable) { this.sourceModel = sourceModel; this.property = property; this.type = type; //TODO After 1.1 we should introspect the meta property and set editable to false if the property is read only this.editable = editable; } public String getProperty() { return property; } public ValueModel getSourceModel() { return sourceModel; } public Object getValue() { Object source = sourceModel.getValue(); if (source != null) { return InvokerHelper.getProperty(source, property); } return null; } public void setValue(Object value) { Object source = sourceModel.getValue(); if (source != null) { InvokerHelper.setProperty(source, property, value); } } public Class getType() { return type; } public boolean isEditable() { return editable; } } groovy-1.8.6/src/main/groovy/model/FormModel.java0000644001501200150120000000246411627206700021267 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import java.util.HashMap; import java.util.Map; /** * Represents a number of field models which can be ValueModel, * PropertyModel, TableModel, TreeModel or nested FormModel instances * * @author James Strachan * @version $Revision$ */ public class FormModel { private Map fieldModels; public FormModel() { this(new HashMap()); } public FormModel(Map fieldModels) { this.fieldModels = fieldModels; } public void addModel(String name, Object model) { fieldModels.put(name, model); } public Object getModel(String name) { return fieldModels.get(name); } } groovy-1.8.6/src/main/groovy/model/DefaultTableColumn.java0000644001501200150120000000501411627206700023107 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import javax.swing.table.TableColumn; /** * Represents a column using a ValueModel to extract the value. * * @author James Strachan * @version $Revision$ */ public class DefaultTableColumn extends TableColumn { private ValueModel valueModel; public DefaultTableColumn(ValueModel valueModel) { this.valueModel = valueModel; } public DefaultTableColumn(Object header, ValueModel valueModel) { this(valueModel); setHeaderValue(header); } public DefaultTableColumn(Object headerValue, Object identifier, ValueModel columnValueModel) { this(headerValue, columnValueModel); setIdentifier(identifier); } public String toString() { return super.toString() + "[header:" + getHeaderValue() + " valueModel:" + valueModel + "]"; } /** * Evaluates the value of a cell * * @return the value * @param row the row of interest * @param rowIndex the index of the row of interest * @param columnIndex the column of interest */ public Object getValue(Object row, int rowIndex, int columnIndex) { if (valueModel instanceof NestedValueModel) { NestedValueModel nestedModel = (NestedValueModel) valueModel; nestedModel.getSourceModel().setValue(row); } return valueModel.getValue(); } public void setValue(Object row, Object value, int rowIndex, int columnIndex) { if (valueModel instanceof NestedValueModel) { NestedValueModel nestedModel = (NestedValueModel) valueModel; nestedModel.getSourceModel().setValue(row); } valueModel.setValue(value); } /** * @return the column type */ public Class getType() { return valueModel.getType(); } public ValueModel getValueModel() { return valueModel; } }groovy-1.8.6/src/main/groovy/model/NestedValueModel.java0000644001501200150120000000160511627206700022577 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; /** * Represents a nested value model such as a PropertyModel * or a ClosureModel * * @author James Strachan * @version $Revision$ */ public interface NestedValueModel { ValueModel getSourceModel(); } groovy-1.8.6/src/main/groovy/model/ValueHolder.java0000644001501200150120000000524711627206700021617 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * A simple ValueModel implementation which is a holder of an object value. * Used to share local variables with closures * * @author James Strachan * @version $Revision$ */ public class ValueHolder implements ValueModel { private Object value; private final Class type; private PropertyChangeSupport propertyChangeSupport; private boolean editable = true; public ValueHolder() { this(Object.class); } public ValueHolder(Class type) { this.type = type; } public ValueHolder(Object value) { this.value = value; this.type = (value != null) ? value.getClass() : Object.class; } /** * Add a PropertyChangeListener to the listener list. * @param listener The listener to add. */ public void addPropertyChangeListener(PropertyChangeListener listener) { if ( propertyChangeSupport == null ) { propertyChangeSupport = new PropertyChangeSupport(this); } propertyChangeSupport.addPropertyChangeListener(listener); } /** * Removes a PropertyChangeListener from the listener list. * @param listener The listener to remove. */ public void removePropertyChangeListener(PropertyChangeListener listener) { if ( propertyChangeSupport != null ) { propertyChangeSupport.removePropertyChangeListener(listener); } } public Object getValue() { return value; } public void setValue(Object value) { Object oldValue = this.value; this.value = value; if ( propertyChangeSupport != null ) { propertyChangeSupport.firePropertyChange("value", oldValue, value); } } public Class getType() { return type; } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } } groovy-1.8.6/src/main/groovy/text/0000755001501200150120000000000011715031256016416 5ustar miguelmiguelgroovy-1.8.6/src/main/groovy/text/TemplateEngine.java0000644001501200150120000000414311627206700022164 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.text; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport; /** * Represents an API to any template engine which is basically a factory of Template instances from a given text input. * * @author sam */ public abstract class TemplateEngine { public abstract Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException; public Template createTemplate(String templateText) throws CompilationFailedException, ClassNotFoundException, IOException { return createTemplate(new StringReader(templateText)); } public Template createTemplate(File file) throws CompilationFailedException, ClassNotFoundException, IOException { Reader reader = new FileReader(file); try { return createTemplate(reader); } finally { DefaultGroovyMethodsSupport.closeWithWarning(reader); } } public Template createTemplate(URL url) throws CompilationFailedException, ClassNotFoundException, IOException { Reader reader = new InputStreamReader(url.openStream()); try { return createTemplate(reader); } finally { DefaultGroovyMethodsSupport.closeWithWarning(reader); } } } groovy-1.8.6/src/main/groovy/text/SimpleTemplateEngine.java0000644001501200150120000002661611707612044023350 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.text; import groovy.lang.*; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.InvokerHelper; /** * Processes template source files substituting variables and expressions into * placeholders in a template source text to produce the desired output. *

    * The template engine uses JSP style <% %> script and <%= %> expression syntax * or GString style expressions. The variable 'out' is bound to the writer that the template * is being written to. *

    * Frequently, the template source will be in a file but here is a simple * example providing the template as a string: *
     * def binding = [
     *     firstname : "Grace",
     *     lastname  : "Hopper",
     *     accepted  : true,
     *     title     : 'Groovy for COBOL programmers'
     * ]
     * def engine = new groovy.text.SimpleTemplateEngine()
     * def text = '''\
     * Dear <%= firstname %> $lastname,
     *
     * We <% if (accepted) print 'are pleased' else print 'regret' %> \
     * to inform you that your paper entitled
     * '$title' was ${ accepted ? 'accepted' : 'rejected' }.
     *
     * The conference committee.
     * '''
     * def template = engine.createTemplate(text).make(binding)
     * println template.toString()
     * 
    * This example uses a mix of the JSP style and GString style placeholders * but you can typically use just one style if you wish. Running this * example will produce this output: *
     * Dear Grace Hopper,
     *
     * We are pleased to inform you that your paper entitled
     * 'Groovy for COBOL programmers' was accepted.
     *
     * The conference committee.
     * 
    * The template engine can also be used as the engine for {@link groovy.servlet.TemplateServlet} by placing the * following in your web.xml file (plus a corresponding servlet-mapping element): *
     * <servlet>
     *   <servlet-name>SimpleTemplate</servlet-name>
     *   <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
     *   <init-param>
     *     <param-name>template.engine</param-name>
     *     <param-value>groovy.text.SimpleTemplateEngine</param-value>
     *   </init-param>
     * </servlet>
     * 
    * In this case, your template source file should be HTML with the appropriate embedded placeholders. * * @author sam * @author Christian Stein * @author Paul King * @author Alex Tkachman */ public class SimpleTemplateEngine extends TemplateEngine { private boolean verbose; private static int counter = 1; private GroovyShell groovyShell; public SimpleTemplateEngine() { this(GroovyShell.class.getClassLoader()); } public SimpleTemplateEngine(boolean verbose) { this(GroovyShell.class.getClassLoader()); setVerbose(verbose); } public SimpleTemplateEngine(ClassLoader parentLoader) { this(new GroovyShell(parentLoader)); } public SimpleTemplateEngine(GroovyShell groovyShell) { this.groovyShell = groovyShell; } public Template createTemplate(Reader reader) throws CompilationFailedException, IOException { SimpleTemplate template = new SimpleTemplate(); String script = template.parse(reader); if (verbose) { System.out.println("\n-- script source --"); System.out.print(script); System.out.println("\n-- script end --\n"); } try { template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy"); } catch (Exception e) { throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage()); } return template; } /** * @param verbose true if you want the engine to display the template source file for debugging purposes */ public void setVerbose(boolean verbose) { this.verbose = verbose; } public boolean isVerbose() { return verbose; } private static class SimpleTemplate implements Template { protected Script script; public Writable make() { return make(null); } public Writable make(final Map map) { return new Writable() { /** * Write the template document with the set binding applied to the writer. * * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(Writer writer) { Binding binding; if (map == null) binding = new Binding(); else binding = new Binding(map); Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); PrintWriter pw = new PrintWriter(writer); scriptObject.setProperty("out", pw); scriptObject.run(); pw.flush(); return writer; } /** * Convert the template and binding into a result String. * * @see java.lang.Object#toString() */ public String toString() { StringWriter sw = new StringWriter(); writeTo(sw); return sw.toString(); } }; } /** * Parse the text document looking for <% or <%= and then call out to the appropriate handler, otherwise copy the text directly * into the script while escaping quotes. * * @param reader a reader for the template text * @return the parsed text * @throws IOException if something goes wrong */ protected String parse(Reader reader) throws IOException { if (!reader.markSupported()) { reader = new BufferedReader(reader); } StringWriter sw = new StringWriter(); startScript(sw); int c; while ((c = reader.read()) != -1) { if (c == '<') { reader.mark(1); c = reader.read(); if (c != '%') { sw.write('<'); reader.reset(); } else { reader.mark(1); c = reader.read(); if (c == '=') { groovyExpression(reader, sw); } else { reader.reset(); groovySection(reader, sw); } } continue; // at least '<' is consumed ... read next chars. } if (c == '$') { reader.mark(1); c = reader.read(); if (c != '{') { sw.write('$'); reader.reset(); } else { reader.mark(1); sw.write("${"); processGSstring(reader, sw); } continue; // at least '$' is consumed ... read next chars. } if (c == '\"') { sw.write('\\'); } /* * Handle raw new line characters. */ if (c == '\n' || c == '\r') { if (c == '\r') { // on Windows, "\r\n" is a new line. reader.mark(1); c = reader.read(); if (c != '\n') { reader.reset(); } } sw.write("\n"); continue; } sw.write(c); } endScript(sw); return sw.toString(); } private void startScript(StringWriter sw) { sw.write("out.print(\"\"\""); } private void endScript(StringWriter sw) { sw.write("\"\"\");\n"); sw.write("\n/* Generated by SimpleTemplateEngine */"); } private void processGSstring(Reader reader, StringWriter sw) throws IOException { int c; while ((c = reader.read()) != -1) { if (c != '\n' && c != '\r') { sw.write(c); } if (c == '}') { break; } } } /** * Closes the currently open write and writes out the following text as a GString expression until it reaches an end %>. * * @param reader a reader for the template text * @param sw a StringWriter to write expression content * @throws IOException if something goes wrong */ private void groovyExpression(Reader reader, StringWriter sw) throws IOException { sw.write("${"); int c; while ((c = reader.read()) != -1) { if (c == '%') { c = reader.read(); if (c != '>') { sw.write('%'); } else { break; } } if (c != '\n' && c != '\r') { sw.write(c); } } sw.write("}"); } /** * Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end %>. * * @param reader a reader for the template text * @param sw a StringWriter to write expression content * @throws IOException if something goes wrong */ private void groovySection(Reader reader, StringWriter sw) throws IOException { sw.write("\"\"\");"); int c; while ((c = reader.read()) != -1) { if (c == '%') { c = reader.read(); if (c != '>') { sw.write('%'); } else { break; } } /* Don't eat EOL chars in sections - as they are valid instruction separators. * See http://jira.codehaus.org/browse/GROOVY-980 */ // if (c != '\n' && c != '\r') { sw.write(c); //} } sw.write(";\nout.print(\"\"\""); } } } groovy-1.8.6/src/main/groovy/text/Template.java0000644001501200150120000000163311627206700021037 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.text; import groovy.lang.Writable; import java.util.Map; /** * A template is a block of text with an associated binding that can be output to a writer or evaluated to a string. * * @author sam */ public interface Template { Writable make(); Writable make(Map binding); } groovy-1.8.6/src/main/groovy/text/package.html0000644001501200150120000000030711627206700020677 0ustar miguelmiguel package groovy.text.*

    Contains the text processing utilities including templating APIs and default implementations.

    groovy-1.8.6/src/main/groovy/text/XmlTemplateEngine.java0000644001501200150120000002655011627206700022653 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.text; import groovy.lang.Binding; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovyShell; import groovy.lang.Script; import groovy.lang.Writable; import groovy.util.IndentPrinter; import groovy.util.Node; import groovy.util.XmlNodePrinter; import groovy.util.XmlParser; import groovy.xml.QName; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.InvokerHelper; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; /** * Template engine for use in templating scenarios where both the template * source and the expected output are intended to be XML. *

    * Templates may use the normal '${expression}' and '$variable' notations * to insert an arbitrary expression into the template. * In addition, support is also provided for special tags: * <gsp:scriptlet> (for inserting code fragments) and * <gsp:expression> (for code fragments which produce output). *

    * Comments and processing instructions * will be removed as part of processing and special XML characters such as * <, >, " and ' will be escaped using the respective XML notation. * The output will also be indented using standard XML pretty printing. *

    * The xmlns namespace definition for gsp: tags will be removed * but other namespace definitions will be preserved (but may change to an * equivalent position within the XML tree). *

    * Normally, the template source will be in a file but here is a simple * example providing the XML template as a string: *
     * def binding = [firstname:"Jochen", lastname:"Theodorou",
     *                nickname:"blackdrag", salutation:"Dear"]
     * def engine = new groovy.text.XmlTemplateEngine()
     * def text = '''\
     * <?xml version="1.0" encoding="UTF-8"?>
     * <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp' xmlns:foo='baz' type='letter'>
     *   <gsp:scriptlet>def greeting = "${salutation}est"</gsp:scriptlet>
     *   <gsp:expression>greeting</gsp:expression>
     *   <foo:to>$firstname "$nickname" $lastname</foo:to>
     *   How are you today?
     * </document>
     * '''
     * def template = engine.createTemplate(text).make(binding)
     * println template.toString()
     * 
    * This example will produce this output: *
     * <document type='letter'>
     * Dearest
     * <foo:to xmlns:foo='baz'>
     *   Jochen &quot;blackdrag&quot; Theodorou
     * </foo:to>
     * How are you today?
     * </document>
     * 
    * The XML template engine can also be used as the engine for {@link groovy.servlet.TemplateServlet} by placing the * following in your web.xml file (plus a corresponding servlet-mapping element): *
     * <servlet>
     *   <servlet-name>XmlTemplate</servlet-name>
     *   <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
     *   <init-param>
     *     <param-name>template.engine</param-name>
     *     <param-value>groovy.text.XmlTemplateEngine</param-value>
     *   </init-param>
     * </servlet>
     * 
    * * @author Christian Stein * @author Paul King */ public class XmlTemplateEngine extends TemplateEngine { private static int counter = 1; private static class GspPrinter extends XmlNodePrinter { public GspPrinter(PrintWriter out, String indent) { this(new IndentPrinter(out, indent)); } public GspPrinter(IndentPrinter out) { super(out, "\\\""); setQuote("'"); } protected void printGroovyTag(String tag, String text) { if (tag.equals("scriptlet")) { out.print(text); out.print("\n"); return; } if (tag.equals("expression")) { printLineBegin(); out.print("${"); out.print(text); out.print("}"); printLineEnd(); return; } throw new RuntimeException("Unsupported 'gsp:' tag named \"" + tag + "\"."); } protected void printSimpleItem(Object value) { this.printLineBegin(); out.print(escapeSpecialChars(InvokerHelper.toString(value))); printLineEnd(); } private String escapeSpecialChars(String s) { StringBuilder sb = new StringBuilder(); boolean inGString = false; for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); switch (c) { case '$': sb.append("$"); if (i < s.length() - 1 && s.charAt(i + 1) == '{') inGString = true; break; case '<': append(sb, c, "<", inGString); break; case '>': append(sb, c, ">", inGString); break; case '"': append(sb, c, """, inGString); break; case '\'': append(sb, c, "'", inGString); break; case '}': sb.append(c); inGString = false; break; default: sb.append(c); } } return sb.toString(); } private void append(StringBuilder sb, char plainChar, String xmlString, boolean inGString) { if (inGString) { sb.append(plainChar); } else { sb.append(xmlString); } } protected void printLineBegin() { out.print("out.print(\"\"\""); out.printIndent(); } protected void printLineEnd(String comment) { out.print("\\n\"\"\");"); if (comment != null) { out.print(" // "); out.print(comment); } out.print("\n"); } protected boolean printSpecialNode(Node node) { Object name = node.name(); if (name != null && name instanceof QName) { QName qn = (QName) name; // check uri and for legacy cases just check prefix name (not recommended) if (qn.getNamespaceURI().equals("http://groovy.codehaus.org/2005/gsp") || qn.getPrefix().equals("gsp")) { String s = qn.getLocalPart(); if (s.length() == 0) { throw new RuntimeException("No local part after 'gsp:' given in node " + node); } printGroovyTag(s, node.text()); return true; } } return false; } } private static class XmlTemplate implements Template { private final Script script; public XmlTemplate(Script script) { this.script = script; } public Writable make() { return make(new HashMap()); } public Writable make(Map map) { if (map == null) { throw new IllegalArgumentException("map must not be null"); } return new XmlWritable(script, new Binding(map)); } } private static class XmlWritable implements Writable { private final Binding binding; private final Script script; private WeakReference result; public XmlWritable(Script script, Binding binding) { this.script = script; this.binding = binding; this.result = new WeakReference(null); } public Writer writeTo(Writer out) { Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); PrintWriter pw = new PrintWriter(out); scriptObject.setProperty("out", pw); scriptObject.run(); pw.flush(); return out; } public String toString() { if (result.get() != null) { return result.get().toString(); } String string = writeTo(new StringWriter(1024)).toString(); result = new WeakReference(string); return string; } } public static final String DEFAULT_INDENTATION = " "; private final GroovyShell groovyShell; private final XmlParser xmlParser; private String indentation; public XmlTemplateEngine() throws SAXException, ParserConfigurationException { this(DEFAULT_INDENTATION, false); } public XmlTemplateEngine(String indentation, boolean validating) throws SAXException, ParserConfigurationException { this(new XmlParser(validating, true), new GroovyShell()); setIndentation(indentation); } public XmlTemplateEngine(XmlParser xmlParser, ClassLoader parentLoader) { this(xmlParser, new GroovyShell(parentLoader)); } public XmlTemplateEngine(XmlParser xmlParser, GroovyShell groovyShell) { this.groovyShell = groovyShell; this.xmlParser = xmlParser; setIndentation(DEFAULT_INDENTATION); } public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException { Node root ; try { root = xmlParser.parse(reader); } catch (SAXException e) { throw new RuntimeException("Parsing XML source failed.", e); } if (root == null) { throw new IOException("Parsing XML source failed: root node is null."); } StringWriter writer = new StringWriter(1024); writer.write("/* Generated by XmlTemplateEngine */\n"); new GspPrinter(new PrintWriter(writer), indentation).print(root); Script script; try { script = groovyShell.parse(writer.toString(), "XmlTemplateScript" + counter++ + ".groovy"); } catch (Exception e) { throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage()); } return new XmlTemplate(script); } public String getIndentation() { return indentation; } public void setIndentation(String indentation) { if (indentation == null) { indentation = DEFAULT_INDENTATION; } this.indentation = indentation; } public String toString() { return "XmlTemplateEngine"; } } groovy-1.8.6/src/main/groovy/text/GStringTemplateEngine.java0000644001501200150120000002676511715031256023500 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovy.text; import groovy.lang.*; import java.io.IOException; import java.io.Reader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import org.codehaus.groovy.control.CompilationFailedException; /** * Processes template source files substituting variables and expressions into * placeholders in a template source text to produce the desired output using * a streaming approach. This engine has equivalent functionality to the * {@link SimpleTemplateEngine} but creates the template using writable * closures making it potentially more scalable for large templates or in streaming scenarios. *

    * The template engine uses JSP style <% %> script and <%= %> expression syntax * or GString style expressions. The variable 'out' is bound to the writer that the template * is being written to. *

    * Frequently, the template source will be in a file but here is a simple * example providing the template as a string: *
     * def binding = [
     *     firstname : "Grace",
     *     lastname  : "Hopper",
     *     accepted  : true,
     *     title     : 'Groovy for COBOL programmers'
     * ]
     * def engine = new groovy.text.GStringTemplateEngine()
     * def text = '''\
     * Dear <%= firstname %> $lastname,
     *
     * We <% if (accepted) print 'are pleased' else print 'regret' %> \
     * to inform you that your paper entitled
     * '$title' was ${ accepted ? 'accepted' : 'rejected' }.
     *
     * The conference committee.
     * '''
     * def template = engine.createTemplate(text).make(binding)
     * println template.toString()
     * 
    * This example uses a mix of the JSP style and GString style placeholders * but you can typically use just one style if you wish. Running this * example will produce this output: *
     * Dear Grace Hopper,
     *
     * We are pleased to inform you that your paper entitled
     * 'Groovy for COBOL programmers' was accepted.
     *
     * The conference committee.
     * 
    * The template engine can also be used as the engine for {@link groovy.servlet.TemplateServlet} by placing the * following in your web.xml file (plus a corresponding servlet-mapping element): *
     * <servlet>
     *   <servlet-name>GStringTemplate</servlet-name>
     *   <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
     *   <init-param>
     *     <param-name>template.engine</param-name>
     *     <param-value>groovy.text.GStringTemplateEngine</param-value>
     *   </init-param>
     * </servlet>
     * 
    * In this case, your template source file should be HTML with the appropriate embedded placeholders. * * @author tug@wilson.co.uk * @author Paul King */ public class GStringTemplateEngine extends TemplateEngine { private final ClassLoader parentLoader; private static int counter = 1; public GStringTemplateEngine() { this(GStringTemplate.class.getClassLoader()); } public GStringTemplateEngine(ClassLoader parentLoader) { this.parentLoader = parentLoader; } /* (non-Javadoc) * @see groovy.text.TemplateEngine#createTemplate(java.io.Reader) */ public Template createTemplate(final Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException { return new GStringTemplate(reader, parentLoader); } private static class GStringTemplate implements Template { final Closure template; /** * Turn the template into a writable Closure * When executed the closure evaluates all the code embedded in the * template and then writes a GString containing the fixed and variable items * to the writer passed as a parameter *

    * For example: *

    * '<%= "test" %> of expr and <% test = 1 %>${test} script.' *

    * would compile into: *

    * { out -> out << "${"test"} of expr and "; test = 1 ; out << "${test} script."}.asWritable() * * @param reader * @param parentLoader * @throws CompilationFailedException * @throws ClassNotFoundException * @throws IOException */ GStringTemplate(final Reader reader, final ClassLoader parentLoader) throws CompilationFailedException, ClassNotFoundException, IOException { final StringBuilder templateExpressions = new StringBuilder("package groovy.tmp.templates\n def getTemplate() { return { out -> delegate = new Binding(delegate); out << \"\"\""); boolean writingString = true; while (true) { int c = reader.read(); if (c == -1) break; if (c == '<') { c = reader.read(); if (c == '%') { c = reader.read(); if (c == '=') { parseExpression(reader, writingString, templateExpressions); writingString = true; continue; } else { parseSection(c, reader, writingString, templateExpressions); writingString = false; continue; } } else { appendCharacter('<', templateExpressions, writingString); writingString = true; } } else if (c == '"') { appendCharacter('\\', templateExpressions, writingString); writingString = true; } else if (c == '$') { appendCharacter('$', templateExpressions, writingString); writingString = true; c = reader.read(); if (c == '{') { appendCharacter('{', templateExpressions, writingString); writingString = true; parseGSstring(reader, writingString, templateExpressions); writingString = true; continue; } } appendCharacter((char) c, templateExpressions, writingString); writingString = true; } if (writingString) { templateExpressions.append("\"\"\""); } templateExpressions.append("}.asWritable()}"); final GroovyClassLoader loader = (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new GroovyClassLoader(parentLoader); } }); final Class groovyClass; try { groovyClass = loader.parseClass(new GroovyCodeSource(templateExpressions.toString(), "GStringTemplateScript" + counter++ + ".groovy", "x")); } catch (Exception e) { throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage()); } try { final GroovyObject object = (GroovyObject) groovyClass.newInstance(); this.template = (Closure) object.invokeMethod("getTemplate", null); } catch (InstantiationException e) { throw new ClassNotFoundException(e.getMessage()); } catch (IllegalAccessException e) { throw new ClassNotFoundException(e.getMessage()); } } private static void appendCharacter(final char c, final StringBuilder templateExpressions, final boolean writingString) { if (!writingString) { templateExpressions.append("out << \"\"\""); } templateExpressions.append(c); } private void parseGSstring(Reader reader, boolean writingString, StringBuilder templateExpressions) throws IOException { if (!writingString) { templateExpressions.append("\"\"\"; "); } while (true) { int c = reader.read(); if (c == -1) break; templateExpressions.append((char) c); if (c == '}') { break; } } } /** * Parse a <% .... %> section * if we are writing a GString close and append ';' * then write the section as a statement * * @param pendingC * @param reader * @param writingString * @param templateExpressions * @throws IOException */ private static void parseSection(final int pendingC, final Reader reader, final boolean writingString, final StringBuilder templateExpressions) throws IOException { if (writingString) { templateExpressions.append("\"\"\"; "); } templateExpressions.append((char) pendingC); while (true) { int c = reader.read(); if (c == -1) break; if (c == '%') { c = reader.read(); if (c == '>') break; templateExpressions.append('%'); } templateExpressions.append((char) c); } templateExpressions.append(";\n "); } /** * Parse a <%= .... %> expression * * @param reader * @param writingString * @param templateExpressions * @throws IOException */ private static void parseExpression(final Reader reader, final boolean writingString, final StringBuilder templateExpressions) throws IOException { if (!writingString) { templateExpressions.append("out << \"\"\""); } templateExpressions.append("${"); while (true) { int c = reader.read(); if (c == -1) break; if (c == '%') { c = reader.read(); if (c == '>') break; templateExpressions.append('%'); } templateExpressions.append((char) c); } templateExpressions.append('}'); } public Writable make() { return make(null); } public Writable make(final Map map) { final Closure template = (Closure) this.template.clone(); template.setDelegate(map); return (Writable) template; } } } groovy-1.8.6/src/main/META-INF/0000755001501200150120000000000011627206702015247 5ustar miguelmiguelgroovy-1.8.6/src/main/META-INF/groovy-release-info.properties0000644001501200150120000000020211627206702023253 0ustar miguelmiguelImplementationVersion=##ImplementationVersion## BundleVersion=##BundleVersion## BuildDate=##BuildDate## BuildTime=##BuildTime##groovy-1.8.6/src/main/META-INF/services/0000755001501200150120000000000011707612044017071 5ustar miguelmiguelgroovy-1.8.6/src/main/META-INF/services/javax.script.ScriptEngineFactory0000644001501200150120000000006511627206702025353 0ustar miguelmiguelorg.codehaus.groovy.jsr223.GroovyScriptEngineFactory groovy-1.8.6/src/main/META-INF/services/org.codehaus.groovy.source.Extensions0000644001501200150120000000060111627206702026354 0ustar miguelmiguel# Format: one extension on each line without the leading "*." # Listed below are default groovy source file extensions. # NOTE: This implementation of supporting multiple file extensions is experimental and # the exact implementation details may vary when modularization gets introduced in # groovy 1.8. However, in terms of the behavior, this support will remain intact. groovygroovy-1.8.6/src/main/META-INF/services/org.codehaus.groovy.transform.ASTTransformation0000644001501200150120000000030311707612044030304 0ustar miguelmiguel# global transformation to handle @Grab annotation groovy.grape.GrabAnnotationTransformation #global transformation for AST Builder org.codehaus.groovy.ast.builder.AstBuilderTransformation groovy-1.8.6/src/main/org/0000755001501200150120000000000011627206700014674 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/0000755001501200150120000000000011627206700016467 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/0000755001501200150120000000000011715031256020014 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/transform/0000755001501200150120000000000011715031256022027 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/transform/AutoExternalizeASTTransformation.java0000644001501200150120000001376311707612046031331 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.AutoExternalize; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.List; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceNonPropertyFields; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstancePropertyFields; /** * Handles generation of code for the @AutoExternalize annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class AutoExternalizeASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = AutoExternalize.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode EXTERNALIZABLE_TYPE = ClassHelper.make(Externalizable.class); private static final ClassNode OBJECTOUTPUT_TYPE = ClassHelper.make(ObjectOutput.class); private static final ClassNode OBJECTINPUT_TYPE = ClassHelper.make(ObjectInput.class); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; checkNotInterface(cNode, MY_TYPE_NAME); cNode.addInterface(EXTERNALIZABLE_TYPE); boolean includeFields = memberHasValue(anno, "includeFields", true); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List list = getInstancePropertyFields(cNode); if (includeFields) { list.addAll(getInstanceNonPropertyFields(cNode)); } createWriteExternal(cNode, excludes, list); createReadExternal(cNode, excludes, list); } } private void createWriteExternal(ClassNode cNode, List excludes, List list) { final BlockStatement body = new BlockStatement(); VariableExpression out = new VariableExpression("out", OBJECTOUTPUT_TYPE); for (FieldNode fNode : list) { if (excludes.contains(fNode.getName())) continue; if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue; body.addStatement(new ExpressionStatement(new MethodCallExpression(out, "write" + suffixForField(fNode), new VariableExpression(fNode)))); } ClassNode[] exceptions = {ClassHelper.make(IOException.class)}; cNode.addMethod("writeExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(OBJECTOUTPUT_TYPE, "out")}, exceptions, body); } private void createReadExternal(ClassNode cNode, List excludes, List list) { final BlockStatement body = new BlockStatement(); final Expression oin = new VariableExpression("oin", OBJECTINPUT_TYPE); for (FieldNode fNode : list) { if (excludes.contains(fNode.getName())) continue; if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue; Expression readObject = new MethodCallExpression(oin, "read" + suffixForField(fNode), MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new BinaryExpression(new VariableExpression(fNode), ASSIGN, readObject))); } cNode.addMethod("readExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(OBJECTINPUT_TYPE, "oin")}, ClassNode.EMPTY_ARRAY, body); } private String suffixForField(FieldNode fNode) { // use primitives for efficiently if (fNode.getType() == ClassHelper.int_TYPE) return "Int"; if (fNode.getType() == ClassHelper.boolean_TYPE) return "Boolean"; // currently char isn't found due to a bug, so go with Object // if (fNode.getType() == ClassHelper.char_TYPE) return "Char"; if (fNode.getType() == ClassHelper.long_TYPE) return "Long"; if (fNode.getType() == ClassHelper.short_TYPE) return "Short"; if (fNode.getType() == ClassHelper.byte_TYPE) return "Byte"; if (fNode.getType() == ClassHelper.float_TYPE) return "Float"; if (fNode.getType() == ClassHelper.double_TYPE) return "Double"; return "Object"; } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ImmutableASTTransformation.java0000644001501200150120000005366311715031256030125 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.lang.MetaClass; import groovy.lang.MissingPropertyException; import groovy.lang.ReadOnlyPropertyException; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import java.lang.reflect.Modifier; import java.util.*; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.*; import static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createEquals; import static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createHashCode; import static org.codehaus.groovy.transform.ToStringASTTransformation.createToString; /** * Handles generation of code for the @Immutable annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ImmutableASTTransformation extends AbstractASTTransformation { /* Currently leaving BigInteger and BigDecimal in list but see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370 Also, Color is not final so while not normally used with child classes, it isn't strictly immutable. Use at your own risk. */ private static List immutableList = Arrays.asList( "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Double", "java.lang.Float", "java.lang.Integer", "java.lang.Long", "java.lang.Short", "java.lang.String", "java.math.BigInteger", "java.math.BigDecimal", "java.awt.Color", "java.net.URI", "java.util.UUID" ); private static final Class MY_CLASS = groovy.transform.Immutable.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode DATE_TYPE = ClassHelper.make(Date.class); private static final ClassNode CLONEABLE_TYPE = ClassHelper.make(Cloneable.class); private static final ClassNode COLLECTION_TYPE = ClassHelper.makeWithoutCaching(Collection.class, false); private static final ClassNode READONLYEXCEPTION_TYPE = ClassHelper.make(ReadOnlyPropertyException.class); private static final ClassNode DGM_TYPE = ClassHelper.make(DefaultGroovyMethods.class); private static final ClassNode SELF_TYPE = ClassHelper.make(ImmutableASTTransformation.class); private static final ClassNode HASHMAP_TYPE = ClassHelper.makeWithoutCaching(HashMap.class, false); private static final ClassNode MAP_TYPE = ClassHelper.makeWithoutCaching(Map.class, false); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; // temporarily have weaker check which allows for old Deprecated Annotation // if (!MY_TYPE.equals(node.getClassNode())) return; if (!node.getClassNode().getName().endsWith(".Immutable")) return; List newProperties = new ArrayList(); if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; String cName = cNode.getName(); checkNotInterface(cNode, MY_TYPE_NAME); makeClassFinal(cNode); final List pList = getInstanceProperties(cNode); for (PropertyNode pNode : pList) { adjustPropertyForImmutability(pNode, newProperties); } for (PropertyNode pNode : newProperties) { cNode.getProperties().remove(pNode); addProperty(cNode, pNode); } final List fList = cNode.getFields(); for (FieldNode fNode : fList) { ensureNotPublic(cName, fNode); } createConstructors(cNode); createHashCode(cNode, true, false, false, null, null); createEquals(cNode, false, false, false, null, null); if (!hasAnnotation(cNode, ToStringASTTransformation.MY_TYPE)) { createToString(cNode, false, false, null, null, false); } } } private void makeClassFinal(ClassNode cNode) { if ((cNode.getModifiers() & ACC_FINAL) == 0) { cNode.setModifiers(cNode.getModifiers() | ACC_FINAL); } } private void createConstructors(ClassNode cNode) { if (!validateConstructors(cNode)) return; List list = getInstanceProperties(cNode); boolean specialHashMapCase = list.size() == 1 && list.get(0).getField().getType().equals(HASHMAP_TYPE); if (specialHashMapCase) { createConstructorMapSpecial(cNode, list); } else { createConstructorMap(cNode, list); createConstructorOrdered(cNode, list); } } private void createConstructorOrdered(ClassNode cNode, List list) { final MapExpression argMap = new MapExpression(); final Parameter[] orderedParams = new Parameter[list.size()]; int index = 0; for (PropertyNode pNode : list) { Parameter param = new Parameter(pNode.getField().getType(), pNode.getField().getName()); orderedParams[index++] = param; argMap.addMapEntryExpression(new ConstantExpression(pNode.getName()), new VariableExpression(pNode.getName())); } final BlockStatement orderedBody = new BlockStatement(); orderedBody.addStatement(new ExpressionStatement( new ConstructorCallExpression(ClassNode.THIS, new ArgumentListExpression(new CastExpression(HASHMAP_TYPE, argMap))) )); cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, orderedParams, ClassNode.EMPTY_ARRAY, orderedBody)); } private Statement createGetterBodyDefault(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); return new ExpressionStatement(fieldExpr); } private Expression cloneCollectionExpr(Expression fieldExpr) { return new StaticMethodCallExpression(DGM_TYPE, "asImmutable", fieldExpr); } private Expression cloneArrayOrCloneableExpr(Expression fieldExpr) { return new MethodCallExpression(fieldExpr, "clone", MethodCallExpression.NO_ARGUMENTS); } private void createConstructorMapSpecial(ClassNode cNode, List list) { final BlockStatement body = new BlockStatement(); body.addStatement(createConstructorStatementMapSpecial(list.get(0).getField())); createConstructorMapCommon(cNode, body); } private void createConstructorMap(ClassNode cNode, List list) { final BlockStatement body = new BlockStatement(); for (PropertyNode pNode : list) { body.addStatement(createConstructorStatement(cNode, pNode)); } // check for missing properties Expression checkArgs = new ArgumentListExpression(new VariableExpression("this"), new VariableExpression("args")); body.addStatement(new ExpressionStatement(new StaticMethodCallExpression(SELF_TYPE, "checkPropNames", checkArgs))); createConstructorMapCommon(cNode, body); } private void createConstructorMapCommon(ClassNode cNode, BlockStatement body) { final List fList = cNode.getFields(); for (FieldNode fNode : fList) { if (fNode.isPublic()) continue; // public fields will be rejected elsewhere if (cNode.getProperty(fNode.getName()) != null) continue; // a property if (fNode.isFinal() && fNode.isStatic()) continue; if (fNode.getName().contains("$")) continue; // internal field if (fNode.isFinal() && fNode.getInitialExpression() != null) body.addStatement(checkFinalArgNotOverridden(cNode, fNode)); body.addStatement(createConstructorStatementDefault(fNode)); } final Parameter[] params = new Parameter[]{new Parameter(HASHMAP_TYPE, "args")}; cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, new IfStatement( equalsNullExpr(new VariableExpression("args")), new EmptyStatement(), body))); } private Statement checkFinalArgNotOverridden(ClassNode cNode, FieldNode fNode) { final String name = fNode.getName(); Expression value = findArg(name); return new IfStatement( equalsNullExpr(value), new EmptyStatement(), new ThrowStatement(new ConstructorCallExpression(READONLYEXCEPTION_TYPE, new ArgumentListExpression(new ConstantExpression(name), new ConstantExpression(cNode.getName()))))); } private Statement createConstructorStatementMapSpecial(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression namedArgs = findArg(fNode.getName()); Expression baseArgs = new VariableExpression("args"); return new IfStatement( equalsNullExpr(baseArgs), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, cloneCollectionExpr(initExpr))), new IfStatement( equalsNullExpr(namedArgs), new IfStatement( isTrueExpr(new MethodCallExpression(baseArgs, "containsKey", new ConstantExpression(fNode.getName()))), assignStatement(fieldExpr, namedArgs), assignStatement(fieldExpr, cloneCollectionExpr(baseArgs))), new IfStatement( isOneExpr(new MethodCallExpression(baseArgs, "size", MethodCallExpression.NO_ARGUMENTS)), assignStatement(fieldExpr, cloneCollectionExpr(namedArgs)), assignStatement(fieldExpr, cloneCollectionExpr(baseArgs))) ) ); } private void ensureNotPublic(String cNode, FieldNode fNode) { String fName = fNode.getName(); // TODO: do we need to lock down things like: $ownClass if (fNode.isPublic() && !fName.contains("$") && !(fNode.isStatic() && fNode.isFinal())) { addError("Public field '" + fName + "' not allowed for " + MY_TYPE_NAME + " class '" + cNode + "'.", fNode); } } private void addProperty(ClassNode cNode, PropertyNode pNode) { final FieldNode fn = pNode.getField(); cNode.getFields().remove(fn); cNode.addProperty(pNode.getName(), pNode.getModifiers() | ACC_FINAL, pNode.getType(), pNode.getInitialExpression(), pNode.getGetterBlock(), pNode.getSetterBlock()); final FieldNode newfn = cNode.getField(fn.getName()); cNode.getFields().remove(newfn); cNode.addField(fn); } private boolean validateConstructors(ClassNode cNode) { if(cNode instanceof InnerClassNode && Modifier.isStatic(cNode.getModifiers())) { List constructors = cNode.getDeclaredConstructors(); if (constructors.size() == 1 && constructors.get(0).getCode() == null) { constructors.remove(0); } } if (cNode.getDeclaredConstructors().size() != 0) { // TODO: allow constructors which only call provided constructor? addError("Explicit constructors not allowed for " + ImmutableASTTransformation.MY_TYPE_NAME + " class: " + cNode.getNameWithoutPackage(), cNode.getDeclaredConstructors().get(0)); } return true; } private Statement createConstructorStatement(ClassNode cNode, PropertyNode pNode) { FieldNode fNode = pNode.getField(); final ClassNode fieldType = fNode.getType(); Statement statement = null; if (fieldType.isArray() || fieldType.implementsInterface(CLONEABLE_TYPE)) { statement = createConstructorStatementArrayOrCloneable(fNode); } else if (fieldType.isDerivedFrom(DATE_TYPE)) { statement = createConstructorStatementDate(fNode); } else if (isOrImplements(fieldType, COLLECTION_TYPE) || fieldType.isDerivedFrom(COLLECTION_TYPE) || isOrImplements(fieldType, MAP_TYPE) || fieldType.isDerivedFrom(MAP_TYPE)) { statement = createConstructorStatementCollection(fNode); } else if (isKnownImmutable(fieldType)) { statement = createConstructorStatementDefault(fNode); } else if (fieldType.isResolved()) { addError(createErrorMessage(cNode.getName(), fNode.getName(), fieldType.getName(), "compiling"), fNode); } else { statement = createConstructorStatementGuarded(cNode, fNode); } return statement; } private Statement createConstructorStatementGuarded(ClassNode cNode, FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression unknown = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(unknown), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, checkUnresolved(cNode, fNode, initExpr))), assignStatement(fieldExpr, checkUnresolved(cNode, fNode, unknown))); } private Expression checkUnresolved(ClassNode cNode, FieldNode fNode, Expression value) { Expression args = new TupleExpression(new ConstantExpression(cNode.getName()), new ConstantExpression(fNode.getName()), value); return new StaticMethodCallExpression(SELF_TYPE, "checkImmutable", args); } private Statement createConstructorStatementCollection(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression collection = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(collection), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, cloneCollectionExpr(initExpr))), new IfStatement( isInstanceOf(collection, CLONEABLE_TYPE), assignStatement(fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(collection))), assignStatement(fieldExpr, cloneCollectionExpr(collection)))); } private boolean isKnownImmutable(ClassNode fieldType) { if (!fieldType.isResolved()) return false; return fieldType.isEnum() || ClassHelper.isPrimitiveType(fieldType) || fieldType.getAnnotations(MY_TYPE).size() != 0 || inImmutableList(fieldType.getName()); } private static boolean inImmutableList(String typeName) { return immutableList.contains(typeName); } private Statement createConstructorStatementArrayOrCloneable(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; final Expression array = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(array), new IfStatement( equalsNullExpr(initExpr), assignStatement(fieldExpr, ConstantExpression.NULL), assignStatement(fieldExpr, cloneArrayOrCloneableExpr(initExpr))), assignStatement(fieldExpr, cloneArrayOrCloneableExpr(array))); } private Statement createConstructorStatementDate(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; final Expression date = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(date), new IfStatement( equalsNullExpr(initExpr), assignStatement(fieldExpr, ConstantExpression.NULL), assignStatement(fieldExpr, cloneDateExpr(initExpr))), assignStatement(fieldExpr, cloneDateExpr(date))); } private Expression cloneDateExpr(Expression origDate) { return new ConstructorCallExpression(DATE_TYPE, new MethodCallExpression(origDate, "getTime", MethodCallExpression.NO_ARGUMENTS)); } private void adjustPropertyForImmutability(PropertyNode pNode, List newNodes) { final FieldNode fNode = pNode.getField(); fNode.setModifiers((pNode.getModifiers() & (~ACC_PUBLIC)) | ACC_FINAL | ACC_PRIVATE); adjustPropertyNode(pNode, createGetterBody(fNode)); newNodes.add(pNode); } private void adjustPropertyNode(PropertyNode pNode, Statement getterBody) { pNode.setSetterBlock(null); pNode.setGetterBlock(getterBody); } private Statement createGetterBody(FieldNode fNode) { BlockStatement body = new BlockStatement(); final ClassNode fieldType = fNode.getType(); final Statement statement; if (fieldType.isArray() || fieldType.implementsInterface(CLONEABLE_TYPE)) { statement = createGetterBodyArrayOrCloneable(fNode); } else if (fieldType.isDerivedFrom(DATE_TYPE)) { statement = createGetterBodyDate(fNode); } else { statement = createGetterBodyDefault(fNode); } body.addStatement(statement); return body; } private static String createErrorMessage(String className, String fieldName, String typeName, String mode) { return MY_TYPE_NAME + " processor doesn't know how to handle field '" + fieldName + "' of type '" + prettyTypeName(typeName) + "' while " + mode + " class " + className + ".\n" + MY_TYPE_NAME + " classes only support properties with effectively immutable types including:\n" + "- Strings, primitive types, wrapper types, BigInteger and BigDecimal, enums\n" + "- other " + MY_TYPE_NAME + " classes and known immutables (java.awt.Color, java.net.URI)\n" + "- Cloneable classes, collections, maps and arrays, and other classes with special handling (java.util.Date)\n" + "Other restrictions apply, please see the groovydoc for " + MY_TYPE_NAME + " for further details"; } private static String prettyTypeName(String name) { return name.equals("java.lang.Object") ? name + " or def" : name; } private Statement createGetterBodyArrayOrCloneable(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); final Expression expression = cloneArrayOrCloneableExpr(fieldExpr); return safeExpression(fieldExpr, expression); } private Statement createGetterBodyDate(FieldNode fNode) { final Expression fieldExpr = new VariableExpression(fNode); final Expression expression = cloneDateExpr(fieldExpr); return safeExpression(fieldExpr, expression); } @SuppressWarnings("Unchecked") public static Object checkImmutable(String className, String fieldName, Object field) { if (field == null || field instanceof Enum || inImmutableList(field.getClass().getName())) return field; if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field); if (field.getClass().getAnnotation(MY_CLASS) != null) return field; final String typeName = field.getClass().getName(); throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing")); } public static void checkPropNames(Object instance, Map args) { final MetaClass metaClass = InvokerHelper.getMetaClass(instance); for (String k : args.keySet()) { if (metaClass.hasProperty(instance, k) == null) throw new MissingPropertyException(k, instance.getClass()); } } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ToStringASTTransformation.java0000644001501200150120000002164411715031256027751 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.ToString; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.StaticMethodCallExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import java.util.ArrayList; import java.util.List; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceNonPropertyFields; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceProperties; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.hasDeclaredMethod; /** * Handles generation of code for the @ToString annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ToStringASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = ToString.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode STRINGBUFFER_TYPE = ClassHelper.make(StringBuffer.class); private static final ClassNode INVOKER_TYPE = ClassHelper.make(InvokerHelper.class); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; checkNotInterface(cNode, MY_TYPE_NAME); boolean includeSuper = memberHasValue(anno, "includeSuper", true); if (includeSuper && cNode.getSuperClass().getName().equals("java.lang.Object")) { addError("Error during " + MY_TYPE_NAME + " processing: includeSuper=true but '" + cNode.getName() + "' has no super class.", anno); } boolean includeNames = memberHasValue(anno, "includeNames", true); boolean includeFields = memberHasValue(anno, "includeFields", true); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List includes = tokenize((String) getMemberValue(anno, "includes")); if (hasAnnotation(cNode, CanonicalASTTransformation.MY_TYPE)) { AnnotationNode canonical = cNode.getAnnotations(CanonicalASTTransformation.MY_TYPE).get(0); if (excludes == null || excludes.isEmpty()) excludes = tokenize((String) getMemberValue(canonical, "excludes")); if (includes == null || includes.isEmpty()) includes = tokenize((String) getMemberValue(canonical, "includes")); } if (includes != null && !includes.isEmpty() && excludes != null && !excludes.isEmpty()) { addError("Error during " + MY_TYPE_NAME + " processing: Only one of 'includes' and 'excludes' should be supplied not both.", anno); } createToString(cNode, includeSuper, includeFields, excludes, includes, includeNames); } } public static void createToString(ClassNode cNode, boolean includeSuper, boolean includeFields, List excludes, List includes, boolean includeNames) { // make a public method if none exists otherwise try a private method with leading underscore boolean hasExistingToString = hasDeclaredMethod(cNode, "toString", 0); if (hasExistingToString && hasDeclaredMethod(cNode, "_toString", 0)) return; final BlockStatement body = new BlockStatement(); // def _result = new StringBuffer() final Expression result = new VariableExpression("_result"); final Expression init = new ConstructorCallExpression(STRINGBUFFER_TYPE, MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new DeclarationExpression(result, ASSIGN, init))); body.addStatement(append(result, new ConstantExpression(cNode.getName()))); body.addStatement(append(result, new ConstantExpression("("))); boolean first = true; List pList = getInstanceProperties(cNode); for (PropertyNode pNode : pList) { if (shouldSkip(pNode.getName(), excludes, includes)) continue; first = appendPrefix(body, result, first, pNode.getName(), includeNames); String getterName = "get" + Verifier.capitalize(pNode.getName()); Expression getter = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, MethodCallExpression.NO_ARGUMENTS); body.addStatement(append(result, new StaticMethodCallExpression(INVOKER_TYPE, "toString", getter))); } List fList = new ArrayList(); if (includeFields) { fList.addAll(getInstanceNonPropertyFields(cNode)); } for (FieldNode fNode : fList) { if (shouldSkip(fNode.getName(), excludes, includes)) continue; first = appendPrefix(body, result, first, fNode.getName(), includeNames); body.addStatement(append(result, new StaticMethodCallExpression(INVOKER_TYPE, "toString", new VariableExpression(fNode)))); } if (includeSuper) { appendPrefix(body, result, first, "super", includeNames); // not through MOP to avoid infinite recursion body.addStatement(append(result, new MethodCallExpression(VariableExpression.SUPER_EXPRESSION, "toString", MethodCallExpression.NO_ARGUMENTS))); } body.addStatement(append(result, new ConstantExpression(")"))); body.addStatement(new ReturnStatement(new MethodCallExpression(result, "toString", MethodCallExpression.NO_ARGUMENTS))); cNode.addMethod(new MethodNode(hasExistingToString ? "_toString" : "toString", hasExistingToString ? ACC_PRIVATE : ACC_PUBLIC, ClassHelper.STRING_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body)); } private static boolean appendPrefix(BlockStatement body, Expression result, boolean first, String name, boolean includeNames) { if (first) { first = false; } else { body.addStatement(append(result, new ConstantExpression(", "))); } if (includeNames) body.addStatement(toStringPropertyName(result, name)); return first; } private static Statement toStringPropertyName(Expression result, String fName) { final BlockStatement body = new BlockStatement(); body.addStatement(append(result, new ConstantExpression(fName))); body.addStatement(append(result, new ConstantExpression(":"))); return body; } private static ExpressionStatement append(Expression result, Expression expr) { return new ExpressionStatement(new MethodCallExpression(result, "append", expr)); } private static boolean shouldSkip(String name, List excludes, List includes) { return (excludes != null && excludes.contains(name)) || name.contains("$") || (includes != null && !includes.isEmpty() && !includes.contains(name)); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/IndexedPropertyASTTransformation.java0000644001501200150120000001525211707612046031326 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.IndexedProperty; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.List; /** * Handles generation of code for the {@code @}IndexedProperty annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class IndexedPropertyASTTransformation implements ASTTransformation, Opcodes { private static final Class MY_CLASS = IndexedProperty.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode LIST_TYPE = ClassHelper.makeWithoutCaching(List.class, false); private static final Token ASSIGN = Token.newSymbol("=", -1, -1); private static final Token INDEX = Token.newSymbol("[", -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; if (parent instanceof FieldNode) { FieldNode fNode = (FieldNode) parent; ClassNode cNode = fNode.getDeclaringClass(); if (cNode.getProperty(fNode.getName()) == null) { addError("Error during " + MY_TYPE_NAME + " processing. Field '" + fNode.getName() + "' doesn't appear to be a property; incorrect visibility?", fNode, source); return; } ClassNode fType = fNode.getType(); if (fType.isArray()) { addArraySetter(fNode); addArrayGetter(fNode); } else if (fType.isDerivedFrom(LIST_TYPE)) { addListSetter(fNode); addListGetter(fNode); } else { addError("Error during " + MY_TYPE_NAME + " processing. Non-Indexable property '" + fNode.getName() + "' found. Type must be array or list but found " + fType.getName(), fNode, source); } } } private void addListGetter(FieldNode fNode) { addGetter(fNode, getComponentTypeForList(fNode.getType())); } private void addListSetter(FieldNode fNode) { addSetter(fNode, getComponentTypeForList(fNode.getType())); } private void addArrayGetter(FieldNode fNode) { addGetter(fNode, fNode.getType().getComponentType()); } private void addArraySetter(FieldNode fNode) { addSetter(fNode, fNode.getType().getComponentType()); } private void addGetter(FieldNode fNode, ClassNode componentType) { ClassNode cNode = fNode.getDeclaringClass(); BlockStatement body = new BlockStatement(); Parameter[] params = new Parameter[1]; params[0] = new Parameter(ClassHelper.int_TYPE, "index"); body.addStatement(new ExpressionStatement( new BinaryExpression( new VariableExpression(fNode.getName()), INDEX, new VariableExpression(params[0])) )); cNode.addMethod(makeName(fNode, "get"), getModifiers(fNode), componentType, params, null, body); } private void addSetter(FieldNode fNode, ClassNode componentType) { ClassNode cNode = fNode.getDeclaringClass(); BlockStatement body = new BlockStatement(); Parameter[] params = new Parameter[2]; params[0] = new Parameter(ClassHelper.int_TYPE, "index"); params[1] = new Parameter(componentType, "value"); body.addStatement(new ExpressionStatement( new BinaryExpression( new BinaryExpression( new VariableExpression(fNode.getName()), INDEX, new VariableExpression(params[0])), ASSIGN, new VariableExpression(params[1]) ))); cNode.addMethod(makeName(fNode, "set"), getModifiers(fNode), ClassHelper.VOID_TYPE, params, null, body); } private ClassNode getComponentTypeForList(ClassNode fType) { if (fType.isUsingGenerics() && fType.getGenericsTypes().length == 1) { return fType.getGenericsTypes()[0].getType(); } else { return ClassHelper.OBJECT_TYPE; } } private int getModifiers(FieldNode fNode) { int mods = ACC_PUBLIC; if (fNode.isStatic()) mods |= ACC_STATIC; return mods; } private String makeName(FieldNode fNode, String prefix) { return prefix + MetaClassHelper.capitalize(fNode.getName()); } private void addError(String msg, ASTNode expr, SourceUnit source) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source) ); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/GroovyASTTransformation.java0000644001501200150120000000375111627206700027464 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.control.CompilePhase; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This is an annotation on a class, currently just {@link ASTTransformation}. * This provides information about how and when to apply the transformation, * such as what phase it should be applied in. * * The allowed phase is a function of how the transformation is introduced * into the compile process. If the transform is automatically added via a * marker annotation only the SEMANTIC_ANALYSIS and latter phases are legal * for the phase(). This is because the annotations are not inspected until * after the classes are all resolved. * * Also, only annotation types present during the SEMANTIC_ANALYSIS phase * will be handled. Transformations adding other annotations that are * transformable will have those new annotations only considered in * latter phases, and only if the type was present in the source unit * during SEMANTIC_ANALYSIS. * * @see ASTTransformation * @author Danno Ferrin (shemnon) */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface GroovyASTTransformation { CompilePhase phase() default CompilePhase.CANONICALIZATION; } groovy-1.8.6/src/main/org/codehaus/groovy/transform/LogASTTransformation.java0000644001501200150120000002144411707612046026722 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; /** * This class provides an AST Transformation to add a log field to a class. * * @author Guillaume Laforge * @author Jochen Theodorou * @author Dinko Srkoc * @author Hamlet D'Arcy * @author Raffaele Cigni * @author Alberto Vilches Raton * @author Tomasz Bujok * @author Martin Ghados * @author Matthias Cullmann */ @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) public class LogASTTransformation implements ASTTransformation { public void visit(ASTNode[] nodes, final SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { addError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes), nodes[0], source); } AnnotatedNode targetClass = (AnnotatedNode) nodes[1]; AnnotationNode logAnnotation = (AnnotationNode) nodes[0]; final LoggingStrategy loggingStrategy = createLoggingStrategy(logAnnotation); if (loggingStrategy == null) return; final String logFieldName = lookupLogFieldName(logAnnotation); if (!(targetClass instanceof ClassNode)) throw new GroovyBugError("Class annotation " + logAnnotation.getClassNode().getName() + " annotated no Class, this must not happen."); final ClassNode classNode = (ClassNode) targetClass; ClassCodeExpressionTransformer transformer = new ClassCodeExpressionTransformer() { private FieldNode logNode; @Override protected SourceUnit getSourceUnit() { return source; } public Expression transform(Expression exp) { if (exp == null) return null; if (exp instanceof MethodCallExpression) { return transformMethodCallExpression(exp); } return super.transform(exp); } @Override public void visitClass(ClassNode node) { FieldNode logField = node.getField(logFieldName); if (logField != null && logField.getOwner().equals(node)) { addError("Class annotated with Log annotation cannot have log field declared", logField); } else if (logField != null && !Modifier.isPrivate(logField.getModifiers())) { addError("Class annotated with Log annotation cannot have log field declared because the field exists in the parent class: " + logField.getOwner().getName(), logField); } else { logNode = loggingStrategy.addLoggerFieldToClass(node, logFieldName); } super.visitClass(node); } private Expression transformMethodCallExpression(Expression exp) { MethodCallExpression mce = (MethodCallExpression) exp; if (!(mce.getObjectExpression() instanceof VariableExpression)) { return exp; } VariableExpression variableExpression = (VariableExpression) mce.getObjectExpression(); if (!variableExpression.getName().equals(logFieldName) || !(variableExpression.getAccessedVariable() instanceof DynamicVariable)) { return exp; } String methodName = mce.getMethodAsString(); if (methodName == null) return exp; if (usesSimpleMethodArgumentsOnly(mce)) return exp; variableExpression.setAccessedVariable(logNode); if (!loggingStrategy.isLoggingMethod(methodName)) return exp; return loggingStrategy.wrapLoggingMethodCall(variableExpression, methodName, exp); } private boolean usesSimpleMethodArgumentsOnly(MethodCallExpression mce) { Expression arguments = mce.getArguments(); if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; for (Expression exp : tuple.getExpressions()) { if (!isSimpleExpression(exp)) return false; } return true; } return !isSimpleExpression(arguments); } private boolean isSimpleExpression(Expression exp) { if (exp instanceof ConstantExpression) return true; if (exp instanceof VariableExpression) return true; return false; } }; transformer.visitClass(classNode); } private String lookupLogFieldName(AnnotationNode logAnnotation) { Expression member = logAnnotation.getMember("value"); if (member != null && member.getText() != null) { return member.getText(); } else { return "log"; } } public void addError(String msg, ASTNode expr, SourceUnit source) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source) ); } private LoggingStrategy createLoggingStrategy(AnnotationNode logAnnotation) { String annotationName = logAnnotation.getClassNode().getName(); Class annotationClass; try { annotationClass = Class.forName(annotationName); } catch (Throwable e) { throw new RuntimeException("Could not resolve class named " + annotationName); } Method annotationMethod; try { annotationMethod = annotationClass.getDeclaredMethod("loggingStrategy", (Class[]) null); } catch (Throwable e) { throw new RuntimeException("Could not find method named loggingStrategy on class named " + annotationName); } Object defaultValue; try { defaultValue = annotationMethod.getDefaultValue(); } catch (Throwable e) { throw new RuntimeException("Could not find default value of method named loggingStrategy on class named " + annotationName); } if (!LoggingStrategy.class.isAssignableFrom((Class) defaultValue)) { throw new RuntimeException("Default loggingStrategy value on class named " + annotationName + " is not a LoggingStrategy"); } try { Class strategyClass = (Class) defaultValue; return strategyClass.newInstance(); } catch (Exception e) { return null; } } /** * A LoggingStrategy defines how to wire a new logger instance into an existing class. * It is meant to be used with the @Log family of annotations to allow you to * write your own Log annotation provider. */ public interface LoggingStrategy { /** * In this method, you are given a ClassNode and a field name, and you must add a new Field * onto the class. Return the result of the ClassNode.addField operations. * * @param classNode the class that was originally annotated with the Log transformation. * @param fieldName the name of the logger field * @return the FieldNode instance that was created and added to the class */ FieldNode addLoggerFieldToClass(ClassNode classNode, String fieldName); boolean isLoggingMethod(String methodName); Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/AbstractASTTransformation.java0000644001501200150120000000660211707612046027743 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.syntax.SyntaxException; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractASTTransformation implements Opcodes, ASTTransformation { private SourceUnit sourceUnit; protected void init(ASTNode[] nodes, SourceUnit sourceUnit) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } this.sourceUnit = sourceUnit; } protected boolean memberHasValue(AnnotationNode node, String name, Object value) { final Expression member = node.getMember(name); return member != null && member instanceof ConstantExpression && ((ConstantExpression) member).getValue().equals(value); } protected Object getMemberValue(AnnotationNode node, String name) { final Expression member = node.getMember(name); if (member != null && member instanceof ConstantExpression) return ((ConstantExpression) member).getValue(); return null; } protected void addError(String msg, ASTNode expr) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); sourceUnit.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), sourceUnit) ); } protected void checkNotInterface(ClassNode cNode, String annotationName) { if (cNode.isInterface()) { addError("Error processing interface '" + cNode.getName() + "'. " + annotationName + " not allowed for interfaces.", cNode); } } protected boolean hasAnnotation(ClassNode cNode, ClassNode annotation) { List annots = cNode.getAnnotations(annotation); return (annots != null && annots.size() > 0); } protected List tokenize(String rawExcludes) { return rawExcludes == null ? new ArrayList() : DefaultGroovyMethods.tokenize(rawExcludes, ", "); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ASTTransformation.java0000644001501200150120000000434411627206700026255 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.control.SourceUnit; /** * This class is instantiated and invoked when an AST transformation is * activated. For Global AST Transformations, this interface is called once per SourceUnit, which is usually a * Groovy source file. For Local AST Transformations, this interface is invoked once every time the Local annotation * marker is encountered.

    * * You must annotate this class with {@link GroovyASTTransformation} so that Groovy knows which * {@link org.codehaus.groovy.control.CompilePhase} to run in. * * @see GroovyASTTransformation * @author Danno Ferrin (shemnon) */ public interface ASTTransformation { /** * The method is invoked when an AST Transformation is active. For local transformations, it is invoked once * each time the local annotation is encountered. For global transformations, it is invoked once for every source * unit, which is typically a source file. * * @param nodes The ASTnodes when the call was triggered. Element 0 is the AnnotationNode that triggered this * annotation to be activated. Element 1 is the AnnotatedNode decorated, such as a MethodNode or ClassNode. For * global transformations it is usually safe to ignore this parameter. * @param source The source unit being compiled. The source unit may contain several classes. For global transformations, * information about the AST can be retrieved from this object. */ void visit(ASTNode nodes[], SourceUnit source); } groovy-1.8.6/src/main/org/codehaus/groovy/transform/EqualsAndHashCodeASTTransformation.java0000644001501200150120000002773311707612046031464 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.EqualsAndHashCode; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.util.HashCodeHelper; import java.util.ArrayList; import java.util.List; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.*; @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class EqualsAndHashCodeASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = EqualsAndHashCode.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode HASHUTIL_TYPE = ClassHelper.make(HashCodeHelper.class); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); private static final ClassNode OBJECT_TYPE = ClassHelper.make(Object.class); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; checkNotInterface(cNode, MY_TYPE_NAME); boolean callSuper = memberHasValue(anno, "callSuper", true); boolean useCanEqual = !memberHasValue(anno, "useCanEqual", false); if (callSuper && cNode.getSuperClass().getName().equals("java.lang.Object")) { addError("Error during " + MY_TYPE_NAME + " processing: callSuper=true but '" + cNode.getName() + "' has no super class.", anno); } boolean includeFields = memberHasValue(anno, "includeFields", true); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List includes = tokenize((String) getMemberValue(anno, "includes")); if (hasAnnotation(cNode, CanonicalASTTransformation.MY_TYPE)) { AnnotationNode canonical = cNode.getAnnotations(CanonicalASTTransformation.MY_TYPE).get(0); if (excludes == null || excludes.isEmpty()) excludes = tokenize((String) getMemberValue(canonical, "excludes")); if (includes == null || includes.isEmpty()) includes = tokenize((String) getMemberValue(canonical, "includes")); } if (includes != null && !includes.isEmpty() && excludes != null && !excludes.isEmpty()) { addError("Error during " + MY_TYPE_NAME + " processing: Only one of 'includes' and 'excludes' should be supplied not both.", anno); } createHashCode(cNode, false, includeFields, callSuper, excludes, includes); createEquals(cNode, includeFields, callSuper, useCanEqual, excludes, includes); } } public static void createHashCode(ClassNode cNode, boolean cacheResult, boolean includeFields, boolean callSuper, List excludes, List includes) { // make a public method if none exists otherwise try a private method with leading underscore boolean hasExistingHashCode = hasDeclaredMethod(cNode, "hashCode", 0); if (hasExistingHashCode && hasDeclaredMethod(cNode, "_hashCode", 0)) return; final BlockStatement body = new BlockStatement(); // TODO use pList and fList if (cacheResult) { final FieldNode hashField = cNode.addField("$hash$code", ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.int_TYPE, null); final Expression hash = new VariableExpression(hashField); body.addStatement(new IfStatement( isZeroExpr(hash), calculateHashStatements(cNode, hash, includeFields, callSuper, excludes, includes), new EmptyStatement() )); body.addStatement(new ReturnStatement(hash)); } else { body.addStatement(calculateHashStatements(cNode, null, includeFields, callSuper, excludes, includes)); } cNode.addMethod(new MethodNode(hasExistingHashCode ? "_hashCode" : "hashCode", hasExistingHashCode ? ACC_PRIVATE : ACC_PUBLIC, ClassHelper.int_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body)); } private static Statement calculateHashStatements(ClassNode cNode, Expression hash, boolean includeFields, boolean callSuper, List excludes, List includes) { final List pList = getInstanceProperties(cNode); final List fList = new ArrayList(); if (includeFields) { fList.addAll(getInstanceNonPropertyFields(cNode)); } final BlockStatement body = new BlockStatement(); // def _result = HashCodeHelper.initHash() final Expression result = new VariableExpression("_result"); final Expression init = new StaticMethodCallExpression(HASHUTIL_TYPE, "initHash", MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new DeclarationExpression(result, ASSIGN, init))); for (PropertyNode pNode : pList) { if (shouldSkip(pNode.getName(), excludes, includes)) continue; // _result = HashCodeHelper.updateHash(_result, getProperty()) String getterName = "get" + Verifier.capitalize(pNode.getName()); Expression getter = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, MethodCallExpression.NO_ARGUMENTS); final Expression args = new TupleExpression(result, getter); final Expression current = new StaticMethodCallExpression(HASHUTIL_TYPE, "updateHash", args); body.addStatement(assignStatement(result, current)); } for (FieldNode fNode : fList) { if (shouldSkip(fNode.getName(), excludes, includes)) continue; // _result = HashCodeHelper.updateHash(_result, field) final Expression fieldExpr = new VariableExpression(fNode); final Expression args = new TupleExpression(result, fieldExpr); final Expression current = new StaticMethodCallExpression(HASHUTIL_TYPE, "updateHash", args); body.addStatement(assignStatement(result, current)); } if (callSuper) { // _result = HashCodeHelper.updateHash(_result, super.hashCode()) final Expression args = new TupleExpression(result, new MethodCallExpression(VariableExpression.SUPER_EXPRESSION, "hashCode", MethodCallExpression.NO_ARGUMENTS)); final Expression current = new StaticMethodCallExpression(HASHUTIL_TYPE, "updateHash", args); body.addStatement(assignStatement(result, current)); } // $hash$code = _result if (hash != null) { body.addStatement(assignStatement(hash, result)); } else { body.addStatement(new ReturnStatement(result)); } return body; } private static boolean shouldSkip(String name, List excludes, List includes) { return (excludes != null && excludes.contains(name)) || name.contains("$") || (includes != null && !includes.isEmpty() && !includes.contains(name)); } private static void createCanEqual(ClassNode cNode) { boolean hasExistingCanEqual = hasDeclaredMethod(cNode, "canEqual", 1); if (hasExistingCanEqual && hasDeclaredMethod(cNode, "_canEqual", 1)) return; final BlockStatement body = new BlockStatement(); VariableExpression other = new VariableExpression("other"); body.addStatement(new ReturnStatement(isInstanceof(cNode, other))); Parameter[] params = {new Parameter(OBJECT_TYPE, other.getName())}; cNode.addMethod(new MethodNode(hasExistingCanEqual ? "_canEqual" : "canEqual", hasExistingCanEqual ? ACC_PRIVATE : ACC_PUBLIC, ClassHelper.boolean_TYPE, params, ClassNode.EMPTY_ARRAY, body)); } public static void createEquals(ClassNode cNode, boolean includeFields, boolean callSuper, boolean useCanEqual, List excludes, List includes) { if (useCanEqual) createCanEqual(cNode); // make a public method if none exists otherwise try a private method with leading underscore boolean hasExistingEquals = hasDeclaredMethod(cNode, "equals", 1); if (hasExistingEquals && hasDeclaredMethod(cNode, "_equals", 1)) return; final BlockStatement body = new BlockStatement(); VariableExpression other = new VariableExpression("other"); // some short circuit cases for efficiency body.addStatement(returnFalseIfNull(other)); body.addStatement(returnTrueIfIdentical(VariableExpression.THIS_EXPRESSION, other)); if (useCanEqual) { body.addStatement(returnFalseIfNotInstanceof(cNode, other)); body.addStatement(new IfStatement( new BooleanExpression(new MethodCallExpression(other, "canEqual", VariableExpression.THIS_EXPRESSION)), new EmptyStatement(), new ReturnStatement(ConstantExpression.FALSE) )); } else { body.addStatement(returnFalseIfWrongType(cNode, other)); } VariableExpression otherTyped = new VariableExpression("otherTyped"); body.addStatement(new ExpressionStatement(new DeclarationExpression(otherTyped, ASSIGN, new CastExpression(cNode, other)))); List pList = getInstanceProperties(cNode); for (PropertyNode pNode : pList) { if (shouldSkip(pNode.getName(), excludes, includes)) continue; body.addStatement(returnFalseIfPropertyNotEqual(pNode, otherTyped)); } List fList = new ArrayList(); if (includeFields) { fList.addAll(getInstanceNonPropertyFields(cNode)); } for (FieldNode fNode : fList) { if (shouldSkip(fNode.getName(), excludes, includes)) continue; body.addStatement(returnFalseIfFieldNotEqual(fNode, otherTyped)); } if (callSuper) { body.addStatement(new IfStatement( isTrueExpr(new MethodCallExpression(VariableExpression.SUPER_EXPRESSION, "equals", other)), new EmptyStatement(), new ReturnStatement(ConstantExpression.FALSE) )); } // default body.addStatement(new ReturnStatement(ConstantExpression.TRUE)); Parameter[] params = {new Parameter(OBJECT_TYPE, other.getName())}; cNode.addMethod(new MethodNode(hasExistingEquals ? "_equals" : "equals", hasExistingEquals ? ACC_PRIVATE : ACC_PUBLIC, ClassHelper.boolean_TYPE, params, ClassNode.EMPTY_ARRAY, body)); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/DelegateASTTransformation.java0000644001501200150120000002473011707612046027714 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.lang.GroovyObject; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Handles generation of code for the @Delegate annotation * * @author Alex Tkachman * @author Guillaume Laforge * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class DelegateASTTransformation implements ASTTransformation, Opcodes { private static final ClassNode DEPRECATED_TYPE = ClassHelper.make(Deprecated.class); private static final ClassNode GROOVYOBJECT_TYPE = ClassHelper.make(GroovyObject.class); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (parent instanceof FieldNode) { FieldNode fieldNode = (FieldNode) parent; final ClassNode type = fieldNode.getType(); final ClassNode owner = fieldNode.getOwner(); if (type.equals(ClassHelper.OBJECT_TYPE) || type.equals(GROOVYOBJECT_TYPE)) { addError("@Delegate field '" + fieldNode.getName() + "' has an inappropriate type: " + type.getName() + ". Please add an explicit type but not java.lang.Object or groovy.lang.GroovyObject.", parent, source); return; } if (type.equals(owner)) { addError("@Delegate field '" + fieldNode.getName() + "' has an inappropriate type: " + type.getName() + ". Delegation to own type not supported. Please use a different type.", parent, source); return; } final List fieldMethods = getAllMethods(type); for (ClassNode next : type.getAllInterfaces()) { fieldMethods.addAll(getAllMethods(next)); } final Expression deprecatedElement = node.getMember("deprecated"); final boolean deprecated = hasBooleanValue(deprecatedElement, true); final List ownerMethods = getAllMethods(owner); for (MethodNode mn : fieldMethods) { addDelegateMethod(fieldNode, owner, ownerMethods, mn, deprecated); } for (PropertyNode prop : type.getProperties()) { if (prop.isStatic() || !prop.isPublic()) continue; String name = prop.getName(); addGetterIfNeeded(fieldNode, owner, prop, name); addSetterIfNeeded(fieldNode, owner, prop, name); } final Expression interfacesElement = node.getMember("interfaces"); if (hasBooleanValue(interfacesElement, false)) return; final Set allInterfaces = type.getAllInterfaces(); final Set ownerIfaces = owner.getAllInterfaces(); for (ClassNode iface : allInterfaces) { if (Modifier.isPublic(iface.getModifiers()) && !ownerIfaces.contains(iface)) { final ClassNode[] ifaces = owner.getInterfaces(); final ClassNode[] newIfaces = new ClassNode[ifaces.length + 1]; System.arraycopy(ifaces, 0, newIfaces, 0, ifaces.length); newIfaces[ifaces.length] = iface; owner.setInterfaces(newIfaces); } } } } private List getAllMethods(ClassNode type) { ClassNode node = type; List result = new ArrayList(); while (node != null) { result.addAll(node.getMethods()); node = node.getSuperClass(); } return result; } private boolean hasBooleanValue(Expression expression, boolean bool) { return expression instanceof ConstantExpression && ((ConstantExpression) expression).getValue().equals(bool); } private void addSetterIfNeeded(FieldNode fieldNode, ClassNode owner, PropertyNode prop, String name) { String setterName = "set" + Verifier.capitalize(name); if ((prop.getModifiers() & ACC_FINAL) == 0 && owner.getSetterMethod(setterName) == null) { owner.addMethod(setterName, ACC_PUBLIC, ClassHelper.VOID_TYPE, new Parameter[]{new Parameter(nonGeneric(prop.getType()), "value")}, null, new ExpressionStatement( new BinaryExpression( new PropertyExpression( new VariableExpression(fieldNode), name), Token.newSymbol(Types.EQUAL, -1, -1), new VariableExpression("value")))); } } private void addGetterIfNeeded(FieldNode fieldNode, ClassNode owner, PropertyNode prop, String name) { String getterName = "get" + Verifier.capitalize(name); if (owner.getGetterMethod(getterName) == null) { owner.addMethod(getterName, ACC_PUBLIC, nonGeneric(prop.getType()), Parameter.EMPTY_ARRAY, null, new ReturnStatement( new PropertyExpression( new VariableExpression(fieldNode), name))); } } private void addDelegateMethod(FieldNode fieldNode, ClassNode owner, List ownMethods, MethodNode candidate, boolean deprecated) { if (!candidate.isPublic() || candidate.isStatic() || 0 != (candidate.getModifiers () & Opcodes.ACC_SYNTHETIC)) return; if (!candidate.getAnnotations(DEPRECATED_TYPE).isEmpty() && !deprecated) return; // ignore methods from GroovyObject for (MethodNode mn : GROOVYOBJECT_TYPE.getMethods()) { if (mn.getTypeDescriptor().equals(candidate.getTypeDescriptor())) { return; } } // ignore methods already in owner for (MethodNode mn : owner.getMethods()) { if (mn.getTypeDescriptor().equals(candidate.getTypeDescriptor())) { return; } } // give precedence to methods of self (but not abstract or static superclass methods) // also allows abstract or static self methods to be selected for overriding but they are ignored later MethodNode existingNode = null; for (MethodNode mn : ownMethods) { if (mn.getTypeDescriptor().equals(candidate.getTypeDescriptor()) && !mn.isAbstract() && !mn.isStatic()) { existingNode = mn; break; } } if (existingNode == null || existingNode.getCode() == null) { final ArgumentListExpression args = new ArgumentListExpression(); final Parameter[] params = candidate.getParameters(); final Parameter[] newParams = new Parameter[params.length]; for (int i = 0; i < newParams.length; i++) { Parameter newParam = new Parameter(nonGeneric(params[i].getType()), params[i].getName()); newParam.setInitialExpression(params[i].getInitialExpression()); newParams[i] = newParam; args.addExpression(new VariableExpression(newParam)); } // addMethod will ignore attempts to override abstract or static methods with same signature on self MethodNode newMethod = owner.addMethod(candidate.getName(), candidate.getModifiers() & (~ACC_ABSTRACT) & (~ACC_NATIVE), nonGeneric(candidate.getReturnType()), newParams, candidate.getExceptions(), new ExpressionStatement( new MethodCallExpression( new VariableExpression(fieldNode), candidate.getName(), args))); newMethod.setGenericsTypes(candidate.getGenericsTypes()); } } private ClassNode nonGeneric(ClassNode type) { if (type.isUsingGenerics()) { final ClassNode nonGen = ClassHelper.makeWithoutCaching(type.getName()); nonGen.setRedirect(type); nonGen.setGenericsTypes(null); nonGen.setUsingGenerics(false); return nonGen; } else if (type.isArray() && type.getComponentType().isUsingGenerics()) { return type.getComponentType().getPlainNodeReference().makeArray(); } else { return type; } } public void addError(String msg, ASTNode expr, SourceUnit source) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source) ); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ThreadInterruptibleASTTransformation.groovy0000644001501200150120000000521611715031256032561 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.ThreadInterrupt import org.codehaus.groovy.ast.ClassHelper import org.codehaus.groovy.ast.ClassNode import org.codehaus.groovy.ast.MethodNode import org.codehaus.groovy.ast.stmt.DoWhileStatement import org.codehaus.groovy.ast.stmt.ForStatement import org.codehaus.groovy.ast.stmt.WhileStatement import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.ast.expr.* /** * Allows "interrupt-safe" executions of scripts by adding Thread.currentThread().isInterrupted() * checks on loops (for, while, do) and first statement of closures. By default, also adds an interrupt check * statement on the beginning of method calls. * * @see groovy.transform.ThreadInterrupt * * @author Cedric Champeau * @author Hamlet D'Arcy * * @since 1.8.0 */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ThreadInterruptibleASTTransformation extends AbstractInterruptibleASTTransformation { private static final ClassNode MY_TYPE = ClassHelper.make(ThreadInterrupt) protected ClassNode type() { return MY_TYPE; } protected String getErrorMessage() { 'Execution interrupted. The current thread has been interrupted.' } protected Expression createCondition() { new MethodCallExpression( new StaticMethodCallExpression(ClassHelper.make(Thread), 'currentThread', ArgumentListExpression.EMPTY_ARGUMENTS), 'isInterrupted', ArgumentListExpression.EMPTY_ARGUMENTS) } @Override public void visitClosureExpression(ClosureExpression closureExpr) { def code = closureExpr.code closureExpr.code = wrapBlock(code) super.visitClosureExpression closureExpr } @Override public void visitMethod(MethodNode node) { if (checkOnMethodStart && !node.isSynthetic() && !node.isAbstract()) { def code = node.code node.code = wrapBlock(code); } super.visitMethod(node) } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/LazyASTTransformation.java0000644001501200150120000002401511707612046027115 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.Opcodes; import java.lang.ref.SoftReference; import java.util.Arrays; /** * Handles generation of code for the @Lazy annotation * * @author Alex Tkachman * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class LazyASTTransformation implements ASTTransformation, Opcodes { private static final ClassNode SOFT_REF = ClassHelper.makeWithoutCaching(SoftReference.class, false); private static final Expression NULL_EXPR = ConstantExpression.NULL; private static final Token ASSIGN = Token.newSymbol("=", -1, -1); private static final Token COMPARE_NOT_EQUAL = Token.newSymbol("!=", -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (parent instanceof FieldNode) { final FieldNode fieldNode = (FieldNode) parent; final Expression member = node.getMember("soft"); final Expression init = getInitExpr(fieldNode); fieldNode.rename("$" + fieldNode.getName()); fieldNode.setModifiers(ACC_PRIVATE | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED)))); if (member instanceof ConstantExpression && ((ConstantExpression) member).getValue().equals(true)) createSoft(fieldNode, init); else { create(fieldNode, init); // @Lazy not meaningful with primitive so convert to wrapper if needed if (ClassHelper.isPrimitiveType(fieldNode.getType())) { fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType())); } } } } private void create(FieldNode fieldNode, final Expression initExpr) { final BlockStatement body = new BlockStatement(); if (fieldNode.isStatic()) { addHolderClassIdiomBody(body, fieldNode, initExpr); } else if (isVolatile(fieldNode)) { addNonThreadSafeBody(body, fieldNode, initExpr); } else { addDoubleCheckedLockingBody(body, fieldNode, initExpr); } addMethod(fieldNode, body, fieldNode.getType()); } private void addHolderClassIdiomBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) { final ClassNode declaringClass = fieldNode.getDeclaringClass(); final ClassNode fieldType = fieldNode.getType(); final int visibility = ACC_PRIVATE | ACC_STATIC; final String fullName = declaringClass.getName() + "$" + fieldType.getNameWithoutPackage() + "Holder_" + fieldNode.getName().substring(1); final InnerClassNode holderClass = new InnerClassNode(declaringClass, fullName, visibility, ClassHelper.OBJECT_TYPE); final String innerFieldName = "INSTANCE"; holderClass.addField(innerFieldName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType, initExpr); final Expression innerField = new PropertyExpression(new ClassExpression(holderClass), innerFieldName); declaringClass.getModule().addClass(holderClass); body.addStatement(new ReturnStatement(innerField)); } private void addDoubleCheckedLockingBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) { final Expression fieldExpr = new VariableExpression(fieldNode); final VariableExpression localVar = new VariableExpression(fieldNode.getName() + "_local"); body.addStatement(new ExpressionStatement(new DeclarationExpression(localVar, ASSIGN, fieldExpr))); body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(localVar, COMPARE_NOT_EQUAL, NULL_EXPR)), new ReturnStatement(localVar), new SynchronizedStatement( synchTarget(fieldNode), new IfStatement( new BooleanExpression(new BinaryExpression(fieldExpr, COMPARE_NOT_EQUAL, NULL_EXPR)), new ReturnStatement(fieldExpr), new ReturnStatement(new BinaryExpression(fieldExpr, ASSIGN, initExpr)) ) ) )); } private void addNonThreadSafeBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) { final Expression fieldExpr = new VariableExpression(fieldNode); body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(fieldExpr, COMPARE_NOT_EQUAL, NULL_EXPR)), new ExpressionStatement(fieldExpr), new ExpressionStatement(new BinaryExpression(fieldExpr, ASSIGN, initExpr)) )); } private void addMethod(FieldNode fieldNode, BlockStatement body, ClassNode type) { int visibility = ACC_PUBLIC; if (fieldNode.isStatic()) visibility |= ACC_STATIC; final String name = "get" + MetaClassHelper.capitalize(fieldNode.getName().substring(1)); fieldNode.getDeclaringClass().addMethod(name, visibility, type, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body); } private void createSoft(FieldNode fieldNode, Expression initExpr) { final ClassNode type = fieldNode.getType(); fieldNode.setType(SOFT_REF); createSoftGetter(fieldNode, initExpr, type); createSoftSetter(fieldNode, type); } private void createSoftGetter(FieldNode fieldNode, Expression initExpr, ClassNode type) { final BlockStatement body = new BlockStatement(); final Expression fieldExpr = new VariableExpression(fieldNode); final Expression resExpr = new VariableExpression("res", type); final MethodCallExpression callExpression = new MethodCallExpression(fieldExpr, "get", new ArgumentListExpression()); callExpression.setSafe(true); body.addStatement(new ExpressionStatement(new DeclarationExpression(resExpr, ASSIGN, callExpression))); final BlockStatement elseBlock = new BlockStatement(); elseBlock.addStatement(new ExpressionStatement(new BinaryExpression(resExpr, ASSIGN, initExpr))); elseBlock.addStatement(new ExpressionStatement(new BinaryExpression(fieldExpr, ASSIGN, new ConstructorCallExpression(SOFT_REF, resExpr)))); elseBlock.addStatement(new ExpressionStatement(resExpr)); final Statement mainIf = new IfStatement( new BooleanExpression(new BinaryExpression(resExpr, COMPARE_NOT_EQUAL, NULL_EXPR)), new ExpressionStatement(resExpr), elseBlock ); if (isVolatile(fieldNode)) { body.addStatement(mainIf); } else { body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(resExpr, COMPARE_NOT_EQUAL, NULL_EXPR)), new ExpressionStatement(resExpr), new SynchronizedStatement(synchTarget(fieldNode), mainIf) )); } addMethod(fieldNode, body, type); } private void createSoftSetter(FieldNode fieldNode, ClassNode type) { final BlockStatement body = new BlockStatement(); final Expression fieldExpr = new VariableExpression(fieldNode); final String name = "set" + MetaClassHelper.capitalize(fieldNode.getName().substring(1)); final Parameter parameter = new Parameter(type, "value"); final Expression paramExpr = new VariableExpression(parameter); body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(paramExpr, COMPARE_NOT_EQUAL, NULL_EXPR)), new ExpressionStatement(new BinaryExpression(fieldExpr, ASSIGN, new ConstructorCallExpression(SOFT_REF, paramExpr))), new ExpressionStatement(new BinaryExpression(fieldExpr, ASSIGN, NULL_EXPR)) )); int visibility = ACC_PUBLIC; if (fieldNode.isStatic()) visibility |= ACC_STATIC; fieldNode.getDeclaringClass().addMethod(name, visibility, ClassHelper.VOID_TYPE, new Parameter[]{parameter}, ClassNode.EMPTY_ARRAY, body); } private Expression synchTarget(FieldNode fieldNode) { return fieldNode.isStatic() ? new ClassExpression(fieldNode.getDeclaringClass()) : VariableExpression.THIS_EXPRESSION; } private boolean isVolatile(FieldNode fieldNode) { return (fieldNode.getModifiers() & ACC_VOLATILE) == 0; } private Expression getInitExpr(FieldNode fieldNode) { Expression initExpr = fieldNode.getInitialValueExpression(); fieldNode.setInitialValueExpression(null); if (initExpr == null) initExpr = new ConstructorCallExpression(fieldNode.getType(), new ArgumentListExpression()); return initExpr; } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/CategoryASTTransformation.java0000644001501200150120000002347111707612046027760 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.syntax.SyntaxException; import org.objectweb.asm.Opcodes; import groovy.lang.Reference; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Handles generation of code for the @Category annotation. *

    * Transformation logic is as follows: *

      *
    • all non-static methods converted to static ones with an additional 'self' parameter *
    • references to 'this' changed to the additional 'self' parameter *
    * * @author Alex Tkachman */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class CategoryASTTransformation implements ASTTransformation, Opcodes { private static final VariableExpression THIS_EXPRESSION; static { THIS_EXPRESSION = new VariableExpression("$this"); THIS_EXPRESSION.setClosureSharedVariable(true); } /** * Property invocations done on 'this' reference are transformed so that the invocations at runtime are * done on the additional parameter 'self' */ public void visit(ASTNode[] nodes, final SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof ClassNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, ClassNode] but got: " + Arrays.asList(nodes)); } AnnotationNode annotation = (AnnotationNode) nodes[0]; ClassNode parent = (ClassNode) nodes[1]; ClassNode targetClass = getTargetClass(source, annotation); final LinkedList> varStack = new LinkedList>(); Set names = new HashSet(); for (FieldNode field : parent.getFields()) { names.add(field.getName()); } varStack.add(names); final Reference parameter = new Reference(); final ClassCodeExpressionTransformer expressionTransformer = new ClassCodeExpressionTransformer() { protected SourceUnit getSourceUnit() { return source; } private void addVariablesToStack(Parameter[] params) { Set names = new HashSet(); names.addAll(varStack.getLast()); for (Parameter param : params) { names.add(param.getName()); } varStack.add(names); } @Override public void visitCatchStatement(CatchStatement statement) { varStack.getLast().add(statement.getVariable().getName()); super.visitCatchStatement(statement); varStack.getLast().remove(statement.getVariable().getName()); } @Override public void visitMethod(MethodNode node) { addVariablesToStack(node.getParameters()); super.visitMethod(node); varStack.removeLast(); } @Override public void visitBlockStatement(BlockStatement block) { Set names = new HashSet(); names.addAll(varStack.getLast()); varStack.add(names); super.visitBlockStatement(block); varStack.remove(names); } @Override public void visitClosureExpression(ClosureExpression ce) { addVariablesToStack(ce.getParameters()); super.visitClosureExpression(ce); varStack.removeLast(); } @Override public void visitDeclarationExpression(DeclarationExpression expression) { if (expression.isMultipleAssignmentDeclaration()) { TupleExpression te = expression.getTupleExpression(); List list = te.getExpressions(); for (Expression arg : list) { VariableExpression ve = (VariableExpression) arg; varStack.getLast().add(ve.getName()); } } else { VariableExpression ve = expression.getVariableExpression(); varStack.getLast().add(ve.getName()); } super.visitDeclarationExpression(expression); } @Override public void visitForLoop(ForStatement forLoop) { Expression exp = forLoop.getCollectionExpression(); exp.visit(this); Parameter loopParam = forLoop.getVariable(); if (loopParam != null) { varStack.getLast().add(loopParam.getName()); } super.visitForLoop(forLoop); } @Override public void visitExpressionStatement(ExpressionStatement es) { // GROOVY-3543: visit the declaration expressions so that declaration variables get added on the varStack Expression exp = es.getExpression(); if (exp instanceof DeclarationExpression) { exp.visit(this); } super.visitExpressionStatement(es); } @Override public Expression transform(Expression exp) { if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.getName().equals("this")) return THIS_EXPRESSION; else { if (!varStack.getLast().contains(ve.getName())) { return new PropertyExpression(THIS_EXPRESSION, ve.getName()); } } } else if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof VariableExpression) { VariableExpression vex = (VariableExpression) pe.getObjectExpression(); if (vex.isThisExpression()) { pe.setObjectExpression(THIS_EXPRESSION); return pe; } } } else if (exp instanceof ClosureExpression) { ClosureExpression ce = (ClosureExpression) exp; ce.getVariableScope().putReferencedLocalVariable((Parameter) parameter.get()); Parameter[] params = ce.getParameters(); if (params == null) { params = new Parameter[0]; } else if (params.length == 0) { params = new Parameter[]{ new Parameter(ClassHelper.OBJECT_TYPE, "it") }; } addVariablesToStack(params); ce.getCode().visit(this); varStack.removeLast(); } return super.transform(exp); } }; for (MethodNode method : parent.getMethods()) { if (!method.isStatic()) { method.setModifiers(method.getModifiers() | Opcodes.ACC_STATIC); final Parameter[] origParams = method.getParameters(); final Parameter[] newParams = new Parameter[origParams.length + 1]; Parameter p = new Parameter(targetClass, "$this"); p.setClosureSharedVariable(true); newParams[0] = p; parameter.set(p); System.arraycopy(origParams, 0, newParams, 1, origParams.length); method.setParameters(newParams); expressionTransformer.visitMethod(method); } } } private ClassNode getTargetClass(SourceUnit source, AnnotationNode annotation) { Expression value = annotation.getMember("value"); if (value == null || !(value instanceof ClassExpression)) { //noinspection ThrowableInstanceNeverThrown source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( "@groovy.lang.Category must define 'value' which is the class to apply this category to", annotation.getLineNumber(), annotation.getColumnNumber()), source)); return null; } else { ClassExpression ce = (ClassExpression) value; return ce.getType(); } } }groovy-1.8.6/src/main/org/codehaus/groovy/transform/TupleConstructorASTTransformation.java0000644001501200150120000002116711707612046031542 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.TupleConstructor; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.*; /** * Handles generation of code for the @TupleConstructor annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class TupleConstructorASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = TupleConstructor.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static Map, Expression> primitivesInitialValues; static { final ConstantExpression zero = new ConstantExpression(0); final ConstantExpression zeroDecimal = new ConstantExpression(.0); primitivesInitialValues = new HashMap, Expression>(); primitivesInitialValues.put(int.class, zero); primitivesInitialValues.put(long.class, zero); primitivesInitialValues.put(short.class, zero); primitivesInitialValues.put(byte.class, zero); primitivesInitialValues.put(char.class, zero); primitivesInitialValues.put(float.class, zeroDecimal); primitivesInitialValues.put(double.class, zeroDecimal); primitivesInitialValues.put(boolean.class, ConstantExpression.FALSE); } public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; checkNotInterface(cNode, MY_TYPE_NAME); boolean includeFields = memberHasValue(anno, "includeFields", true); boolean includeProperties = !memberHasValue(anno, "includeProperties", false); boolean includeSuperFields = memberHasValue(anno, "includeSuperFields", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean callSuper = memberHasValue(anno, "callSuper", true); boolean force = memberHasValue(anno, "force", true); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List includes = tokenize((String) getMemberValue(anno, "includes")); if (hasAnnotation(cNode, CanonicalASTTransformation.MY_TYPE)) { AnnotationNode canonical = cNode.getAnnotations(CanonicalASTTransformation.MY_TYPE).get(0); if (excludes == null || excludes.isEmpty()) excludes = tokenize((String) getMemberValue(canonical, "excludes")); if (includes == null || includes.isEmpty()) includes = tokenize((String) getMemberValue(canonical, "includes")); } if (includes != null && !includes.isEmpty() && excludes != null && !excludes.isEmpty()) { addError("Error during " + MY_TYPE_NAME + " processing: Only one of 'includes' and 'excludes' should be supplied not both.", anno); } createConstructor(cNode, includeFields, includeProperties, includeSuperFields, includeSuperProperties, callSuper, force, excludes, includes); } } public static void createConstructor(ClassNode cNode, boolean includeFields, boolean includeProperties, boolean includeSuperFields, boolean includeSuperProperties, boolean callSuper, boolean force, List excludes, List includes) { // no processing if existing constructors found List constructors = cNode.getDeclaredConstructors(); if (constructors.size() > 1 && !force) return; boolean foundEmpty = constructors.size() == 1 && constructors.get(0).getFirstStatement() == null; if (constructors.size() == 1 && !foundEmpty && !force) return; // HACK: JavaStubGenerator could have snuck in a constructor we don't want if (foundEmpty) constructors.remove(0); List superList = new ArrayList(); if (includeSuperProperties) { superList.addAll(getSuperPropertyFields(cNode.getSuperClass())); } if (includeSuperFields) { superList.addAll(getSuperNonPropertyFields(cNode.getSuperClass())); } List list = new ArrayList(); if (includeProperties) { list.addAll(getInstancePropertyFields(cNode)); } if (includeFields) { list.addAll(getInstanceNonPropertyFields(cNode)); } final List params = new ArrayList(); final List superParams = new ArrayList(); final BlockStatement body = new BlockStatement(); for (FieldNode fNode : superList) { String name = fNode.getName(); if (shouldSkip(name, excludes, includes)) continue; params.add(createParam(fNode, name)); if (callSuper) { superParams.add(new VariableExpression(name)); } else { body.addStatement(assignStatement(new PropertyExpression(VariableExpression.THIS_EXPRESSION, name), new VariableExpression(name))); } } if (callSuper) { body.addStatement(new ExpressionStatement(new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(superParams)))); } for (FieldNode fNode : list) { String name = fNode.getName(); if (shouldSkip(name, excludes, includes)) continue; params.add(createParam(fNode, name)); body.addStatement(assignStatement(new PropertyExpression(VariableExpression.THIS_EXPRESSION, name), new VariableExpression(name))); } cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, params.toArray(new Parameter[params.size()]), ClassNode.EMPTY_ARRAY, body)); } private static Parameter createParam(FieldNode fNode, String name) { Parameter param = new Parameter(fNode.getType(), name); param.setInitialExpression(providedOrDefaultInitialValue(fNode)); return param; } private static boolean shouldSkip(String name, List excludes, List includes) { return (excludes != null && excludes.contains(name)) || name.contains("$") || (includes != null && !includes.isEmpty() && !includes.contains(name)); } private static Expression providedOrDefaultInitialValue(FieldNode fNode) { Expression initialExp = fNode.getInitialExpression() != null ? fNode.getInitialExpression() : ConstantExpression.NULL; final ClassNode paramType = fNode.getType(); if (ClassHelper.isPrimitiveType(paramType) && initialExp.equals(ConstantExpression.NULL)) { initialExp = primitivesInitialValues.get(paramType.getTypeClass()); } return initialExp; } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/PackageScopeASTTransformation.java0000644001501200150120000002017611707612046030527 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.PackageScope; import groovy.transform.PackageScopeTarget; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.List; import java.util.ArrayList; /** * Handles transformation for the @PackageScope annotation. *

    * Both the deprecated groovy.lang.PackageScope and groovy.transform.PackageScope * annotations are supported. The former will be removed in a future version of Groovy. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) public class PackageScopeASTTransformation implements ASTTransformation, Opcodes { private static final Class MY_CLASS = PackageScope.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final String LEGACY_TYPE_NAME = "groovy.lang.PackageScope"; private static final Class TARGET_CLASS = groovy.transform.PackageScopeTarget.class; private static final String TARGET_CLASS_NAME = ClassHelper.make(TARGET_CLASS).getNameWithoutPackage(); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; boolean legacyMode = LEGACY_TYPE_NAME.equals(node.getClassNode().getName()); if (!MY_TYPE.equals(node.getClassNode()) && !legacyMode) return; Expression value = node.getMember("value"); if (parent instanceof ClassNode) { List targets; if (value == null) targets = Arrays.asList(legacyMode ? PackageScopeTarget.FIELDS: PackageScopeTarget.CLASS); else targets = determineTargets(value); visitClassNode((ClassNode) parent, targets); parent.getAnnotations(); } else { if (value != null) throw new RuntimeException("Error during " + MY_TYPE_NAME + " processing: " + TARGET_CLASS_NAME + " only allowed at class level."); if (parent instanceof MethodNode) { visitMethodNode((MethodNode) parent); } else if (parent instanceof FieldNode) { visitFieldNode((FieldNode) parent); } } } private void visitMethodNode(MethodNode methodNode) { if (methodNode.isSyntheticPublic()) revertVisibility(methodNode); else throw new RuntimeException("Can't use " + MY_TYPE_NAME + " for method '" + methodNode.getName() + "' which has explicit visibility."); } private void visitClassNode(ClassNode cNode, List value) { String cName = cNode.getName(); if (cNode.isInterface() && value.size() != 1 && value.get(0) != PackageScopeTarget.CLASS) { throw new RuntimeException("Error processing interface '" + cName + "'. " + MY_TYPE_NAME + " not allowed for interfaces except when targeting Class level."); } if (value.contains(groovy.transform.PackageScopeTarget.CLASS)) { if (cNode.isSyntheticPublic()) revertVisibility(cNode); else throw new RuntimeException("Can't use " + MY_TYPE_NAME + " for class '" + cNode.getName() + "' which has explicit visibility."); } if (value.contains(groovy.transform.PackageScopeTarget.METHODS)) { final List mList = cNode.getMethods(); for (MethodNode mNode : mList) { if (mNode.isSyntheticPublic()) revertVisibility(mNode); } } if (value.contains(PackageScopeTarget.FIELDS)) { final List pList = cNode.getProperties(); List foundProps = new ArrayList(); List foundNames = new ArrayList(); for (PropertyNode pNode : pList) { foundProps.add(pNode); foundNames.add(pNode.getName()); } for (PropertyNode pNode : foundProps) { pList.remove(pNode); } final List fList = cNode.getFields(); for (FieldNode fNode : fList) { if (foundNames.contains(fNode.getName())) { revertVisibility(fNode); } } } } private void visitFieldNode(FieldNode fNode) { final ClassNode cNode = fNode.getDeclaringClass(); final List pList = cNode.getProperties(); PropertyNode foundProp = null; for (PropertyNode pNode : pList) { if (pNode.getName().equals(fNode.getName())) { foundProp = pNode; break; } } if (foundProp != null) { revertVisibility(fNode); pList.remove(foundProp); } } private void revertVisibility(FieldNode fNode) { fNode.setModifiers(fNode.getModifiers() & ~ACC_PRIVATE); } private void revertVisibility(MethodNode mNode) { mNode.setModifiers(mNode.getModifiers() & ~ACC_PUBLIC); } private void revertVisibility(ClassNode cNode) { cNode.setModifiers(cNode.getModifiers() & ~ACC_PUBLIC); } private List determineTargets(Expression expr) { List list = new ArrayList(); if (expr instanceof PropertyExpression) { list.add(extractTarget((PropertyExpression) expr)); } else if (expr instanceof ListExpression) { final ListExpression expressionList = (ListExpression) expr; final List expressions = expressionList.getExpressions(); for (Expression ex : expressions) { if (ex instanceof PropertyExpression) { list.add(extractTarget((PropertyExpression) ex)); } } } return list; } private groovy.transform.PackageScopeTarget extractTarget(PropertyExpression expr) { Expression oe = expr.getObjectExpression(); if (oe instanceof ClassExpression) { ClassExpression ce = (ClassExpression) oe; if (ce.getType().getName().equals("groovy.transform.PackageScopeTarget")) { Expression prop = expr.getProperty(); if (prop instanceof ConstantExpression) { String propName = (String) ((ConstantExpression) prop).getValue(); try { return PackageScopeTarget.valueOf(propName); } catch(IllegalArgumentException iae) { /* ignore */ } } } } throw new RuntimeException("Internal error during " + MY_TYPE_NAME + " processing. Annotation parameters must be of type: " + TARGET_CLASS_NAME + "."); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ReadWriteLockASTTransformation.java0000644001501200150120000001465711707612046030710 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.WithReadLock; import groovy.transform.WithWriteLock; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Handles generation of code for the {@code @}WithReadLock and {@code @}WithWriteLock annotation.
    * This transformation adds an instance of ReentrantReadWriteLock to the class.
    * Any method annotated with @WithReadLock will obtain a read lock and release it in a finally block.
    * Any method annotated with @WithWriteLock will obtain a write lock and release it in a finally block.
    * For more information see {@link WithReadLock} and {@link WithWriteLock}
    * @author Hamlet D'Arcy */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ReadWriteLockASTTransformation implements ASTTransformation, Opcodes { private static final ClassNode READ_LOCK_TYPE = ClassHelper.make(WithReadLock.class); private static final ClassNode WRITE_LOCK_TYPE = ClassHelper.make(WithWriteLock.class); private static final ClassNode LOCK_TYPE = ClassHelper.make(ReentrantReadWriteLock.class); private static final Token ASSIGN = Token.newSymbol("=", -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; final boolean isWriteLock; if (READ_LOCK_TYPE.equals(node.getClassNode())) { isWriteLock = false; } else if (WRITE_LOCK_TYPE.equals(node.getClassNode())) { isWriteLock = true; } else { throw new RuntimeException("Internal error: expecting [" + READ_LOCK_TYPE.getName() + ", " + WRITE_LOCK_TYPE.getName() + "]" + " but got: " + node.getClassNode().getName()); } String myTypeName = "@" + node.getClassNode().getNameWithoutPackage(); Expression valueExpr = node.getMember("value"); String value = null; if (valueExpr instanceof ConstantExpression) { ConstantExpression ce = (ConstantExpression) valueExpr; Object valueObject = ce.getValue(); if (valueObject != null) value = valueObject.toString(); } if (parent instanceof MethodNode) { MethodNode mNode = (MethodNode) parent; ClassNode cNode = mNode.getDeclaringClass(); String lockExpr = determineLock(value, cNode, mNode.isStatic(), myTypeName); // get lock type final Expression lockType; if (isWriteLock) { lockType = new MethodCallExpression(new VariableExpression(lockExpr), "writeLock", ArgumentListExpression.EMPTY_ARGUMENTS); } else { lockType = new MethodCallExpression(new VariableExpression(lockExpr), "readLock", ArgumentListExpression.EMPTY_ARGUMENTS); } MethodCallExpression acquireLock = new MethodCallExpression(lockType, "lock", ArgumentListExpression.EMPTY_ARGUMENTS); MethodCallExpression releaseLock = new MethodCallExpression(lockType, "unlock", ArgumentListExpression.EMPTY_ARGUMENTS); Statement originalCode = mNode.getCode(); BlockStatement body = new BlockStatement(); body.addStatement(new ExpressionStatement(acquireLock)); body.addStatement(new TryCatchStatement(originalCode, new ExpressionStatement(releaseLock))); mNode.setCode(body); } } private String determineLock(String value, ClassNode targetClass, boolean isStatic, String myTypeName) { if (value != null && value.length() > 0 && !value.equalsIgnoreCase("$reentrantlock")) { if (targetClass.getDeclaredField(value) == null) { throw new RuntimeException("Error during " + myTypeName + " processing: lock field with name '" + value + "' not found in class " + targetClass.getName()); } if (targetClass.getDeclaredField(value).isStatic() != isStatic) { throw new RuntimeException("Error during " + myTypeName + " processing: lock field with name '" + value + "' should " + (isStatic ? "" : "not ") + "be static"); } return value; } if (isStatic) { FieldNode field = targetClass.getDeclaredField("$REENTRANTLOCK"); if (field == null) { int visibility = ACC_PRIVATE | ACC_STATIC | ACC_FINAL; targetClass.addField("$REENTRANTLOCK", visibility, LOCK_TYPE, createLockObject()); } else if (!field.isStatic()) { throw new RuntimeException("Error during " + myTypeName + " processing: $REENTRANTLOCK field must be static"); } return "$REENTRANTLOCK"; } FieldNode field = targetClass.getDeclaredField("$reentrantlock"); if (field == null) { int visibility = ACC_PRIVATE | ACC_FINAL; targetClass.addField("$reentrantlock", visibility, LOCK_TYPE, createLockObject()); } else if (field.isStatic()) { throw new RuntimeException("Error during " + myTypeName + " processing: $reentrantlock field must not be static"); } return "$reentrantlock"; } private Expression createLockObject() { return new ConstructorCallExpression(LOCK_TYPE, MethodCallExpression.NO_ARGUMENTS); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ConditionalInterruptibleASTTransformation.groovy0000644001501200150120000001356511715031256033623 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.ConditionalInterrupt import org.codehaus.groovy.ast.stmt.DoWhileStatement import org.codehaus.groovy.ast.stmt.ForStatement import org.codehaus.groovy.ast.stmt.WhileStatement import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.* import groovy.inspect.swingui.AstNodeToScriptAdapter /** * Allows "interrupt-safe" executions of scripts by adding a custom conditional * check on loops (for, while, do) and first statement of closures. By default, also adds an interrupt check * statement on the beginning of method calls. * * @see groovy.transform.ConditionalInterrupt * * @author Cedric Champeau * @author Hamlet D'Arcy * * @since 1.8.0 */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ConditionalInterruptibleASTTransformation extends AbstractInterruptibleASTTransformation { private static final ClassNode MY_TYPE = ClassHelper.make(ConditionalInterrupt) private static final String CONDITION_METHOD = 'conditionalTransform$condition'; private ClosureExpression conditionNode private MethodCallExpression conditionCallExpression private ClassNode currentClass protected ClassNode type() { return MY_TYPE; } protected void setupTransform(AnnotationNode node) { super.setupTransform(node) def member = node.getMember("value") if (!member || !(member instanceof ClosureExpression)) internalError("Expected closure value for annotation parameter 'value'. Found $member") conditionNode = member; conditionCallExpression = new MethodCallExpression(new VariableExpression('this'), CONDITION_METHOD, new ArgumentListExpression()) } protected String getErrorMessage() { 'Execution interrupted. The following condition failed: ' + convertClosureToSource(conditionNode) } public void visitClass(ClassNode type) { currentClass = type; def method = type.addMethod(CONDITION_METHOD, ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, conditionNode.code); method.synthetic = true super.visitClass(type); } protected Expression createCondition() { conditionCallExpression } @Override public void visitAnnotations(AnnotatedNode node) { // this transformation does not apply on annotation nodes // visiting could lead to stack overflows } @Override void visitField(FieldNode node) { if (!node.isStatic() && !node.isSynthetic()) { super.visitField node } } @Override void visitProperty(PropertyNode node) { if (!node.isStatic() && !node.isSynthetic()) { super.visitProperty node } } @Override public void visitClosureExpression(ClosureExpression closureExpr) { if (closureExpr == conditionNode) return // no not visit the closure from the annotation itself def code = closureExpr.code closureExpr.code = wrapBlock(code) super.visitClosureExpression closureExpr } @Override public void visitMethod(MethodNode node) { if (node.name == CONDITION_METHOD && !node.isSynthetic()) return // do not visit the generated method if (node.name == 'run' && currentClass.isScript() && node.parameters.length == 0) { // the run() method should not have the statement added, otherwise the script binding won't be set before // the condition is actually tested super.visitMethod(node) } else { if (checkOnMethodStart && !node.isSynthetic() && !node.isStatic() && !node.isAbstract()) { def code = node.code node.code = wrapBlock(code); } if (!node.isSynthetic() && !node.isStatic()) super.visitMethod(node) } } /** * Converts a ClosureExpression into the String source. * @param expression a closure * @return the source the closure was created from */ // TODO should this be moved to ClosureExpression? It also appers in AstBuilderTransformation private String convertClosureToSource(ClosureExpression expression) { if (expression == null) throw new IllegalArgumentException('Null: expression') def lineRange = (expression.lineNumber..expression.lastLineNumber) def source = lineRange.collect { def line = source.source.getLine(it, null) if (line == null) { return "Error calculating source code for expression. Trying to read line $it from ${source.source.class}" } else { if (it == expression.lastLineNumber) { line = line.substring(0, expression.lastColumnNumber - 1) } if (it == expression.lineNumber) { line = line.substring(expression.columnNumber - 1) } } return line }?.join('\n')?.trim() //restoring line breaks is important b/c of lack of semicolons if (!source.startsWith('{')) { return 'Error converting ClosureExpression into source code. ' + "Closures must start with {. Found: $source" } return source } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ASTTransformationCollectorCodeVisitor.java0000644001501200150120000001442111627206700032274 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SimpleMessage; import groovy.lang.GroovyClassLoader; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * This visitor walks the AST tree and collects references to Annotations that * are annotated themselves by {@link GroovyASTTransformation}. Each such * annotation is added. *

    * This visitor is only intended to be executed once, during the * SEMANTIC_ANALYSIS phase of compilation. * * @author Danno Ferrin (shemnon) * @author Roshan Dawrani (roshandawrani) */ public class ASTTransformationCollectorCodeVisitor extends ClassCodeVisitorSupport { private SourceUnit source; private ClassNode classNode; private GroovyClassLoader transformLoader; public ASTTransformationCollectorCodeVisitor(SourceUnit source, GroovyClassLoader transformLoader) { this.source = source; this.transformLoader = transformLoader; } protected SourceUnit getSourceUnit() { return source; } public void visitClass(ClassNode klassNode) { ClassNode oldClass = classNode; classNode = klassNode; super.visitClass(classNode); classNode = oldClass; } /** * If the annotation is annotated with {@link GroovyASTTransformation} * the annotation is added to stageVisitors at the appropriate processor visitor. * * @param node the node to process */ public void visitAnnotations(AnnotatedNode node) { super.visitAnnotations(node); for (AnnotationNode annotation : node.getAnnotations()) { Annotation transformClassAnnotation = getTransformClassAnnotation(annotation.getClassNode()); if (transformClassAnnotation == null) { // skip if there is no such annotation continue; } addTransformsToClassNode(annotation, transformClassAnnotation); } } private void addTransformsToClassNode(AnnotationNode annotation, Annotation transformClassAnnotation) { String[] transformClassNames = getTransformClassNames(transformClassAnnotation); Class[] transformClasses = getTransformClasses(transformClassAnnotation); if(transformClassNames.length == 0 && transformClasses.length == 0) { source.getErrorCollector().addError(new SimpleMessage("@GroovyASTTransformationClass in " + annotation.getClassNode().getName() + " does not specify any transform class names/classes", source)); } if(transformClassNames.length > 0 && transformClasses.length > 0) { source.getErrorCollector().addError(new SimpleMessage("@GroovyASTTransformationClass in " + annotation.getClassNode().getName() + " should specify transforms only by class names or by classes and not by both", source)); } for (String transformClass : transformClassNames) { try { Class klass = transformLoader.loadClass(transformClass, false, true, false); verifyClassAndAddTransform(annotation, klass); } catch (ClassNotFoundException e) { source.getErrorCollector().addErrorAndContinue( new SimpleMessage( "Could not find class for Transformation Processor " + transformClass + " declared by " + annotation.getClassNode().getName(), source)); } } for (Class klass : transformClasses) { verifyClassAndAddTransform(annotation, klass); } } private void verifyClassAndAddTransform(AnnotationNode annotation, Class klass) { if (ASTTransformation.class.isAssignableFrom(klass)) { classNode.addTransform(klass, annotation); } else { source.getErrorCollector().addError(new SimpleMessage("Not an ASTTransformation: " + klass.getName() + " declared by " + annotation.getClassNode().getName(), source)); } } private static Annotation getTransformClassAnnotation(ClassNode annotatedType) { if (!annotatedType.isResolved()) return null; for (Annotation ann : annotatedType.getTypeClass().getAnnotations()) { // because compiler clients are free to choose any GroovyClassLoader for // resolving ClassNodeS such as annotatedType, we have to compare by name, // and cannot cast the return value to GroovyASTTransformationClass if (ann.annotationType().getName().equals(GroovyASTTransformationClass.class.getName())){ return ann; } } return null; } private String[] getTransformClassNames(Annotation transformClassAnnotation) { try { Method valueMethod = transformClassAnnotation.getClass().getMethod("value"); return (String[]) valueMethod.invoke(transformClassAnnotation); } catch (Exception e) { source.addException(e); return new String[0]; } } private Class[] getTransformClasses(Annotation transformClassAnnotation) { try { Method classesMethod = transformClassAnnotation.getClass().getMethod("classes"); return (Class[]) classesMethod.invoke(transformClassAnnotation); } catch (Exception e) { source.addException(e); return new Class[0]; } } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/SingletonASTTransformation.java0000644001501200150120000001302011707612046030132 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.Opcodes; import java.util.List; import java.util.Iterator; /** * Handles generation of code for the @Singleton annotation * * @author Alex Tkachman */ @GroovyASTTransformation(phase= CompilePhase.CANONICALIZATION) public class SingletonASTTransformation implements ASTTransformation, Opcodes { /** * * @param nodes the ast nodes * @param source the source unit for the nodes */ public void visit(ASTNode[] nodes, SourceUnit source) { if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException( String.format( "Internal error: wrong types: %s / %s. Expected: AnnotationNode / AnnotatedNode", nodes[0].getClass(), nodes[1].getClass()) ); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (parent instanceof ClassNode) { ClassNode classNode = (ClassNode) parent; final Expression member = node.getMember("lazy"); if(member instanceof ConstantExpression && ((ConstantExpression)member).getValue().equals(true)) createLazy(classNode); else createNonLazy(classNode); } } private void createNonLazy(ClassNode classNode) { final FieldNode fieldNode = classNode.addField("instance", ACC_PUBLIC|ACC_FINAL|ACC_STATIC, classNode.getPlainNodeReference(), new ConstructorCallExpression(classNode, new ArgumentListExpression())); createConstructor(classNode, fieldNode); final BlockStatement body = new BlockStatement(); body.addStatement(new ReturnStatement(new VariableExpression(fieldNode))); classNode.addMethod("getInstance", ACC_STATIC|ACC_PUBLIC, classNode.getPlainNodeReference(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body); } private void createLazy(ClassNode classNode) { final FieldNode fieldNode = classNode.addField("instance", ACC_PRIVATE|ACC_STATIC|ACC_VOLATILE, classNode.getPlainNodeReference(), null); createConstructor(classNode, fieldNode); final BlockStatement body = new BlockStatement(); final Expression instanceExpression = new VariableExpression(fieldNode); body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(instanceExpression, Token.newSymbol("!=",-1,-1), ConstantExpression.NULL)), new ReturnStatement(instanceExpression), new SynchronizedStatement( new ClassExpression(classNode), new IfStatement( new BooleanExpression(new BinaryExpression(instanceExpression, Token.newSymbol("!=",-1,-1), ConstantExpression.NULL)), new ReturnStatement(instanceExpression), new ReturnStatement(new BinaryExpression(instanceExpression,Token.newSymbol("=",-1,-1), new ConstructorCallExpression(classNode, new ArgumentListExpression()))) ) ) )); classNode.addMethod("getInstance", ACC_STATIC|ACC_PUBLIC, classNode.getPlainNodeReference(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body); } private void createConstructor(ClassNode classNode, FieldNode field) { final List list = classNode.getDeclaredConstructors(); MethodNode found = null; for (Iterator it = list.iterator(); it.hasNext(); ) { MethodNode mn = (MethodNode) it.next(); final Parameter[] parameters = mn.getParameters(); if (parameters == null || parameters.length == 0) { found = mn; break; } } if (found == null) { final BlockStatement body = new BlockStatement(); body.addStatement(new IfStatement( new BooleanExpression(new BinaryExpression(new VariableExpression(field), Token.newSymbol("!=",-1,-1), ConstantExpression.NULL)), new ThrowStatement( new ConstructorCallExpression(ClassHelper.make(RuntimeException.class), new ArgumentListExpression( new ConstantExpression("Can't instantiate singleton " + classNode.getName() + ". Use " + classNode.getName() + ".instance" )))), new EmptyStatement())); classNode.addConstructor(new ConstructorNode(ACC_PRIVATE, body)); } } }groovy-1.8.6/src/main/org/codehaus/groovy/transform/CanonicalASTTransformation.java0000644001501200150120000000673111715031256030067 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.Canonical; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import java.util.List; import static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createEquals; import static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createHashCode; import static org.codehaus.groovy.transform.ToStringASTTransformation.createToString; import static org.codehaus.groovy.transform.TupleConstructorASTTransformation.createConstructor; /** * Handles generation of code for the @Canonical annotation. * * @author Paulo Poiati * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class CanonicalASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = Canonical.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; // TODO remove - let other validation steps pick this up if (hasAnnotation(cNode, ImmutableASTTransformation.MY_TYPE)) { addError(MY_TYPE_NAME + " class '" + cNode.getName() + "' can't also be " + ImmutableASTTransformation.MY_TYPE_NAME, parent); } checkNotInterface(cNode, MY_TYPE_NAME); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List includes = tokenize((String) getMemberValue(anno, "includes")); if (includes != null && !includes.isEmpty() && excludes != null && !excludes.isEmpty()) { addError("Error during " + MY_TYPE_NAME + " processing: Only one of 'includes' and 'excludes' should be supplied not both.", anno); } if (!hasAnnotation(cNode, TupleConstructorASTTransformation.MY_TYPE)) { createConstructor(cNode, false, true, false, false, false, false, excludes, includes); } if (!hasAnnotation(cNode, EqualsAndHashCodeASTTransformation.MY_TYPE)) { createHashCode(cNode, false, false, false, excludes, includes); createEquals(cNode, false, false, true, excludes, includes); } if (!hasAnnotation(cNode, ToStringASTTransformation.MY_TYPE)) { createToString(cNode, false, false, excludes, includes, false); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/SynchronizedASTTransformation.java0000644001501200150120000001126311707612046030656 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.Synchronized; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import java.util.Arrays; /** * Handles generation of code for the {@code @}Synchronized annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SynchronizedASTTransformation implements ASTTransformation, Opcodes { private static final Class MY_CLASS = Synchronized.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; Expression valueExpr = node.getMember("value"); String value = null; if (valueExpr instanceof ConstantExpression) { ConstantExpression ce = (ConstantExpression) valueExpr; Object valueObject = ce.getValue(); if (valueObject != null) value = valueObject.toString(); } if (parent instanceof MethodNode) { MethodNode mNode = (MethodNode) parent; ClassNode cNode = mNode.getDeclaringClass(); String lockExpr = determineLock(value, cNode, mNode.isStatic()); Statement origCode = mNode.getCode(); Statement newCode = new SynchronizedStatement(new VariableExpression(lockExpr), origCode); mNode.setCode(newCode); } } private String determineLock(String value, ClassNode cNode, boolean isStatic) { if (value != null && value.length() > 0 && !value.equalsIgnoreCase("$lock")) { if (cNode.getDeclaredField(value) == null) { throw new RuntimeException("Error during " + MY_TYPE_NAME + " processing: lock field with name '" + value + "' not found in class " + cNode.getName()); } if (cNode.getDeclaredField(value).isStatic() != isStatic) { throw new RuntimeException("Error during " + MY_TYPE_NAME + " processing: lock field with name '" + value + "' should " + (isStatic ? "" : "not ") + "be static"); } return value; } if (isStatic) { FieldNode field = cNode.getDeclaredField("$LOCK"); if (field == null) { int visibility = ACC_PRIVATE | ACC_STATIC | ACC_FINAL; cNode.addField("$LOCK", visibility, ClassHelper.OBJECT_TYPE, zeroLengthObjectArray()); } else if (!field.isStatic()) { throw new RuntimeException("Error during " + MY_TYPE_NAME + " processing: $LOCK field must be static"); } return "$LOCK"; } FieldNode field = cNode.getDeclaredField("$lock"); if (field == null) { int visibility = ACC_PRIVATE | ACC_FINAL; cNode.addField("$lock", visibility, ClassHelper.OBJECT_TYPE, zeroLengthObjectArray()); } else if (field.isStatic()) { throw new RuntimeException("Error during " + MY_TYPE_NAME + " processing: $lock field must not be static"); } return "$lock"; } private Expression zeroLengthObjectArray() { return new ArrayExpression(ClassHelper.OBJECT_TYPE, null, Arrays.asList((Expression)new ConstantExpression(0))); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/GroovyASTTransformationClass.java0000644001501200150120000000323111627206700030443 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This is an annotation on some item that indicates that * an associated transform classes should be executed. As of * Groovy 1.6 the only valid target is the annotation type. * * Each of the class names in the value must be annotated with * {@link GroovyASTTransformation}. * * It is a compile time error to specify a {@link GroovyASTTransformationClass} * that is not accessible at compile time. It need not be available at runtime. * * @author Danno Ferrin (shemnon) * @author Roshan Dawrani (roshandawrani) */ @Retention(RetentionPolicy.RUNTIME) // in the future the target will be wider than annotations, but for now it is just on annotations @Target(ElementType.ANNOTATION_TYPE) public @interface GroovyASTTransformationClass { String[] value() default {}; Class[] classes() default {}; } groovy-1.8.6/src/main/org/codehaus/groovy/transform/ASTTransformationVisitor.java0000644001501200150120000003707111715031256027640 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.*; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.WarningMessage; import groovy.lang.GroovyClassLoader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.*; /** * This class handles the invocation of the ASTAnnotationTransformation * when it is encountered by a tree walk. One instance of each exists * for each phase of the compilation it applies to. Before invocation the *

    * {@link org.codehaus.groovy.transform.ASTTransformationCollectorCodeVisitor} will add a list * of annotations that this visitor should be concerned about. All other * annotations are ignored, whether or not they are GroovyASTTransformation * annotated or not. *

    * A Two-pass method is used. First all candidate annotations are added to a * list then the transformations are called on those collected annotations. * This is done to avoid concurrent modification exceptions during the AST tree * walk and allows the transformations to alter any portion of the AST tree. * Hence annotations that are added in this phase will not be processed as * transformations. They will only be handled in later phases (and then only * if the type was in the AST prior to any AST transformations being run * against it). * * @author Danno Ferrin (shemnon) */ public final class ASTTransformationVisitor extends ClassCodeVisitorSupport { private CompilePhase phase; private SourceUnit source; private List targetNodes; private Map> transforms; private Map, ASTTransformation> transformInstances; private static CompilationUnit compUnit; private static Set globalTransformNames = new HashSet(); private ASTTransformationVisitor(CompilePhase phase) { this.phase = phase; } protected SourceUnit getSourceUnit() { return source; } /** * Main loop entry. *

    * First, it delegates to the super visitClass so we can collect the * relevant annotations in an AST tree walk. *

    * Second, it calls the visit method on the transformation for each relevant * annotation found. * * @param classNode the class to visit */ public void visitClass(ClassNode classNode) { // only descend if we have annotations to look for Map, Set> baseTransforms = classNode.getTransforms(phase); if (!baseTransforms.isEmpty()) { transformInstances = new HashMap, ASTTransformation>(); for (Class transformClass : baseTransforms.keySet()) { try { transformInstances.put(transformClass, transformClass.newInstance()); } catch (InstantiationException e) { source.getErrorCollector().addError( new SimpleMessage( "Could not instantiate Transformation Processor " + transformClass , //+ " declared by " + annotation.getClassNode().getName(), source)); } catch (IllegalAccessException e) { source.getErrorCollector().addError( new SimpleMessage( "Could not instantiate Transformation Processor " + transformClass , //+ " declared by " + annotation.getClassNode().getName(), source)); } } // invert the map, is now one to many transforms = new HashMap>(); for (Map.Entry, Set> entry : baseTransforms.entrySet()) { for (ASTNode node : entry.getValue()) { List list = transforms.get(node); if (list == null) { list = new ArrayList(); transforms.put(node, list); } list.add(transformInstances.get(entry.getKey())); } } targetNodes = new LinkedList(); // first pass, collect nodes super.visitClass(classNode); // second pass, call visit on all of the collected nodes for (ASTNode[] node : targetNodes) { for (ASTTransformation snt : transforms.get(node[0])) { snt.visit(node, source); } } } } /** * Adds the annotation to the internal target list if a match is found. * * @param node the node to be processed */ public void visitAnnotations(AnnotatedNode node) { super.visitAnnotations(node); for (AnnotationNode annotation : node.getAnnotations()) { if (transforms.containsKey(annotation)) { targetNodes.add(new ASTNode[]{annotation, node}); } } } public static void addPhaseOperations(final CompilationUnit compilationUnit) { addGlobalTransforms(compilationUnit); compilationUnit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(source, compilationUnit.getTransformLoader()); collector.visitClass(classNode); } }, Phases.SEMANTIC_ANALYSIS); for (CompilePhase phase : CompilePhase.values()) { final ASTTransformationVisitor visitor = new ASTTransformationVisitor(phase); switch (phase) { case INITIALIZATION: case PARSING: case CONVERSION: // with transform detection alone these phases are inaccessible, so don't add it break; default: compilationUnit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { visitor.source = source; visitor.visitClass(classNode); } }, phase.getPhaseNumber()); break; } } } public static void addGlobalTransformsAfterGrab() { doAddGlobalTransforms(compUnit, false); } public static void addGlobalTransforms(CompilationUnit compilationUnit) { compUnit = compilationUnit; doAddGlobalTransforms(compilationUnit, true); } private static void doAddGlobalTransforms(CompilationUnit compilationUnit, boolean isFirstScan) { GroovyClassLoader transformLoader = compilationUnit.getTransformLoader(); Map transformNames = new LinkedHashMap(); try { Enumeration globalServices = transformLoader.getResources("META-INF/services/org.codehaus.groovy.transform.ASTTransformation"); while (globalServices.hasMoreElements()) { URL service = globalServices.nextElement(); String className; BufferedReader svcIn = new BufferedReader(new InputStreamReader(service.openStream())); try { className = svcIn.readLine(); } catch (IOException ioe) { compilationUnit.getErrorCollector().addError(new SimpleMessage( "IOException reading the service definition at " + service.toExternalForm() + " because of exception " + ioe.toString(), null)); continue; } while (className != null) { if (!className.startsWith("#") && className.length() > 0) { if (transformNames.containsKey(className)) { if (!service.equals(transformNames.get(className))) { compilationUnit.getErrorCollector().addWarning( WarningMessage.POSSIBLE_ERRORS, "The global transform for class " + className + " is defined in both " + transformNames.get(className).toExternalForm() + " and " + service.toExternalForm() + " - the former definition will be used and the latter ignored.", null, null); } } else { transformNames.put(className, service); } } try { className = svcIn.readLine(); } catch (IOException ioe) { compilationUnit.getErrorCollector().addError(new SimpleMessage( "IOException reading the service definition at " + service.toExternalForm() + " because of exception " + ioe.toString(), null)); //noinspection UnnecessaryContinue continue; } } } } catch (IOException e) { //FIXME the warning message will NPE with what I have :( compilationUnit.getErrorCollector().addError(new SimpleMessage( "IO Exception attempting to load global transforms:" + e.getMessage(), null)); } try { Class.forName("java.lang.annotation.Annotation"); // test for 1.5 JVM } catch (Exception e) { // we failed, notify the user StringBuffer sb = new StringBuffer(); sb.append("Global ASTTransformations are not enabled in retro builds of groovy.\n"); sb.append("The following transformations will be ignored:"); for (Map.Entry entry : transformNames.entrySet()) { sb.append('\t'); sb.append(entry.getKey()); sb.append('\n'); } compilationUnit.getErrorCollector().addWarning(new WarningMessage( WarningMessage.POSSIBLE_ERRORS, sb.toString(), null, null)); return; } // record the transforms found in the first scan, so that in the 2nd scan, phase operations // can be added for only for new transforms that have come in if(isFirstScan) { for (Map.Entry entry : transformNames.entrySet()) { globalTransformNames.add(entry.getKey()); } addPhaseOperationsForGlobalTransforms(compilationUnit, transformNames, isFirstScan); } else { Iterator> it = transformNames.entrySet().iterator(); while(it.hasNext()) { Map.Entry entry = it.next(); if(!globalTransformNames.add(entry.getKey())) { // phase operations for this transform class have already been added before, so remove from current scan cycle it.remove(); } } addPhaseOperationsForGlobalTransforms(compilationUnit, transformNames, isFirstScan); } } private static void addPhaseOperationsForGlobalTransforms(CompilationUnit compilationUnit, Map transformNames, boolean isFirstScan) { GroovyClassLoader transformLoader = compilationUnit.getTransformLoader(); for (Map.Entry entry : transformNames.entrySet()) { try { Class gTransClass = transformLoader.loadClass(entry.getKey(), false, true, false); //no inspection unchecked GroovyASTTransformation transformAnnotation = (GroovyASTTransformation) gTransClass.getAnnotation(GroovyASTTransformation.class); if (transformAnnotation == null) { compilationUnit.getErrorCollector().addWarning(new WarningMessage( WarningMessage.POSSIBLE_ERRORS, "Transform Class " + entry.getKey() + " is specified as a global transform in " + entry.getValue().toExternalForm() + " but it is not annotated by " + GroovyASTTransformation.class.getName() + " the global tranform associated with it may fail and cause the compilation to fail.", null, null)); continue; } if (ASTTransformation.class.isAssignableFrom(gTransClass)) { final ASTTransformation instance = (ASTTransformation)gTransClass.newInstance(); CompilationUnit.SourceUnitOperation suOp = new CompilationUnit.SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { instance.visit(new ASTNode[] {source.getAST()}, source); } }; if(isFirstScan) { compilationUnit.addPhaseOperation(suOp, transformAnnotation.phase().getPhaseNumber()); } else { compilationUnit.addNewPhaseOperation(suOp, transformAnnotation.phase().getPhaseNumber()); } } else { compilationUnit.getErrorCollector().addError(new SimpleMessage( "Transform Class " + entry.getKey() + " specified at " + entry.getValue().toExternalForm() + " is not an ASTTransformation.", null)); } } catch (Exception e) { compilationUnit.getErrorCollector().addError(new SimpleMessage( "Could not instantiate global transform class " + entry.getKey() + " specified at " + entry.getValue().toExternalForm() + " because of exception " + e.toString(), null)); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/AbstractInterruptibleASTTransformation.java0000644001501200150120000001740311707612046032515 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.List; /** * Base class for AST Transformations which will automatically throw an {@link InterruptedException} when * some conditions are met. * * @author Cedric Champeau * @author Hamlet D'Arcy * @since 1.8.0 */ public abstract class AbstractInterruptibleASTTransformation extends ClassCodeVisitorSupport implements ASTTransformation, Opcodes { protected static final String CHECK_METHOD_START_MEMBER = "checkOnMethodStart"; protected static final String PROPAGATE_TO_COMPILE_UNIT = "applyToAllClasses"; protected static final String THROWN_EXCEPTION_TYPE = "thrown"; protected SourceUnit source; protected boolean checkOnMethodStart; protected boolean applyToAllClasses; protected ClassNode thrownExceptionType; protected SourceUnit getSourceUnit() { return source; } protected abstract ClassNode type(); /** * Subclasses should implement this method to set the condition of the interruption statement */ protected abstract Expression createCondition(); /** * Subclasses should implement this method to provide good error resolution. */ protected abstract String getErrorMessage(); protected void setupTransform(AnnotationNode node) { checkOnMethodStart = getBooleanAnnotationParameter(node, CHECK_METHOD_START_MEMBER, true); applyToAllClasses = getBooleanAnnotationParameter(node, PROPAGATE_TO_COMPILE_UNIT, true); thrownExceptionType = getClassAnnotationParameter(node, THROWN_EXCEPTION_TYPE, ClassHelper.make(InterruptedException.class)); } public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { internalError("Expecting [AnnotationNode, AnnotatedClass] but got: " + Arrays.asList(nodes)); } this.source = source; AnnotationNode node = (AnnotationNode) nodes[0]; AnnotatedNode annotatedNode = (AnnotatedNode) nodes[1]; if (!type().equals(node.getClassNode())) { internalError("Transformation called from wrong annotation: " + node.getClassNode().getName()); } setupTransform(node); // should be limited to the current SourceUnit or propagated to the whole CompilationUnit final ModuleNode tree = source.getAST(); if (applyToAllClasses) { // guard every class and method defined in this script if (tree != null) { final List classes = tree.getClasses(); for (ClassNode classNode : classes) { visitClass(classNode); } } } else if (annotatedNode instanceof ClassNode) { // only guard this particular class this.visitClass((ClassNode) annotatedNode); } else { // only guard the script class if (tree != null) { final List classes = tree.getClasses(); for (ClassNode classNode : classes) { if (classNode.isScript()) { visitClass(classNode); } } } } } protected static boolean getBooleanAnnotationParameter(AnnotationNode node, String parameterName, boolean defaultValue) { Expression member = node.getMember(parameterName); if (member != null) { if (member instanceof ConstantExpression) { try { return DefaultGroovyMethods.asType(((ConstantExpression) member).getValue(), Boolean.class); } catch (Exception e) { internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member"); } } else { internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member"); } } return defaultValue; } protected static ClassNode getClassAnnotationParameter(AnnotationNode node, String parameterName, ClassNode defaultValue) { Expression member = node.getMember(parameterName); if (member != null) { if (member instanceof ClassExpression) { try { return member.getType(); } catch (Exception e) { internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member"); } } else { internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member"); } } return defaultValue; } protected static void internalError(String message) { throw new GroovyBugError("Internal error: " + message); } /** * @return Returns the interruption check statement. */ protected Statement createInterruptStatement() { return new IfStatement( new BooleanExpression( createCondition() ), new ThrowStatement( new ConstructorCallExpression(thrownExceptionType, new ArgumentListExpression(new ConstantExpression(getErrorMessage()))) ), new EmptyStatement() ); } /** * Takes a statement and wraps it into a block statement which first element is the interruption check statement. * * @param statement the statement to be wrapped * @return a {@link BlockStatement block statement} which first element is for checking interruption, and the * second one the statement to be wrapped. */ protected final Statement wrapBlock(Statement statement) { BlockStatement stmt = new BlockStatement(); stmt.addStatement(createInterruptStatement()); stmt.addStatement(statement); return stmt; } @Override public final void visitForLoop(ForStatement forStatement) { visitLoop(forStatement); super.visitForLoop(forStatement); } /** * Shortcut method which avoids duplicating code for every type of loop. * Actually wraps the loopBlock of different types of loop statements. */ private void visitLoop(LoopingStatement loopStatement) { Statement statement = loopStatement.getLoopBlock(); loopStatement.setLoopBlock(wrapBlock(statement)); } @Override public final void visitDoWhileLoop(DoWhileStatement doWhileStatement) { visitLoop(doWhileStatement); super.visitDoWhileLoop(doWhileStatement); } @Override public final void visitWhileLoop(WhileStatement whileStatement) { visitLoop(whileStatement); super.visitWhileLoop(whileStatement); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/NewifyASTTransformation.java0000644001501200150120000003023711707612046027442 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.lang.Newify; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import java.util.HashSet; import java.util.List; import java.util.Arrays; import java.util.Set; /** * Handles generation of code for the @Newify annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class NewifyASTTransformation extends ClassCodeExpressionTransformer implements ASTTransformation { private static final ClassNode MY_TYPE = ClassHelper.make(Newify.class); private static final String MY_NAME = MY_TYPE.getNameWithoutPackage(); private static final String BASE_BAD_PARAM_ERROR = "Error during @" + MY_NAME + " processing. Annotation parameter must be a class or list of classes but found "; private SourceUnit source; private ListExpression classesToNewify; private DeclarationExpression candidate; private boolean auto; public void visit(ASTNode[] nodes, SourceUnit source) { this.source = source; if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { internalError("Expecting [AnnotationNode, AnnotatedClass] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) { internalError("Transformation called from wrong annotation: " + node.getClassNode().getName()); } boolean autoFlag = determineAutoFlag(node.getMember("auto")); Expression value = node.getMember("value"); if (parent instanceof ClassNode) { newifyClass((ClassNode) parent, autoFlag, determineClasses(value, false)); } else if (parent instanceof MethodNode || parent instanceof FieldNode) { newifyMethodOrField(parent, autoFlag, determineClasses(value, false)); } else if (parent instanceof DeclarationExpression) { newifyDeclaration((DeclarationExpression) parent, autoFlag, determineClasses(value, true)); } } private void newifyDeclaration(DeclarationExpression de, boolean autoFlag, ListExpression list) { ClassNode cNode = de.getDeclaringClass(); candidate = de; final ListExpression oldClassesToNewify = classesToNewify; final boolean oldAuto = auto; classesToNewify = list; auto = autoFlag; super.visitClass(cNode); classesToNewify = oldClassesToNewify; auto = oldAuto; } private boolean determineAutoFlag(Expression autoExpr) { return !(autoExpr instanceof ConstantExpression && ((ConstantExpression) autoExpr).getValue().equals(false)); } /** allow non-strict mode in scripts because parsing not complete at that point */ private ListExpression determineClasses(Expression expr, boolean searchSourceUnit) { ListExpression list = new ListExpression(); if (expr instanceof ClassExpression) { list.addExpression(expr); } else if (expr instanceof VariableExpression && searchSourceUnit) { VariableExpression ve = (VariableExpression) expr; ClassNode fromSourceUnit = getSourceUnitClass(ve); if (fromSourceUnit != null) { ClassExpression found = new ClassExpression(fromSourceUnit); found.setSourcePosition(ve); list.addExpression(found); } else { addError(BASE_BAD_PARAM_ERROR + "an unresolvable reference to '" + ve.getName() + "'.", expr); } } else if (expr instanceof ListExpression) { list = (ListExpression) expr; final List expressions = list.getExpressions(); for (int i = 0; i < expressions.size(); i++) { Expression next = expressions.get(i); if (next instanceof VariableExpression && searchSourceUnit) { VariableExpression ve = (VariableExpression) next; ClassNode fromSourceUnit = getSourceUnitClass(ve); if (fromSourceUnit != null) { ClassExpression found = new ClassExpression(fromSourceUnit); found.setSourcePosition(ve); expressions.set(i, found); } else { addError(BASE_BAD_PARAM_ERROR + "a list containing an unresolvable reference to '" + ve.getName() + "'.", next); } } else if (!(next instanceof ClassExpression)) { addError(BASE_BAD_PARAM_ERROR + "a list containing type: " + next.getType().getName() + ".", next); } } checkDuplicateNameClashes(list); } else if (expr != null) { addError(BASE_BAD_PARAM_ERROR + "a type: " + expr.getType().getName() + ".", expr); } return list; } private ClassNode getSourceUnitClass(VariableExpression ve) { List classes = source.getAST().getClasses(); for (ClassNode classNode : classes) { if (classNode.getNameWithoutPackage().equals(ve.getName())) return classNode; } return null; } public Expression transform(Expression expr) { if (expr == null) return null; if (expr instanceof MethodCallExpression && candidate == null) { MethodCallExpression mce = (MethodCallExpression) expr; Expression args = transform(mce.getArguments()); if (isNewifyCandidate(mce)) { Expression transformed = transformMethodCall(mce, args); transformed.setSourcePosition(mce); return transformed; } Expression method = transform(mce.getMethod()); Expression object = transform(mce.getObjectExpression()); MethodCallExpression transformed = new MethodCallExpression(object, method, args); transformed.setSourcePosition(mce); return transformed; } else if (expr instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) expr; if (de == candidate) { candidate = null; Expression left = de.getLeftExpression(); Expression right = transform(de.getRightExpression()); DeclarationExpression newDecl = new DeclarationExpression(left, de.getOperation(), right); newDecl.addAnnotations(de.getAnnotations()); return newDecl; } return de; } return expr.transformExpression(this); } private void newifyClass(ClassNode cNode, boolean autoFlag, ListExpression list) { String cName = cNode.getName(); if (cNode.isInterface()) { addError("Error processing interface '" + cName + "'. @" + MY_NAME + " not allowed for interfaces.", cNode); } final ListExpression oldClassesToNewify = classesToNewify; final boolean oldAuto = auto; classesToNewify = list; auto = autoFlag; super.visitClass(cNode); classesToNewify = oldClassesToNewify; auto = oldAuto; } private void newifyMethodOrField(AnnotatedNode parent, boolean autoFlag, ListExpression list) { final ListExpression oldClassesToNewify = classesToNewify; final boolean oldAuto = auto; checkClassLevelClashes(list); checkAutoClash(autoFlag, parent); classesToNewify = list; auto = autoFlag; if (parent instanceof FieldNode) { super.visitField((FieldNode) parent); } else { super.visitMethod((MethodNode) parent); } classesToNewify = oldClassesToNewify; auto = oldAuto; } private void checkDuplicateNameClashes(ListExpression list) { final Set seen = new HashSet(); @SuppressWarnings("unchecked") final List classes = (List)list.getExpressions(); for (ClassExpression ce : classes) { final String name = ce.getType().getNameWithoutPackage(); if (seen.contains(name)) { addError("Duplicate name '" + name + "' found during @" + MY_NAME + " processing.", ce); } seen.add(name); } } private void checkAutoClash(boolean autoFlag, AnnotatedNode parent) { if (auto && !autoFlag) { addError("Error during @" + MY_NAME + " processing. The 'auto' flag can't be false at " + "method/constructor/field level if it is true at the class level.", parent); } } private void checkClassLevelClashes(ListExpression list) { @SuppressWarnings("unchecked") final List classes = (List)list.getExpressions(); for (ClassExpression ce : classes) { final String name = ce.getType().getNameWithoutPackage(); if (findClassWithMatchingBasename(name)) { addError("Error during @" + MY_NAME + " processing. Class '" + name + "' can't appear at " + "method/constructor/field level if it already appears at the class level.", ce); } } } private boolean findClassWithMatchingBasename(String nameWithoutPackage) { if (classesToNewify == null) return false; @SuppressWarnings("unchecked") final List classes = (List)classesToNewify.getExpressions(); for (ClassExpression ce : classes) { if (ce.getType().getNameWithoutPackage().equals(nameWithoutPackage)) { return true; } } return false; } private boolean isNewifyCandidate(MethodCallExpression mce) { return mce.getObjectExpression() == VariableExpression.THIS_EXPRESSION || (auto && isNewMethodStyle(mce)); } private boolean isNewMethodStyle(MethodCallExpression mce) { final Expression obj = mce.getObjectExpression(); final Expression meth = mce.getMethod(); return (obj instanceof ClassExpression && meth instanceof ConstantExpression && ((ConstantExpression) meth).getValue().equals("new")); } private Expression transformMethodCall(MethodCallExpression mce, Expression args) { ClassNode classType; if (isNewMethodStyle(mce)) { classType = mce.getObjectExpression().getType(); } else { classType = findMatchingCandidateClass(mce); } if (classType != null) { return new ConstructorCallExpression(classType, args); } // set the args as they might have gotten Newify transformed GROOVY-3491 mce.setArguments(args); return mce; } private ClassNode findMatchingCandidateClass(MethodCallExpression mce) { if (classesToNewify == null) return null; @SuppressWarnings("unchecked") List classes = (List)classesToNewify.getExpressions(); for (ClassExpression ce : classes) { final ClassNode type = ce.getType(); if (type.getNameWithoutPackage().equals(mce.getMethodAsString())) { return type; } } return null; } private void internalError(String message) { throw new GroovyBugError("Internal error: " + message); } protected SourceUnit getSourceUnit() { return source; } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy0000644001501200150120000002551311707612046032421 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.TimedInterrupt import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.syntax.Token import org.codehaus.groovy.syntax.Types import org.objectweb.asm.Opcodes import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.* import org.codehaus.groovy.ast.stmt.* /** * Allows "interrupt-safe" executions of scripts by adding timer expiration * checks on loops (for, while, do) and first statement of closures. By default, also adds an interrupt check * statement on the beginning of method calls. * * @see groovy.transform.ThreadInterrupt * * @author Cedric Champeau * @author Hamlet D'Arcy * * @since 1.8.0 */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class TimedInterruptibleASTTransformation implements ASTTransformation { private static final ClassNode MY_TYPE = ClassHelper.make(TimedInterrupt.class) private static final String CHECK_METHOD_START_MEMBER = 'checkOnMethodStart' private static final String PROPAGATE_TO_COMPILE_UNIT = 'applyToAllClasses' private static final String THROWN_EXCEPTION_TYPE = "thrown" public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { internalError("Expecting [AnnotationNode, AnnotatedClass] but got: ${Arrays.asList(nodes)}") } AnnotationNode node = nodes[0] AnnotatedNode annotatedNode = nodes[1] if (!MY_TYPE.equals(node.getClassNode())) { internalError("Transformation called from wrong annotation: $node.classNode.name") } def checkOnMethodStart = getConstantAnnotationParameter(node, CHECK_METHOD_START_MEMBER, Boolean.TYPE, true) def applyToAllClasses = getConstantAnnotationParameter(node, PROPAGATE_TO_COMPILE_UNIT, Boolean.TYPE, true) def maximum = getConstantAnnotationParameter(node, 'value', Long.TYPE, Long.MAX_VALUE) def thrown = AbstractInterruptibleASTTransformation.getClassAnnotationParameter(node, THROWN_EXCEPTION_TYPE, ClassHelper.make(TimeoutException)) Expression unit = node.getMember('unit') ?: new PropertyExpression(new ClassExpression(ClassHelper.make(TimeUnit)), "SECONDS") // should be limited to the current SourceUnit or propagated to the whole CompilationUnit if (applyToAllClasses) { // guard every class and method defined in this script source.getAST()?.classes?.each { ClassNode it -> // DO NOT inline this code. It has state that must not persist between calls def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, maximum, unit, thrown) visitor.visitClass(it) } } else if (annotatedNode instanceof ClassNode) { // only guard this particular class // DO NOT inline this code. It has state that must not persist between calls def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, maximum, unit, thrown) visitor.visitClass annotatedNode } else { // only guard the script class source.getAST()?.classes?.each { ClassNode it -> if (it.isScript()) { // DO NOT inline this code. It has state that must not persist between calls def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, maximum, unit, thrown) visitor.visitClass(it) } } } } static def getConstantAnnotationParameter(AnnotationNode node, String parameterName, Class type, defaultValue) { def member = node.getMember(parameterName) if (member) { if (member instanceof ConstantExpression) { try { return member.value.asType(type) } catch (e) { internalError("Expecting boolean value for ${parameterName} annotation parameter. Found $member") } } else { internalError("Expecting boolean value for ${parameterName} annotation parameter. Found $member") } } return defaultValue } private static void internalError(String message) { throw new RuntimeException("Internal error: $message") } private static class TimedInterruptionVisitor extends ClassCodeVisitorSupport { final private SourceUnit source final private boolean checkOnMethodStart final private boolean applyToAllClasses private FieldNode expireTimeField = null private FieldNode startTimeField = null private final Expression unit private final maximum private final ClassNode thrown TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, maximum, unit, thrown) { this.source = source this.checkOnMethodStart = checkOnMethodStart this.applyToAllClasses = applyToAllClasses this.unit = unit this.maximum = maximum this.thrown = thrown } /** * @return Returns the interruption check statement. */ final def createInterruptStatement() { new IfStatement( new BooleanExpression( new BinaryExpression( new VariableExpression('TimedInterrupt$expireTime'), new Token(Types.COMPARE_LESS_THAN, '<', -1, -1), new StaticMethodCallExpression( ClassHelper.make(System), 'nanoTime', ArgumentListExpression.EMPTY_ARGUMENTS) ) ), new ThrowStatement( new ConstructorCallExpression(thrown, new ArgumentListExpression( new BinaryExpression( new ConstantExpression( 'Execution timed out after ' + maximum + ' units. Start time: '), new Token(Types.PLUS, '+', -1, -1), new VariableExpression('TimedInterrupt$startTime'), ) ) ) ), new EmptyStatement() ) } /** * Takes a statement and wraps it into a block statement which first element is the interruption check statement. * @param statement the statement to be wrapped * @return a {@link BlockStatement block statement} which first element is for checking interruption, and the * second one the statement to be wrapped. */ private def wrapBlock(statement) { def stmt = new BlockStatement(); stmt.addStatement(createInterruptStatement()); stmt.addStatement(statement); stmt } @Override void visitClass(ClassNode node) { expireTimeField = node.addField('TimedInterrupt$expireTime', Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE, ClassHelper.long_TYPE, new BinaryExpression( new StaticMethodCallExpression(ClassHelper.make(System), 'nanoTime', ArgumentListExpression.EMPTY_ARGUMENTS), new Token(Types.PLUS, '+', -1, -1), new MethodCallExpression( new PropertyExpression( new ClassExpression(ClassHelper.make(TimeUnit)), 'NANOSECONDS' ), 'convert', new ArgumentListExpression( new ConstantExpression(maximum), unit ) ) ) ); expireTimeField.synthetic = true startTimeField = node.addField('TimedInterrupt$startTime', Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE, ClassHelper.make(Date), new ConstructorCallExpression(ClassHelper.make(Date), ArgumentListExpression.EMPTY_ARGUMENTS) ) startTimeField.synthetic = true // force these fields to be initialized first node.fields.remove(expireTimeField) node.fields.remove(startTimeField) node.fields.add(0, startTimeField) node.fields.add(0, expireTimeField) super.visitClass node } @Override public void visitClosureExpression(ClosureExpression closureExpr) { def code = closureExpr.code if (code instanceof BlockStatement) { code.statements.add(0, createInterruptStatement()) } else { closureExpr.code = wrapBlock(code) } super.visitClosureExpression closureExpr } @Override void visitField(FieldNode node) { if (!node.isStatic() && !node.isSynthetic()) { super.visitField node } } @Override void visitProperty(PropertyNode node) { if (!node.isStatic() && !node.isSynthetic()) { super.visitProperty node } } /** * Shortcut method which avoids duplicating code for every type of loop. * Actually wraps the loopBlock of different types of loop statements. */ private def visitLoop(loopStatement) { def statement = loopStatement.loopBlock loopStatement.loopBlock = wrapBlock(statement) } @Override public void visitForLoop(ForStatement forStatement) { visitLoop(forStatement) super.visitForLoop(forStatement) } @Override public void visitDoWhileLoop(final DoWhileStatement doWhileStatement) { visitLoop(doWhileStatement) super.visitDoWhileLoop(doWhileStatement) } @Override public void visitWhileLoop(final WhileStatement whileStatement) { visitLoop(whileStatement) super.visitWhileLoop(whileStatement) } @Override public void visitMethod(MethodNode node) { if (checkOnMethodStart && !node.isSynthetic() && !node.isStatic() && !node.isAbstract()) { def code = node.code node.code = wrapBlock(code); } if (!node.isSynthetic() && !node.isStatic()) { super.visitMethod(node) } } protected SourceUnit getSourceUnit() { return source; } } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/AbstractASTTransformUtil.java0000644001501200150120000002524311707612046027550 0ustar miguelmiguel/* * Copyright 2008-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.List; public abstract class AbstractASTTransformUtil implements Opcodes { private static final Token COMPARE_EQUAL = Token.newSymbol(Types.COMPARE_EQUAL, -1, -1); private static final Token COMPARE_NOT_EQUAL = Token.newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1); private static final Token INSTANCEOF = Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); public static boolean hasDeclaredMethod(ClassNode cNode, String name, int argsCount) { List ms = cNode.getDeclaredMethods(name); for (MethodNode m : ms) { Parameter[] paras = m.getParameters(); if (paras != null && paras.length == argsCount) { return true; } } return false; } public static Statement returnFalseIfWrongType(ClassNode cNode, Expression other) { return new IfStatement( notEqualClasses(cNode, other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } public static Statement returnFalseIfNotInstanceof(ClassNode cNode, Expression other) { return new IfStatement( isInstanceof(cNode, other), new EmptyStatement(), new ReturnStatement(ConstantExpression.FALSE) ); } public static IfStatement returnFalseIfNull(Expression other) { return new IfStatement( equalsNullExpr(other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } public static IfStatement returnTrueIfIdentical(Expression self, Expression other) { return new IfStatement( identicalExpr(self, other), new ReturnStatement(ConstantExpression.TRUE), new EmptyStatement() ); } @Deprecated public static Statement returnFalseIfPropertyNotEqual(FieldNode fNode, Expression other) { return returnFalseIfFieldNotEqual(fNode, other); } public static Statement returnFalseIfPropertyNotEqual(PropertyNode pNode, Expression other) { return new IfStatement( notEqualsPropertyExpr(pNode, other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } public static Statement returnFalseIfFieldNotEqual(FieldNode fNode, Expression other) { return new IfStatement( notEqualsFieldExpr(fNode, other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } public static List getInstanceProperties(ClassNode cNode) { final List result = new ArrayList(); for (PropertyNode pNode : cNode.getProperties()) { if (!pNode.isStatic()) { result.add(pNode); } } return result; } public static List getInstancePropertyFields(ClassNode cNode) { final List result = new ArrayList(); for (PropertyNode pNode : cNode.getProperties()) { if (!pNode.isStatic()) { result.add(pNode.getField()); } } return result; } public static List getInstanceNonPropertyFields(ClassNode cNode) { final List result = new ArrayList(); for (FieldNode fNode : cNode.getFields()) { if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) { result.add(fNode); } } return result; } public static List getSuperPropertyFields(ClassNode cNode) { final List result; if (cNode == ClassHelper.OBJECT_TYPE) { result = new ArrayList(); } else { result = getSuperPropertyFields(cNode.getSuperClass()); } for (PropertyNode pNode : cNode.getProperties()) { if (!pNode.isStatic()) { result.add(pNode.getField()); } } return result; } public static List getSuperNonPropertyFields(ClassNode cNode) { final List result; if (cNode == ClassHelper.OBJECT_TYPE) { result = new ArrayList(); } else { result = getSuperNonPropertyFields(cNode.getSuperClass()); } for (FieldNode fNode : cNode.getFields()) { if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) { result.add(fNode); } } return result; } public static Statement assignStatement(Expression fieldExpr, Expression value) { return new ExpressionStatement(assignExpr(fieldExpr, value)); } private static Expression assignExpr(Expression expression, Expression value) { return new BinaryExpression(expression, ASSIGN, value); } public static BooleanExpression isInstanceOf(Expression objectExpression, ClassNode cNode) { return new BooleanExpression(new BinaryExpression(objectExpression, INSTANCEOF, new ClassExpression(cNode))); } public static BooleanExpression equalsNullExpr(Expression argExpr) { return new BooleanExpression(new BinaryExpression(argExpr, COMPARE_EQUAL, ConstantExpression.NULL)); } public static BooleanExpression isZeroExpr(Expression expr) { return new BooleanExpression(new BinaryExpression(expr, COMPARE_EQUAL, new ConstantExpression(0))); } private static BooleanExpression notEqualsFieldExpr(FieldNode fNode, Expression other) { final Expression fieldExpr = new VariableExpression(fNode); final Expression otherExpr = new PropertyExpression(other, fNode.getName()); return new BooleanExpression(new BinaryExpression(fieldExpr, COMPARE_NOT_EQUAL, otherExpr)); } private static BooleanExpression notEqualsPropertyExpr(PropertyNode pNode, Expression other) { String getterName = "get" + Verifier.capitalize(pNode.getName()); Expression selfGetter = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, getterName, MethodCallExpression.NO_ARGUMENTS); Expression otherGetter = new MethodCallExpression(other, getterName, MethodCallExpression.NO_ARGUMENTS); return new BooleanExpression(new BinaryExpression(selfGetter, COMPARE_NOT_EQUAL, otherGetter)); } private static BooleanExpression identicalExpr(Expression self, Expression other) { return new BooleanExpression(new MethodCallExpression(self, "is", new ArgumentListExpression(other))); } private static BooleanExpression notEqualClasses(ClassNode cNode, Expression other) { return new BooleanExpression(new BinaryExpression(new ClassExpression(cNode), COMPARE_NOT_EQUAL, new MethodCallExpression(other, "getClass", MethodCallExpression.NO_ARGUMENTS))); } public static BooleanExpression isInstanceof(ClassNode cNode, Expression other) { return new BooleanExpression(new BinaryExpression(other, INSTANCEOF, new ClassExpression(cNode))); } public static boolean isOrImplements(ClassNode fieldType, ClassNode interfaceType) { return fieldType.equals(interfaceType) || fieldType.implementsInterface(interfaceType); } public static BooleanExpression isTrueExpr(Expression argExpr) { return new BooleanExpression(new BinaryExpression(argExpr, COMPARE_EQUAL, ConstantExpression.TRUE)); } public static BooleanExpression isOneExpr(Expression expr) { return new BooleanExpression(new BinaryExpression(expr, COMPARE_EQUAL, new ConstantExpression(1))); } public static Statement safeExpression(Expression fieldExpr, Expression expression) { return new IfStatement( equalsNullExpr(fieldExpr), new ExpressionStatement(fieldExpr), new ExpressionStatement(expression)); } public static Statement createConstructorStatementDefault(FieldNode fNode) { final String name = fNode.getName(); final Expression fieldExpr = new PropertyExpression(VariableExpression.THIS_EXPRESSION, name); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression value = findArg(name); return new IfStatement( equalsNullExpr(value), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, initExpr)), assignStatement(fieldExpr, value)); } public static Expression findArg(String argName) { return new PropertyExpression(new VariableExpression("args"), argName); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/InheritConstructorsASTTransformation.java0000644001501200150120000001264011714271434032232 0ustar miguelmiguel/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.InheritConstructors; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Handles generation of code for the {@code @}InheritConstructors annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class InheritConstructorsASTTransformation implements ASTTransformation, Opcodes { private static final Class MY_CLASS = InheritConstructors.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; if (parent instanceof ClassNode) { processClass((ClassNode) parent, source); } } private void processClass(ClassNode cNode, SourceUnit source) { if (cNode.isInterface()) { addError("Error processing interface '" + cNode.getName() + "'. " + MY_TYPE_NAME + " only allowed for classes.", cNode, source); return; } ClassNode sNode = cNode.getSuperClass(); List superAnnotations = sNode.getAnnotations(MY_TYPE); if (superAnnotations.size() == 1) { // We need @InheritConstructors from parent classes processed first // so force that order here. The transformation is benign on an already // processed node so processing twice in any order won't matter bar // a very small time penalty. processClass(sNode, source); } for (ConstructorNode cn : sNode.getDeclaredConstructors()) { addConstructorUnlessAlreadyExisting(cNode, cn); } } private void addConstructorUnlessAlreadyExisting(ClassNode classNode, ConstructorNode consNode) { Parameter[] origParams = consNode.getParameters(); if (consNode.isPrivate()) return; Parameter[] params = new Parameter[origParams.length]; List args = new ArrayList(); for (int i = 0; i < origParams.length; i++) { Parameter p = origParams[i]; params[i] = p.hasInitialExpression() ? new Parameter(p.getType(), p.getName(), p.getInitialExpression()) : new Parameter(p.getType(), p.getName()); args.add(new VariableExpression(p.getName(), p.getType())); } if (isExisting(classNode, params)) return; BlockStatement body = new BlockStatement(); body.addStatement(new ExpressionStatement( new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(args)))); classNode.addConstructor(consNode.getModifiers(), params, consNode.getExceptions(), body); } private boolean isExisting(ClassNode classNode, Parameter[] params) { for (ConstructorNode consNode : classNode.getDeclaredConstructors()) { if (matchingTypes(params, consNode.getParameters())) { return true; } } return false; } private boolean matchingTypes(Parameter[] params, Parameter[] existingParams) { if (params.length != existingParams.length) return false; for (int i = 0; i < params.length; i++) { if (!params[i].getType().equals(existingParams[i].getType())) { return false; } } return true; } private void addError(String msg, ASTNode expr, SourceUnit source) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source) ); } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/FieldASTTransformation.java0000644001501200150120000001700611713765676027242 0ustar miguelmiguel/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.Field; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.classgen.VariableScopeVisitor; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Handles transformation for the @Field annotation. * * @author Paul King * @author Cedric Champeau */ @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) public class FieldASTTransformation extends ClassCodeExpressionTransformer implements ASTTransformation, Opcodes { private static final Class MY_CLASS = Field.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode ASTTRANSFORM_TYPE = ClassHelper.make(GroovyASTTransformationClass.class); private SourceUnit sourceUnit; private DeclarationExpression candidate; private boolean insideScriptBody; private String variableName; private FieldNode fieldNode; private ClosureExpression currentClosure; public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; if (parent instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) parent; ClassNode cNode = de.getDeclaringClass(); if (!cNode.isScript()) { addError("Error: annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent); return; } candidate = de; // GROOVY-4548: temp fix to stop CCE until proper support is added if (de.isMultipleAssignmentDeclaration()) { addError("Error: annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", parent); return; } VariableExpression ve = de.getVariableExpression(); variableName = ve.getName(); // set owner null here, it will be updated by addField fieldNode = new FieldNode(variableName, ve.getModifiers(), ve.getType(), null, de.getRightExpression()); fieldNode.setSourcePosition(de); cNode.addField(fieldNode); // GROOVY-4833 : annotations that are not Groovy transforms should be transferred to the generated field final List annotations = de.getAnnotations(); for (AnnotationNode annotation : annotations) { final ClassNode annotationClassNode = annotation.getClassNode(); if (annotationClassNode.getAnnotations(ASTTRANSFORM_TYPE).isEmpty()) { fieldNode.addAnnotation(annotation); } } super.visitClass(cNode); // GROOVY-5207 So that Closures can see newly added fields // (not super efficient for a very large class with many @Fields but we chose simplicity // and understandability of this solution over more complex but efficient alternatives) VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(cNode); } } @Override public Expression transform(Expression expr) { if (expr == null) return null; if (expr instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) expr; if (de.getLeftExpression() == candidate.getLeftExpression()) { if (insideScriptBody) { // TODO make EmptyExpression work // partially works but not if only thing in script // return EmptyExpression.INSTANCE; return new ConstantExpression(null); } addError("Error: annotation " + MY_TYPE_NAME + " can only be used within a Script body.", expr); return expr; } } else if (insideScriptBody && expr instanceof VariableExpression && currentClosure != null) { VariableExpression ve = (VariableExpression) expr; if (ve.getName().equals(variableName)) { // we may only check the variable name because the Groovy compiler // already fails if a variable with the same name already exists in the scope. // this means that a closure cannot shadow a class variable ve.setAccessedVariable(fieldNode); final VariableScope variableScope = currentClosure.getVariableScope(); final Iterator iterator = variableScope.getReferencedLocalVariablesIterator(); while (iterator.hasNext()) { Variable next = iterator.next(); if (next.getName().equals(variableName)) iterator.remove(); } variableScope.putReferencedClassVariable(fieldNode); return ve; } } return expr.transformExpression(this); } @Override public void visitClosureExpression(final ClosureExpression expression) { ClosureExpression old = currentClosure; currentClosure = expression; super.visitClosureExpression(expression); currentClosure = old; } @Override public void visitMethod(MethodNode node) { Boolean oldInsideScriptBody = insideScriptBody; if (node.isScriptBody()) insideScriptBody = true; super.visitMethod(node); insideScriptBody = oldInsideScriptBody; } @Override public void visitExpressionStatement(ExpressionStatement es) { Expression exp = es.getExpression(); if (exp instanceof BinaryExpression) { exp.visit(this); } super.visitExpressionStatement(es); } protected SourceUnit getSourceUnit() { return sourceUnit; } } groovy-1.8.6/src/main/org/codehaus/groovy/transform/AutoCloneASTTransformation.java0000644001501200150120000002547711707612046030104 0ustar miguelmiguel/* * Copyright 2008-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.transform.AutoClone; import groovy.transform.AutoCloneStyle; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.VariableScope; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.assignStatement; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceNonPropertyFields; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstancePropertyFields; import static org.codehaus.groovy.transform.AbstractASTTransformUtil.isInstanceOf; /** * Handles generation of code for the @AutoClone annotation. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class AutoCloneASTTransformation extends AbstractASTTransformation { static final Class MY_CLASS = AutoClone.class; static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode CLONEABLE_TYPE = ClassHelper.make(Cloneable.class); private static final ClassNode BAOS_TYPE = ClassHelper.make(ByteArrayOutputStream.class); private static final ClassNode BAIS_TYPE = ClassHelper.make(ByteArrayInputStream.class); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(anno.getClassNode())) return; if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; checkNotInterface(cNode, MY_TYPE_NAME); cNode.addInterface(CLONEABLE_TYPE); boolean includeFields = memberHasValue(anno, "includeFields", true); AutoCloneStyle style = getStyle(anno, "style"); List excludes = tokenize((String) getMemberValue(anno, "excludes")); List list = getInstancePropertyFields(cNode); if (includeFields) { list.addAll(getInstanceNonPropertyFields(cNode)); } if (style == null) style = AutoCloneStyle.CLONE; switch (style) { case COPY_CONSTRUCTOR: createCloneCopyConstructor(cNode, list, excludes); break; case SERIALIZATION: createCloneSerialization(cNode, list, excludes); break; case CLONE: createClone(cNode, list, excludes); break; } } } private void createCloneSerialization(ClassNode cNode, List list, List excludes) { final BlockStatement body = new BlockStatement(); // def baos = new ByteArrayOutputStream() final Expression baos = new VariableExpression("baos"); body.addStatement(new ExpressionStatement(new DeclarationExpression(baos, ASSIGN, new ConstructorCallExpression(BAOS_TYPE, MethodCallExpression.NO_ARGUMENTS)))); // baos.withObjectOutputStream{ it.writeObject(this) } BlockStatement writeClosureCode = new BlockStatement(); final Expression it = new VariableExpression("it"); writeClosureCode.addStatement(new ExpressionStatement(new MethodCallExpression(it, "writeObject", VariableExpression.THIS_EXPRESSION))); ClosureExpression writeClosure = new ClosureExpression(new Parameter[]{}, writeClosureCode); writeClosure.setVariableScope(new VariableScope()); body.addStatement(new ExpressionStatement(new MethodCallExpression(baos, "withObjectOutputStream", new ArgumentListExpression(writeClosure)))); // def bais = new ByteArrayInputStream(baos.toByteArray()) final Expression bais = new VariableExpression("bais"); ConstructorCallExpression bytes = new ConstructorCallExpression(BAIS_TYPE, new TupleExpression(new MethodCallExpression(baos, "toByteArray", MethodCallExpression.NO_ARGUMENTS))); body.addStatement(new ExpressionStatement(new DeclarationExpression(bais, ASSIGN, bytes))); // return bais.withObjectInputStream(getClass().classLoader){ it.readObject() } BlockStatement readClosureCode = new BlockStatement(); readClosureCode.addStatement(new ExpressionStatement(new MethodCallExpression(it, "readObject", MethodCallExpression.NO_ARGUMENTS))); ClosureExpression readClosure = new ClosureExpression(new Parameter[]{}, readClosureCode); readClosure.setVariableScope(new VariableScope()); Expression klass = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "getClass", MethodCallExpression.NO_ARGUMENTS); Expression classLoader = new MethodCallExpression(klass, "getClassLoader", MethodCallExpression.NO_ARGUMENTS); Expression result = new MethodCallExpression(bais, "withObjectInputStream", new ArgumentListExpression(classLoader, readClosure)); body.addStatement(new ReturnStatement(result)); ClassNode[] exceptions = {ClassHelper.make(CloneNotSupportedException.class)}; cNode.addMethod("clone", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, new Parameter[0], exceptions, body); } private void createCloneCopyConstructor(ClassNode cNode, List list, List excludes) { BlockStatement initBody = new BlockStatement(); if (cNode.getDeclaredConstructors().size() == 0) { // add no-arg constructor initBody.addStatement(new EmptyStatement()); cNode.addConstructor(ACC_PUBLIC, new Parameter[0], ClassNode.EMPTY_ARRAY, initBody); initBody = new BlockStatement(); } Parameter initParam = new Parameter(cNode, "other"); final Expression other = new VariableExpression(initParam); boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE; if (hasParent) { initBody.addStatement(new ExpressionStatement(new ConstructorCallExpression(ClassNode.SUPER, other))); } for (FieldNode fieldNode : list) { String name = fieldNode.getName(); if (excludes.contains(name)) continue; PropertyExpression direct = new PropertyExpression(other, name); Expression cloned = new MethodCallExpression(direct, "clone", MethodCallExpression.NO_ARGUMENTS); Expression to = new PropertyExpression(VariableExpression.THIS_EXPRESSION, name); Statement assignCloned = assignStatement(to, cloned); Statement assignDirect = assignStatement(to, direct); initBody.addStatement(new IfStatement(isInstanceOf(direct, CLONEABLE_TYPE), assignCloned, assignDirect)); } ClassNode[] exceptions = {ClassHelper.make(CloneNotSupportedException.class)}; cNode.addConstructor(ACC_PROTECTED, new Parameter[]{initParam}, ClassNode.EMPTY_ARRAY, initBody); final BlockStatement cloneBody = new BlockStatement(); cloneBody.addStatement(new ExpressionStatement(new ConstructorCallExpression(cNode, new ArgumentListExpression(VariableExpression.THIS_EXPRESSION)))); cNode.addMethod("clone", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, new Parameter[0], exceptions, cloneBody); } private void createClone(ClassNode cNode, List list, List excludes) { final BlockStatement body = new BlockStatement(); final Expression result = new VariableExpression("_result"); final Expression clone = new MethodCallExpression(VariableExpression.SUPER_EXPRESSION, "clone", MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new DeclarationExpression(result, ASSIGN, clone))); for (FieldNode fieldNode : list) { if (excludes.contains(fieldNode.getName())) continue; Expression fieldExpr = new VariableExpression(fieldNode); Expression from = new MethodCallExpression(fieldExpr, "clone", MethodCallExpression.NO_ARGUMENTS); Expression to = new PropertyExpression(result, fieldNode.getName()); Statement doClone = assignStatement(to, from); Statement doNothing = new EmptyStatement(); body.addStatement(new IfStatement(isInstanceOf(fieldExpr, CLONEABLE_TYPE), doClone, doNothing)); } body.addStatement(new ReturnStatement(result)); ClassNode[] exceptions = {ClassHelper.make(CloneNotSupportedException.class)}; cNode.addMethod("clone", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, new Parameter[0], exceptions, body); } private AutoCloneStyle getStyle(AnnotationNode node, String name) { final Expression member = node.getMember(name); if (member != null && member instanceof PropertyExpression) { PropertyExpression prop = (PropertyExpression) member; Expression oe = prop.getObjectExpression(); if (oe instanceof ClassExpression) { ClassExpression ce = (ClassExpression) oe; if (ce.getType().getName().equals("groovy.transform.AutoCloneStyle")) { return AutoCloneStyle.valueOf(prop.getPropertyAsString()); } } } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/0000755001501200150120000000000011715031256020576 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ant/RootLoaderRef.java0000644001501200150120000001027111707612044024152 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.codehaus.groovy.tools.LoaderConfiguration; import org.codehaus.groovy.tools.RootLoader; /** * Sets the RootLoader as reference. * Reexecution of this task will set a new instance of RootLoader for * the reference. * * arguments: *

      *
    • ref
    • *
    • classpath
    • *
    * * all arguments are required. * * As ant requires an AntClassLoader as reference, this will create a RootLoader * and set an AntClassLoader as child and stored in the reference. The AntClassLoader * instance will not have a classpath nor will it have access to the classpath somehow, * all loading is done by the RootLoader parent. To avoid problems with loading classes * multiple times and using them at the same time, this task will filter out the ant jars * and the commons-logging jars. This only works if the ant jars are starting with "ant-" and * the logging jar starts with "commons-logging-". * * This was needed because if ant wants to access a task argument that uses for example a Path * it look for a matching method which includes a matching class. But two classes of the same name * with different classloaders are different, so ant would not be able to find the method. * * @see org.codehaus.groovy.tools.RootLoader * @author Jochen Theodorou * @version $Revision$ */ public class RootLoaderRef extends MatchingTask { private String name; private Path taskClasspath; /** * sets the name of the reference which should store the Loader */ public void setRef(String n){ name = n; } public void execute() throws BuildException { if (taskClasspath==null || taskClasspath.size()==0) { throw new BuildException("no classpath given"); } Project project = getProject(); AntClassLoader loader = new AntClassLoader(makeRoot(),true); project.addReference(name,loader); } private RootLoader makeRoot() { String[] list = taskClasspath.list(); LoaderConfiguration lc = new LoaderConfiguration(); for (int i=0; iJason Dillon */ public class UberCompileTask extends Task { private final LoggingHelper log = new LoggingHelper(this); private Path src; private File destdir; private Path classpath; private GenStubsAdapter genStubsTask; private GroovycAdapter groovycTask; private JavacAdapter javacTask; public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } public void setSrcdir(final Path dir) { assert dir != null; if (src == null) { src = dir; } else { src.append(dir); } } public Path getSrcdir() { return src; } public void setDestdir(final File dir) { assert dir != null; this.destdir = dir; } public void setClasspath(final Path path) { assert path != null; if (classpath == null) { classpath = path; } else { classpath.append(path); } } public Path getClasspath() { return classpath; } public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } public void setClasspathRef(final Reference r) { assert r != null; createClasspath().setRefid(r); } public GenStubsAdapter createGeneratestubs() { if (genStubsTask == null) { genStubsTask = new GenStubsAdapter(); genStubsTask.setProject(getProject()); } return genStubsTask; } public GroovycAdapter createGroovyc() { if (groovycTask == null) { groovycTask = new GroovycAdapter(); groovycTask.setProject(getProject()); } return groovycTask; } public JavacAdapter createJavac() { if (javacTask == null) { javacTask = new JavacAdapter(); javacTask.setProject(getProject()); } return javacTask; } protected void validate() throws BuildException { if (src == null) { throw new BuildException("Missing attribute: srcdir (or one or more nested elements).", getLocation()); } if (destdir == null) { throw new BuildException("Missing attribute: destdir", getLocation()); } if (!destdir.exists()) { throw new BuildException("Destination directory does not exist: " + destdir, getLocation()); } } public void execute() throws BuildException { validate(); FileSet fileset; GenStubsAdapter genstubs = createGeneratestubs(); genstubs.classpath = classpath; genstubs.src = src; if (genstubs.destdir == null) { genstubs.destdir = createTempDir(); } fileset = genstubs.getFileSet(); if (!fileset.hasPatterns()) { genstubs.createInclude().setName("**/*.java"); genstubs.createInclude().setName("**/*.groovy"); } JavacAdapter javac = createJavac(); javac.setSrcdir(src); javac.setDestdir(destdir); javac.setClasspath(classpath); fileset = javac.getFileSet(); if (!fileset.hasPatterns()) { javac.createInclude().setName("**/*.java"); } // Include the stubs in the Javac compilation javac.createSrc().createPathElement().setLocation(genstubs.destdir); GroovycAdapter groovyc = createGroovyc(); groovyc.classpath = classpath; groovyc.src = src; groovyc.destdir = destdir; // // HACK: For now force all classes to compile, so we pick up stub changes // groovyc.force = true; fileset = groovyc.getFileSet(); if (!fileset.hasPatterns()) { groovyc.createInclude().setName("**/*.groovy"); } // Invoke each task in the right order genstubs.execute(); javac.execute(); groovyc.execute(); } private File createTempDir() { try { File dir = File.createTempFile("groovy-", "stubs"); dir.delete(); dir.mkdirs(); return dir; } catch (IOException e) { throw new BuildException(e, getLocation()); } } // // Nested task adapters // private class GenStubsAdapter extends GenerateStubsTask { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":genstubs"; } } private class JavacAdapter extends Javac { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":javac"; } } private class GroovycAdapter extends GroovycTask { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":groovyc"; } } }groovy-1.8.6/src/main/org/codehaus/groovy/ant/Groovyc.java0000644001501200150120000011247011715031256023076 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyResourceLoader; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.RuntimeConfigurable; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.SourceFileScanner; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.SourceExtensionHandler; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.tools.ErrorReporter; import org.codehaus.groovy.tools.FileSystemCompiler; import org.codehaus.groovy.tools.RootLoader; import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** * Compiles Groovy source files. This task can take the following arguments: *
      *
    • srcdir
    • *
    • destdir
    • *
    • classpath
    • *
    • encoding
    • *
    • verbose
    • *
    • failonerror
    • *
    • includeantruntime
    • *
    • includejavaruntime
    • *
    • memoryInitialSize
    • *
    • memoryMaximumSize
    • *
    • fork
    • *
    • stacktrace
    • *
    • stubdir
    • *
    * Of these arguments, the srcdir and destdir are required. *

    *

    When this task executes, it will recursively scan srcdir and destdir looking for Groovy source files * to compile. This task makes its compile decision based on timestamp.

    *

    *

    Based heavily on the Javac implementation in Ant.

    * * @author James Strachan * @author Hein Meling * @author Russel Winder * @author Danno Ferrin * @version $Revision$ */ public class Groovyc extends MatchingTask { private final LoggingHelper log = new LoggingHelper(this); private Path src; private File destDir; private Path compileClasspath; private Path compileSourcepath; private String encoding; private boolean stacktrace = false; private boolean verbose = false; private boolean includeAntRuntime = true; private boolean includeJavaRuntime = false; private boolean fork = false; private File forkJDK; private String memoryInitialSize; private String memoryMaximumSize; private String scriptExtension = "*.groovy"; private String targetBytecode = null; protected boolean failOnError = true; protected boolean listFiles = false; protected File[] compileList = new File[0]; private String updatedProperty; private String errorProperty; private boolean taskSuccess = true; // assume the best private boolean includeDestClasses = true; protected CompilerConfiguration configuration; private Javac javac; private boolean jointCompilation; private List temporaryFiles = new ArrayList(2); private File stubDir; private boolean keepStubs; private Set scriptExtensions = new LinkedHashSet(); /** * Adds a path for source compilation. * * @return a nested src element. */ public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } /** * Recreate src. * * @return a nested src element. */ protected Path recreateSrc() { src = null; return createSrc(); } /** * Set the source directories to find the source Java files. * * @param srcDir the source directories as a path */ public void setSrcdir(Path srcDir) { if (src == null) { src = srcDir; } else { src.append(srcDir); } } /** * Gets the source dirs to find the source java files. * * @return the source directories as a path */ public Path getSrcdir() { return src; } /** * Set the extension to use when searching for Groovy source files. * Accepts extensions in the form *.groovy, .groovy or groovy * * @param scriptExtension the extension of Groovy source files */ public void setScriptExtension(String scriptExtension) { if (scriptExtension.startsWith("*.")) { this.scriptExtension = scriptExtension; } else if (scriptExtension.startsWith(".")) { this.scriptExtension = "*" + scriptExtension; } else { this.scriptExtension = "*." + scriptExtension; } } /** * Get the extension to use when searching for Groovy source files. * * @return the extension of Groovy source files */ public String getScriptExtension() { return scriptExtension; } /** * Sets the bytecode compatibility mode * * @param version the bytecode compatibility mode */ public void setTargetBytecode(String version) { if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) { this.targetBytecode = version; } } /** * Retrieves the compiler bytecode compatibility mode. * * @return bytecode compatibility mode. Can be either 1.5 or 1.4. */ public String getTargetBytecode() { return this.targetBytecode; } /** * Set the destination directory into which the Java source * files should be compiled. * * @param destDir the destination director */ public void setDestdir(File destDir) { this.destDir = destDir; } /** * Gets the destination directory into which the java source files * should be compiled. * * @return the destination directory */ public File getDestdir() { return destDir; } /** * Set the sourcepath to be used for this compilation. * * @param sourcepath the source path */ public void setSourcepath(Path sourcepath) { if (compileSourcepath == null) { compileSourcepath = sourcepath; } else { compileSourcepath.append(sourcepath); } } /** * Gets the sourcepath to be used for this compilation. * * @return the source path */ public Path getSourcepath() { return compileSourcepath; } /** * Adds a path to sourcepath. * * @return a sourcepath to be configured */ public Path createSourcepath() { if (compileSourcepath == null) { compileSourcepath = new Path(getProject()); } return compileSourcepath.createPath(); } /** * Adds a reference to a source path defined elsewhere. * * @param r a reference to a source path */ public void setSourcepathRef(Reference r) { createSourcepath().setRefid(r); } /** * Set the classpath to be used for this compilation. * * @param classpath an Ant Path object containing the compilation classpath. */ public void setClasspath(Path classpath) { if (compileClasspath == null) { compileClasspath = classpath; } else { compileClasspath.append(classpath); } } /** * Gets the classpath to be used for this compilation. * * @return the class path */ public Path getClasspath() { return compileClasspath; } /** * Adds a path to the classpath. * * @return a class path to be configured */ public Path createClasspath() { if (compileClasspath == null) { compileClasspath = new Path(getProject()); } return compileClasspath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. * * @param r a reference to a classpath */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } /** * If true, list the source files being handed off to the compiler. * Default is false. * * @param list if true list the source files */ public void setListfiles(boolean list) { listFiles = list; } /** * Get the listfiles flag. * * @return the listfiles flag */ public boolean getListfiles() { return listFiles; } /** * Indicates whether the build will continue * even if there are compilation errors; defaults to true. * * @param fail if true halt the build on failure */ public void setFailonerror(boolean fail) { failOnError = fail; } /** * @param proceed inverse of failonerror */ public void setProceed(boolean proceed) { failOnError = !proceed; } /** * Gets the failonerror flag. * * @return the failonerror flag */ public boolean getFailonerror() { return failOnError; } /** * The initial size of the memory for the underlying VM * if javac is run externally; ignored otherwise. * Defaults to the standard VM memory setting. * (Examples: 83886080, 81920k, or 80m) * * @param memoryInitialSize string to pass to VM */ public void setMemoryInitialSize(String memoryInitialSize) { this.memoryInitialSize = memoryInitialSize; } /** * Gets the memoryInitialSize flag. * * @return the memoryInitialSize flag */ public String getMemoryInitialSize() { return memoryInitialSize; } /** * The maximum size of the memory for the underlying VM * if javac is run externally; ignored otherwise. * Defaults to the standard VM memory setting. * (Examples: 83886080, 81920k, or 80m) * * @param memoryMaximumSize string to pass to VM */ public void setMemoryMaximumSize(String memoryMaximumSize) { this.memoryMaximumSize = memoryMaximumSize; } /** * Gets the memoryMaximumSize flag. * * @return the memoryMaximumSize flag */ public String getMemoryMaximumSize() { return memoryMaximumSize; } /** * Sets the file encoding for generated files. * * @param encoding the file encoding to be used */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Returns the encoding to be used when creating files. * * @return the file encoding to use */ public String getEncoding() { return encoding; } /** * Enable verbose compiling which will display which files * are being compiled. Default is false. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Gets the verbose flag. * * @return the verbose flag */ public boolean getVerbose() { return verbose; } /** * If true, includes Ant's own classpath in the classpath. Default is true. * If setting to false and using groovyc in conjunction with AntBuilder * you might need to explicitly add the Groovy jar(s) to the groovyc * classpath using a nested classpath task. * * @param include if true, includes Ant's own classpath in the classpath */ public void setIncludeantruntime(boolean include) { includeAntRuntime = include; } /** * Gets whether or not the ant classpath is to be included in the classpath. * * @return whether or not the ant classpath is to be included in the classpath */ public boolean getIncludeantruntime() { return includeAntRuntime; } /** * If true, includes the Java runtime libraries in the classpath. Default is false. * * @param include if true, includes the Java runtime libraries in the classpath */ public void setIncludejavaruntime(boolean include) { includeJavaRuntime = include; } /** * Gets whether or not the java runtime should be included in this * task's classpath. * * @return the includejavaruntime attribute */ public boolean getIncludejavaruntime() { return includeJavaRuntime; } /** * If true forks the Groovy compiler. Default is false. * * @param f "true|false|on|off|yes|no" */ public void setFork(boolean f) { fork = f; } /** * The JDK Home to use when forked. * * @param home the java.home value to use, default is the current JDK's home */ public void setJavaHome(File home) { forkJDK = home; } /** * The property to set on compilation success. * This property will not be set if the compilation * fails, or if there are no files to compile. * * @param updatedProperty the property name to use. */ public void setUpdatedProperty(String updatedProperty) { this.updatedProperty = updatedProperty; } /** * The property to set on compilation failure. * This property will be set if the compilation * fails. * * @param errorProperty the property name to use. */ public void setErrorProperty(String errorProperty) { this.errorProperty = errorProperty; } /** * This property controls whether to include the * destination classes directory in the classpath * given to the compiler. * The default value is "true". * * @param includeDestClasses the value to use. */ public void setIncludeDestClasses(boolean includeDestClasses) { this.includeDestClasses = includeDestClasses; } /** * Get the value of the includeDestClasses property. * * @return the value. */ public boolean isIncludeDestClasses() { return includeDestClasses; } /** * Get the result of the groovyc task (success or failure). * * @return true if compilation succeeded, or * was not necessary, false if the compilation failed. */ public boolean getTaskSuccess() { return taskSuccess; } /* public void setJointCompilationOptions(String options) { String[] args = StringHelper.tokenizeUnquoted(options); evalCompilerFlags(args); } */ /** * Add the configured nested javac task if present to initiate joint compilation. */ public void addConfiguredJavac(final Javac javac) { this.javac = javac; jointCompilation = true; } /** * Enable compiler to report stack trace information if a problem occurs * during compilation. Default is false. */ public void setStacktrace(boolean stacktrace) { this.stacktrace = stacktrace; } /** * Executes the task. * * @throws BuildException if an error occurs */ public void execute() throws BuildException { checkParameters(); resetFileLists(); loadRegisteredScriptExtensions(); if (javac != null) jointCompilation = true; // scan source directories and dest directory to build up // compile lists String[] list = src.list(); for (String filename : list) { File file = getProject().resolveFile(filename); if (!file.exists()) { throw new BuildException("srcdir \"" + file.getPath() + "\" does not exist!", getLocation()); } DirectoryScanner ds = this.getDirectoryScanner(file); String[] files = ds.getIncludedFiles(); scanDir(file, destDir != null ? destDir : file, files); } compile(); if (updatedProperty != null && taskSuccess && compileList.length != 0) { getProject().setNewProperty(updatedProperty, "true"); } } /** * Clear the list of files to be compiled and copied.. */ protected void resetFileLists() { compileList = new File[0]; scriptExtensions = new LinkedHashSet(); } /** * Scans the directory looking for source files to be compiled. * The results are returned in the class variable compileList * * @param srcDir The source directory * @param destDir The destination directory * @param files An array of filenames */ protected void scanDir(File srcDir, File destDir, String[] files) { GlobPatternMapper m = new GlobPatternMapper(); SourceFileScanner sfs = new SourceFileScanner(this); File[] newFiles; for (String extension : getScriptExtensions()) { m.setFrom("*." + extension); m.setTo("*.class"); newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); addToCompileList(newFiles); } if (jointCompilation) { m.setFrom("*.java"); m.setTo("*.class"); newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); addToCompileList(newFiles); } } protected void addToCompileList(File[] newFiles) { if (newFiles.length > 0) { File[] newCompileList = new File[compileList.length + newFiles.length]; System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); System.arraycopy(newFiles, 0, newCompileList, compileList.length, newFiles.length); compileList = newCompileList; } } /** * Gets the list of files to be compiled. * * @return the list of files as an array */ public File[] getFileList() { return compileList; } protected void checkParameters() throws BuildException { if (src == null) { throw new BuildException("srcdir attribute must be set!", getLocation()); } if (src.size() == 0) { throw new BuildException("srcdir attribute must be set!", getLocation()); } if (destDir != null && !destDir.isDirectory()) { throw new BuildException("destination directory \"" + destDir + "\" does not exist or is not a directory", getLocation()); } if (encoding != null && !Charset.isSupported(encoding)) { throw new BuildException("encoding \"" + encoding + "\" not supported."); } } protected void compile() { try { if (compileList.length > 0) { log("Compiling " + compileList.length + " source file" + (compileList.length == 1 ? "" : "s") + (destDir != null ? " to " + destDir : "")); if (listFiles) { for (File srcFile : compileList) { log(srcFile.getAbsolutePath()); } } Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject()); // extract joint options, some get pushed up... List jointOptions = new ArrayList(); if (jointCompilation) { RuntimeConfigurable rc = javac.getRuntimeConfigurableWrapper(); for (Iterator i = rc.getAttributeMap().entrySet().iterator(); i.hasNext();) { final Map.Entry e = (Map.Entry) i.next(); final String key = e.getKey().toString(); final String value = getProject().replaceProperties(e.getValue().toString()); if (key.contains("debug")) { String level = ""; if (javac.getDebugLevel() != null) { level = ":" + javac.getDebugLevel(); } jointOptions.add("-Fg" + level); } else if (key.contains("debugLevel")) { // ignore, taken care of in debug } else if ((key.contains("nowarn")) || (key.contains("verbose")) || (key.contains("deprecation"))) { // false is default, so something to do only in true case if ("on".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase("value")) jointOptions.add("-F" + key); } else if (key.contains("classpath")) { classpath.add(javac.getClasspath()); } else if ((key.contains("depend")) || (key.contains("extdirs")) || (key.contains("encoding")) || (key.contains("source")) || (key.contains("target")) || (key.contains("verbose"))) { // TODO remove extra verbose? jointOptions.add("-J" + key + "=" + value); } else { log("The option " + key + " cannot be set on the contained element. The option will be ignored", Project.MSG_WARN); } // includes? excludes? } // ant's supports nested elements (there can be multiple of them) // for additional options to be passed to javac. Enumeration children = rc.getChildren(); while (children.hasMoreElements()) { RuntimeConfigurable childrc = (RuntimeConfigurable) children.nextElement(); if (childrc.getElementTag().equals("compilerarg")) { for (Iterator i = childrc.getAttributeMap().entrySet().iterator(); i.hasNext();) { final Map.Entry e = (Map.Entry) i.next(); final String key = e.getKey().toString(); if (key.equals("value")) { final String value = getProject().replaceProperties(e.getValue().toString()); StringTokenizer st = new StringTokenizer(value, " "); while (st.hasMoreTokens()) { String optionStr = st.nextToken(); String replaced = optionStr.replace("-X", "-FX"); if(optionStr == replaced) { replaced = optionStr.replace("-W", "-FW"); // GROOVY-5063 } jointOptions.add(replaced); } } } } } } String separator = System.getProperty("file.separator"); List commandLineList = new ArrayList(); if (fork) { String javaHome; if (forkJDK != null) { javaHome = forkJDK.getPath(); } else { javaHome = System.getProperty("java.home"); } if (includeAntRuntime) { classpath.addExisting((new Path(getProject())).concatSystemClasspath("last")); } if (includeJavaRuntime) { classpath.addJavaRuntime(); } commandLineList.add(javaHome + separator + "bin" + separator + "java"); commandLineList.add("-classpath"); commandLineList.add(classpath.toString()); final String fileEncodingProp = System.getProperty("file.encoding"); if ((fileEncodingProp != null) && !fileEncodingProp.equals("")) { commandLineList.add("-Dfile.encoding=" + fileEncodingProp); } if (targetBytecode != null) { commandLineList.add("-Dgroovy.target.bytecode=" + targetBytecode); } if ((memoryInitialSize != null) && !memoryInitialSize.equals("")) { commandLineList.add("-Xms" + memoryInitialSize); } if ((memoryMaximumSize != null) && !memoryMaximumSize.equals("")) { commandLineList.add("-Xmx" + memoryMaximumSize); } if (!"*.groovy".equals(getScriptExtension())) { String tmpExtension = getScriptExtension(); if (tmpExtension.startsWith("*.")) tmpExtension = tmpExtension.substring(1); commandLineList.add("-Dgroovy.default.scriptExtension=" + tmpExtension); } commandLineList.add(FileSystemCompilerFacade.class.getName()); } commandLineList.add("--classpath"); commandLineList.add(classpath.toString()); if (jointCompilation) { commandLineList.add("-j"); commandLineList.addAll(jointOptions); } commandLineList.add("-d"); commandLineList.add(destDir.getPath()); if (encoding != null) { commandLineList.add("--encoding"); commandLineList.add(encoding); } if (stacktrace) { commandLineList.add("-e"); } // check to see if an external file is needed int count = 0; if (fork) { for (File srcFile : compileList) { count += srcFile.getPath().length(); } for (Object commandLineArg : commandLineList) { count += commandLineArg.toString().length(); } count += compileList.length; count += commandLineList.size(); } // 32767 is the command line length limit on Windows if (fork && (count > 32767)) { try { File tempFile = File.createTempFile("groovyc-files-", ".txt"); temporaryFiles.add(tempFile); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); for (File srcFile : compileList) { pw.println(srcFile.getPath()); } pw.close(); commandLineList.add("@" + tempFile.getPath()); } catch (IOException e) { log("Error creating file list", e, Project.MSG_ERR); } } else { for (File srcFile : compileList) { commandLineList.add(srcFile.getPath()); } } final String[] commandLine = new String[commandLineList.size()]; for (int i = 0; i < commandLine.length; ++i) { commandLine[i] = commandLineList.get(i); } log("Compilation arguments:", Project.MSG_VERBOSE); log(DefaultGroovyMethods.join(commandLine, "\n"), Project.MSG_VERBOSE); if (fork) { // use the main method in FileSystemCompiler final Execute executor = new Execute(); // new LogStreamHandler ( attributes , Project.MSG_INFO , Project.MSG_WARN ) ) ; executor.setAntRun(getProject()); executor.setWorkingDirectory(getProject().getBaseDir()); executor.setEnvironment(addClasspathToEnvironment(executor.getEnvironment(), classpath.toString())); executor.setCommandline(commandLine); try { executor.execute(); } catch (final IOException ioe) { throw new BuildException("Error running forked groovyc.", ioe); } final int returnCode = executor.getExitValue(); if (returnCode != 0) { if (failOnError) { throw new BuildException("Forked groovyc returned error code: " + returnCode); } else { log("Forked groovyc returned error code: " + returnCode, Project.MSG_ERR); } } } else { // hand crank it so we can add our own compiler configuration try { Options options = FileSystemCompiler.createCompilationOptions(); PosixParser cliParser = new PosixParser(); CommandLine cli; cli = cliParser.parse(options, commandLine); configuration = FileSystemCompiler.generateCompilerConfigurationFromOptions(cli); configuration.setScriptExtensions(getScriptExtensions()); String tmpExtension = getScriptExtension(); if (tmpExtension.startsWith("*.")) tmpExtension = tmpExtension.substring(1); configuration.setDefaultScriptExtension(tmpExtension); // Load the file name list String[] filenames = FileSystemCompiler.generateFileNamesFromOptions(cli); boolean fileNameErrors = filenames == null; fileNameErrors = fileNameErrors && !FileSystemCompiler.validateFiles(filenames); if (targetBytecode != null) { configuration.setTargetBytecode(targetBytecode); } if (!fileNameErrors) { FileSystemCompiler.doCompilation(configuration, makeCompileUnit(), filenames, false); } } catch (Exception re) { Throwable t = re; if ((re.getClass() == RuntimeException.class) && (re.getCause() != null)) { // unwrap to the real exception t = re.getCause(); } StringWriter writer = new StringWriter(); new ErrorReporter(t, false).write(new PrintWriter(writer)); String message = writer.toString(); if (failOnError) { log(message, Project.MSG_INFO); throw new BuildException("Compilation Failed", t, getLocation()); } else { log(message, Project.MSG_ERR); } } } } } finally { for (File temporaryFile : temporaryFiles) { try { FileSystemCompiler.deleteRecursive(temporaryFile); } catch (Throwable t) { System.err.println("error: could not delete temp files - " + temporaryFile.getPath()); } } } } private String[] addClasspathToEnvironment(String[] oldEnvironment, String classpath) { List newEnvironmentList = (oldEnvironment == null) ? new ArrayList() : Arrays.asList(oldEnvironment); newEnvironmentList.add("classpath=" + classpath); return newEnvironmentList.toArray(new String[newEnvironmentList.size()]); } protected CompilationUnit makeCompileUnit() { Map options = configuration.getJointCompilationOptions(); if (options != null) { if (keepStubs) { options.put("keepStubs", Boolean.TRUE); } if (stubDir != null) { options.put("stubDir", stubDir); } else { try { File tempStubDir = FileSystemCompiler.createTempDir(); temporaryFiles.add(tempStubDir); options.put("stubDir", tempStubDir); } catch (IOException ioe) { throw new BuildException(ioe); } } return new JavaAwareCompilationUnit(configuration, buildClassLoaderFor()); } else { return new CompilationUnit(configuration, null, buildClassLoaderFor()); } } protected GroovyClassLoader buildClassLoaderFor() { ClassLoader parent = getIncludeantruntime() ? getClass().getClassLoader() : new AntClassLoader(new RootLoader(new URL[0], null), getProject(), getClasspath()); if (parent instanceof AntClassLoader) { AntClassLoader antLoader = (AntClassLoader) parent; String[] pathElm = antLoader.getClasspath().split(File.pathSeparator); List classpath = configuration.getClasspath(); /* * Iterate over the classpath provided to groovyc, and add any missing path * entries to the AntClassLoader. This is a workaround, since for some reason * 'directory' classpath entries were not added to the AntClassLoader' classpath. */ for (String cpEntry : classpath) { boolean found = false; for (String path : pathElm) { if (cpEntry.equals(path)) { found = true; break; } } /* * fix for GROOVY-2284 * seems like AntClassLoader doesn't check if the file * may not exist in the classpath yet */ if (!found && new File(cpEntry).exists()) antLoader.addPathElement(cpEntry); } } GroovyClassLoader loader = new GroovyClassLoader(parent, configuration); // in command line we don't need to do script lookups loader.setResourceLoader(new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return null; } }); return loader; } /** * Set the stub directory into which the Java source stub * files should be generated. The directory need not exist * and will not be deleted automatically - though its contents * will be cleared unless 'keepStubs' is true. Ignored when forked. * * @param stubDir the stub directory */ public void setStubdir(File stubDir) { jointCompilation = true; this.stubDir = stubDir; } /** * Gets the stub directory into which the Java source stub * files should be generated * * @return the stub directory */ public File getStubdir() { return stubDir; } /** * Set the keepStubs flag. Defaults to false. Set to true for debugging. * Ignored when forked. * * @param keepStubs should stubs be retained */ public void setKeepStubs(boolean keepStubs) { this.keepStubs = keepStubs; } /** * Gets the keepStubs flag. * * @return the keepStubs flag */ public boolean getKeepStubs() { return keepStubs; } private Set getScriptExtensions() { return scriptExtensions; } private void loadRegisteredScriptExtensions() { if (scriptExtensions.isEmpty()) { scriptExtensions.add(getScriptExtension().substring(2)); // first extension will be the one set explicitly on Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject()); final String[] pe = classpath.list(); final GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); for (String file : pe) { loader.addClasspath(file); } scriptExtensions.addAll(SourceExtensionHandler.getRegisteredExtensions(loader)); } } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/VerifyClass.java0000644001501200150120000001262511713765676023723 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.MatchingTask; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.Analyzer; import org.objectweb.asm.tree.analysis.Frame; import org.objectweb.asm.tree.analysis.SimpleVerifier; import org.objectweb.asm.util.CheckClassAdapter; import org.objectweb.asm.util.TraceMethodVisitor; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; /** * Verify Class files. This task can take the following * arguments: *
      *
    • dir *
    * When this task executes, it will recursively scan the dir and * look for class files to verify. */ public class VerifyClass extends MatchingTask { private String topDir = null; private boolean verbose = false; public VerifyClass() { } public void execute() throws BuildException { if (topDir == null) throw new BuildException("no dir attribute is set"); File top = new File(topDir); if (!top.exists()) throw new BuildException("the directory " + top + " does not exist"); log("top dir is " + top); int fails = execute(top); if (fails == 0) { log("no bytecode problems found"); } else { log("found " + fails + " failing classes"); } } public void setDir(String dir) throws BuildException { topDir = dir; } public void setVerbose(boolean v) { verbose = v; } private int execute(File dir) { int fails = 0; File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { fails += execute(f); } else if (f.getName().endsWith(".class")) { try { boolean ok = readClass(f.getCanonicalPath()); if (!ok) fails++; } catch (IOException ioe) { log(ioe.getMessage()); throw new BuildException(ioe); } } } return fails; } private boolean readClass(String clazz) throws IOException { ClassReader cr = new ClassReader(new FileInputStream(clazz)); ClassNode ca = new ClassNode() { public void visitEnd() { //accept(cv); } }; cr.accept(new CheckClassAdapter(ca), ClassWriter.COMPUTE_MAXS); boolean failed = false; List methods = ca.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = (MethodNode) methods.get(i); if (method.instructions.size() > 0) { Analyzer a = new Analyzer(new SimpleVerifier()); try { a.analyze(ca.name, method); continue; } catch (Exception e) { e.printStackTrace(); } final Frame[] frames = a.getFrames(); if (!failed) { failed = true; log("verifying of class " + clazz + " failed"); } if (verbose) log(method.name + method.desc); TraceMethodVisitor mv = new TraceMethodVisitor(null) { public void visitMaxs(int maxStack, int maxLocals) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < text.size(); ++i) { String s = frames[i] == null ? "null" : frames[i].toString(); while (s.length() < maxStack + maxLocals + 1) { s += " "; } buffer.append(Integer.toString(i + 100000).substring(1)); buffer.append(" "); buffer.append(s); buffer.append(" : "); buffer.append(text.get(i)); } if (verbose) log(buffer.toString()); } }; for (int j = 0; j < method.instructions.size(); ++j) { Object insn = method.instructions.get(j); if (insn instanceof AbstractInsnNode) { ((AbstractInsnNode) insn).accept(mv); } else { mv.visitLabel((Label) insn); } } mv.visitMaxs(method.maxStack, method.maxLocals); } } return !failed; } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/LoggingHelper.java0000644001501200150120000000271511627206700024174 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; /** * Helper to make logging from Ant easier. * * @version $Id$ * @author Jason Dillon */ public class LoggingHelper { private Task owner; public LoggingHelper(final Task owner) { assert owner != null; this.owner = owner; } public void error(final String msg) { owner.log(msg, Project.MSG_ERR); } public void warn(final String msg) { owner.log(msg, Project.MSG_WARN); } public void info(final String msg) { owner.log(msg, Project.MSG_INFO); } public void verbose(final String msg) { owner.log(msg, Project.MSG_VERBOSE); } public void debug(final String msg) { owner.log(msg, Project.MSG_DEBUG); } }groovy-1.8.6/src/main/org/codehaus/groovy/ant/FileScanner.java0000644001501200150120000000376011627206700023640 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; /** *

    FileScanner is a bean which allows the iteration * over a number of files from a collection of FileSet instances. * * @author James Strachan * @author Marc Guillemot * @version $Revision$ */ public class FileScanner extends Task { /** FileSets */ private List filesets = new ArrayList(); public FileScanner() { } public FileScanner(final Project project) { setProject(project); } public Iterator iterator() { return new FileIterator(getProject(), filesets.iterator()); } public Iterator directories() { return new FileIterator(getProject(), filesets.iterator(), true); } public boolean hasFiles() { return filesets.size() > 0; } /** * Clears any file sets that have been added to this scanner */ public void clear() { filesets.clear(); } // Properties //------------------------------------------------------------------------- /** * Adds a set of files (nested fileset attribute). */ public void addFileset(FileSet set) { filesets.add(set); } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/CompileTaskSupport.java0000644001501200150120000001075011627206700025254 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import groovy.lang.GroovyClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.tools.ErrorReporter; import java.io.File; import java.io.StringWriter; import java.io.PrintWriter; /** * Support for compilation related tasks. * * @version $Id$ * @author Jason Dillon */ public abstract class CompileTaskSupport extends MatchingTask { protected final LoggingHelper log = new LoggingHelper(this); protected Path src; protected File destdir; protected Path classpath; protected CompilerConfiguration config = new CompilerConfiguration(); protected boolean failOnError = true; public void setFailonerror(final boolean fail) { failOnError = fail; } public boolean getFailonerror() { return failOnError; } public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } public void setSrcdir(final Path dir) { assert dir != null; if (src == null) { src = dir; } else { src.append(dir); } } public Path getSrcdir() { return src; } public void setDestdir(final File dir) { assert dir != null; this.destdir = dir; } public void setClasspath(final Path path) { assert path != null; if (classpath == null) { classpath = path; } else { classpath.append(path); } } public Path getClasspath() { return classpath; } public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } public void setClasspathRef(final Reference r) { assert r != null; createClasspath().setRefid(r); } public CompilerConfiguration createConfiguration() { return config; } protected void validate() throws BuildException { if (src == null) { throw new BuildException("Missing attribute: srcdir (or one or more nested elements).", getLocation()); } if (destdir == null) { throw new BuildException("Missing attribute: destdir", getLocation()); } if (!destdir.exists()) { throw new BuildException("Destination directory does not exist: " + destdir, getLocation()); } } protected GroovyClassLoader createClassLoader() { ClassLoader parent = ClassLoader.getSystemClassLoader(); GroovyClassLoader gcl = new GroovyClassLoader(parent, config); Path path = getClasspath(); if (path != null) { final String[] filePaths = path.list(); for (int i = 0; i < filePaths.length; i++) { String filePath = filePaths[i]; gcl.addClasspath(filePath); } } return gcl; } protected void handleException(final Exception e) throws BuildException { assert e != null; StringWriter writer = new StringWriter(); new ErrorReporter(e, false).write(new PrintWriter(writer)); String message = writer.toString(); if (failOnError) { throw new BuildException(message, e, getLocation()); } else { log.error(message); } } public void execute() throws BuildException { validate(); try { compile(); } catch (Exception e) { handleException(e); } } protected abstract void compile() throws Exception; }groovy-1.8.6/src/main/org/codehaus/groovy/ant/package.html0000644001501200150120000000035511627206700023062 0ustar miguelmiguel package org.codehaus.groovy.ant.*

    Ant tasks for working with Groovy - such as groovyc for compiling Groovy source code to Java bytecode

    groovy-1.8.6/src/main/org/codehaus/groovy/ant/FileSystemCompilerFacade.java0000644001501200150120000000205411667450312026311 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.codehaus.groovy.tools.FileSystemCompiler; /** * This is a helper class, to provide a controlled entry point for the groovyc * ant task forked mode. * @author Jochen "blackdrag" Theodorou */ public class FileSystemCompilerFacade { public static void main(String[] args) { FileSystemCompiler.commandLineCompileWithErrorHandling(args,false); } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/FileIterator.java0000644001501200150120000001052311627206700024033 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import java.io.File; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; /** *

    FileIterator is an iterator over a * number of files from a collection of FileSet instances. * * @author James Strachan * @version $Revision$ */ public class FileIterator implements Iterator { /** The iterator over the FileSet objects */ private Iterator fileSetIterator; /** The Ant project */ private Project project; /** The directory scanner */ private DirectoryScanner ds; /** The file names in the current FileSet scan */ private String[] files; /** The current index into the file name array */ private int fileIndex = -1; /** The next File object we'll iterate over */ private File nextFile; /** Have we set a next object? */ private boolean nextObjectSet = false; /** Return only directories? */ private boolean iterateDirectories = false; public FileIterator(Project project, Iterator fileSetIterator) { this( project, fileSetIterator, false); } public FileIterator(Project project, Iterator fileSetIterator, boolean iterateDirectories) { this.project = project; this.fileSetIterator = fileSetIterator; this.iterateDirectories = iterateDirectories; } // Iterator interface //------------------------------------------------------------------------- /** @return true if there is another object that matches the given predicate */ public boolean hasNext() { if ( nextObjectSet ) { return true; } else { return setNextObject(); } } /** @return the next object which matches the given predicate */ public Object next() { if ( !nextObjectSet ) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextObjectSet = false; return nextFile; } /** * throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException(); } // Implementation methods //------------------------------------------------------------------------- /** * Set nextObject to the next object. If there are no more * objects then return false. Otherwise, return true. */ private boolean setNextObject() { while (true) { while (ds == null) { if ( ! fileSetIterator.hasNext() ) { return false; } FileSet fs = (FileSet) fileSetIterator.next(); ds = fs.getDirectoryScanner(project); ds.scan(); if (iterateDirectories) { files = ds.getIncludedDirectories(); } else { files = ds.getIncludedFiles(); } if ( files.length > 0 ) { fileIndex = -1; break; } else { ds = null; } } if ( ds != null && files != null ) { if ( ++fileIndex < files.length ) { nextFile = new File( ds.getBasedir(), files[fileIndex] ); nextObjectSet = true; return true; } else { ds = null; } } } } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/GenerateStubsTask.java0000644001501200150120000000473611627206700025051 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import groovy.lang.GroovyClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.codehaus.groovy.tools.javac.JavaStubCompilationUnit; import java.io.File; /** * Generates Java stubs from Groovy sources. * * @version $Id$ * @author Jason Dillon */ public class GenerateStubsTask extends CompileTaskSupport { @Override protected void compile() { GroovyClassLoader gcl = createClassLoader(); JavaStubCompilationUnit cu = new JavaStubCompilationUnit(config, gcl, destdir); int count = 0; String[] list = src.list(); for (int i = 0; i < list.length; i++) { File basedir = getProject().resolveFile(list[i]); if (!basedir.exists()) { throw new BuildException("Source directory does not exist: " + basedir, getLocation()); } DirectoryScanner scanner = getDirectoryScanner(basedir); String[] includes = scanner.getIncludedFiles(); log.debug("Including files from: " + basedir); for (int j=0; j < includes.length; j++) { log.debug(" " + includes[j]); File file = new File(basedir, includes[j]); cu.addSource(file); // Increment the count for each non/java src we found if (!includes[j].endsWith(".java")) { count++; } } } if (count > 0) { log.info("Generating " + count + " Java stub" + (count > 1 ? "s" : "") + " to " + destdir); cu.compile(); log.info("Generated " + cu.getStubCount() + " Java stub(s)"); } else { log.info("No sources found for stub generation"); } } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/Groovydoc.java0000644001501200150120000004377511627206700023434 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.DirSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PatternSet; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager; import org.codehaus.groovy.tools.groovydoc.FileOutputTool; import org.codehaus.groovy.tools.groovydoc.GroovyDocTool; import org.codehaus.groovy.tools.groovydoc.LinkArgument; import org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.*; /** * Access to the GroovyDoc tool from Ant. * * @version $Id$ */ public class Groovydoc extends Task { private final LoggingHelper log = new LoggingHelper(this); private Path sourcePath; private File destDir; private List packageNames; private List excludePackageNames; private String windowTitle = "Groovy Documentation"; private String docTitle = "Groovy Documentation"; private String footer = "Groovy Documentation"; private String header = "Groovy Documentation"; private Boolean privateScope; private Boolean protectedScope; private Boolean packageScope; private Boolean publicScope; private Boolean author; private Boolean processScripts; private Boolean includeMainForScripts; private boolean useDefaultExcludes; private boolean includeNoSourcePackages; private List packageSets; private List sourceFilesToDoc; private List links = new ArrayList(); private File overviewFile; private File styleSheetFile; // dev note: update javadoc comment for #setExtensions(String) if updating below private String extensions = ".java:.groovy:.gv:.gvy:.gsh"; public Groovydoc() { packageNames = new ArrayList(); excludePackageNames = new ArrayList(); packageSets = new ArrayList(); sourceFilesToDoc = new ArrayList(); privateScope = false; protectedScope = false; publicScope = false; packageScope = false; useDefaultExcludes = true; includeNoSourcePackages = false; author = true; processScripts = true; includeMainForScripts = true; } /** * Specify where to find source file * * @param src a Path instance containing the various source directories. */ public void setSourcepath(Path src) { if (sourcePath == null) { sourcePath = src; } else { sourcePath.append(src); } } /** * Set the directory where the Groovydoc output will be generated. * * @param dir the destination directory. */ public void setDestdir(File dir) { destDir = dir; // todo: maybe tell groovydoc to use file output } /** * If set to false, author will not be displayed. * Currently not used. * * @param author new value */ public void setAuthor(boolean author) { this.author = author; } /** * If set to false, Scripts will not be processed. * Defaults to true. * * @param processScripts new value */ public void setProcessScripts(boolean processScripts) { this.processScripts = processScripts; } /** * If set to false, 'public static void main' method will not be displayed. * Defaults to true. Ignored when not processing Scripts. * * @param includeMainForScripts new value */ public void setIncludeMainForScripts(boolean includeMainForScripts) { this.includeMainForScripts = includeMainForScripts; } /** * A colon-separated list of filename extensions to look for when searching for files to process in a given directory. * Default value: .java:.groovy:.gv:.gvy:.gsh * * @param extensions new value */ public void setExtensions(String extensions) { this.extensions = extensions; } /** * Set the package names to be processed. * * @param packages a comma separated list of packages specs * (may be wildcarded). */ public void setPackagenames(String packages) { StringTokenizer tok = new StringTokenizer(packages, ","); while (tok.hasMoreTokens()) { String packageName = tok.nextToken(); packageNames.add(packageName); } } public void setUse(boolean b) { //ignore as 'use external file' irrelevant with groovydoc :-) } /** * Set the title to be placed in the HTML <title> tag of the * generated documentation. * * @param title the window title to use. */ public void setWindowtitle(String title) { windowTitle = title; } /** * Set the title for the overview page. * * @param htmlTitle the html to use for the title. */ public void setDoctitle(String htmlTitle) { docTitle = htmlTitle; } /** * Specify the file containing the overview to be included in the generated documentation. * * @param file the overview file */ public void setOverview(File file) { overviewFile = file; } /** * Indicates the access mode or scope of interest: one of public, protected, package, or private. * Package scoped access is ignored for fields of Groovy classes where they correspond to properties. * * @param access one of public, protected, package, or private */ public void setAccess(String access) { if ("public".equals(access)) publicScope = true; else if ("protected".equals(access)) protectedScope = true; else if ("package".equals(access)) packageScope = true; else if ("private".equals(access)) privateScope = true; } /** * Indicate whether all classes and * members are to be included in the scope processed. * * @param b true if scope is to be private level. */ public void setPrivate(boolean b) { privateScope = b; } /** * Indicate whether only public classes and members are to be included in the scope processed. * * @param b true if scope only includes public level classes and members */ public void setPublic(boolean b) { publicScope = b; } /** * Indicate whether only protected and public classes and members are to be included in the scope processed. * * @param b true if scope includes protected level classes and members */ public void setProtected(boolean b) { protectedScope = b; } /** * Indicate whether only package, protected and public classes and members are to be included in the scope processed. * Package scoped access is ignored for fields of Groovy classes where they correspond to properties. * * @param b true if scope includes package level classes and members */ public void setPackage(boolean b) { packageScope = b; } /** * Set the footer to place at the bottom of each generated html page. * * @param footer the footer value */ public void setFooter(String footer) { this.footer = footer; } /** * Specifies the header text to be placed at the top of each output file. * The header will be placed to the right of the upper navigation bar. * It may contain HTML tags and white space, though if it does, it must * be enclosed in quotes. Any internal quotation marks within the header * may have to be escaped. * * @param header the header value */ public void setHeader(String header) { this.header = header; } /** * Specifies a stylesheet file to use. If not specified, * a default one will be generated for you. * * @param styleSheetFile the css stylesheet file to use */ public void setStyleSheetFile(File styleSheetFile) { this.styleSheetFile = styleSheetFile; } /** * Add the directories matched by the nested dirsets to the resulting * packages list and the base directories of the dirsets to the Path. * It also handles the packages and excludepackages attributes and * elements. * * @param resultantPackages a list to which we add the packages found * @param sourcePath a path to which we add each basedir found * @since 1.5 */ private void parsePackages(List resultantPackages, Path sourcePath) { List addedPackages = new ArrayList(); List dirSets = new ArrayList(packageSets); // for each sourcePath entry, add a directoryset with includes // taken from packagenames attribute and nested package // elements and excludes taken from excludepackages attribute // and nested excludepackage elements if (this.sourcePath != null) { PatternSet ps = new PatternSet(); if (packageNames.size() > 0) { for (String pn : packageNames) { String pkg = pn.replace('.', '/'); if (pkg.endsWith("*")) { pkg += "*"; } ps.createInclude().setName(pkg); } } else { ps.createInclude().setName("**"); } for (String epn : excludePackageNames) { String pkg = epn.replace('.', '/'); if (pkg.endsWith("*")) { pkg += "*"; } ps.createExclude().setName(pkg); } String[] pathElements = this.sourcePath.list(); for (String pathElement : pathElements) { File dir = new File(pathElement); if (dir.isDirectory()) { DirSet ds = new DirSet(); ds.setDefaultexcludes(useDefaultExcludes); ds.setDir(dir); ds.createPatternSet().addConfiguredPatternset(ps); dirSets.add(ds); } else { log.warn("Skipping " + pathElement + " since it is no directory."); } } } for (DirSet ds : dirSets) { File baseDir = ds.getDir(getProject()); log.debug("scanning " + baseDir + " for packages."); DirectoryScanner dsc = ds.getDirectoryScanner(getProject()); String[] dirs = dsc.getIncludedDirectories(); boolean containsPackages = false; for (String dir : dirs) { // are there any groovy or java files in this directory? File pd = new File(baseDir, dir); String[] files = pd.list(new FilenameFilter() { public boolean accept(File dir1, String name) { if (!includeNoSourcePackages && name.equals("package.html")) return true; final StringTokenizer tokenizer = new StringTokenizer(extensions, ":"); while (tokenizer.hasMoreTokens()) { String ext = tokenizer.nextToken(); if (name.endsWith(ext)) return true; } return false; } }); for (String filename : Arrays.asList(files)) { sourceFilesToDoc.add(dir + File.separator + filename); } if (files.length > 0) { if ("".equals(dir)) { log.warn(baseDir + " contains source files in the default package," + " you must specify them as source files not packages."); } else { containsPackages = true; String pn = dir.replace(File.separatorChar, '.'); if (!addedPackages.contains(pn)) { addedPackages.add(pn); resultantPackages.add(pn); } } } } if (containsPackages) { // We don't need to care for duplicates here, // Path.list does it for us. sourcePath.createPathElement().setLocation(baseDir); } else { log.verbose(baseDir + " doesn't contain any packages, dropping it."); } } } public void execute() throws BuildException { List packagesToDoc = new ArrayList(); Path sourceDirs = new Path(getProject()); Properties properties = new Properties(); properties.setProperty("windowTitle", windowTitle); properties.setProperty("docTitle", docTitle); properties.setProperty("footer", footer); properties.setProperty("header", header); checkScopeProperties(properties); properties.setProperty("publicScope", publicScope.toString()); properties.setProperty("protectedScope", protectedScope.toString()); properties.setProperty("packageScope", packageScope.toString()); properties.setProperty("privateScope", privateScope.toString()); properties.setProperty("author", author.toString()); properties.setProperty("processScripts", processScripts.toString()); properties.setProperty("includeMainForScripts", includeMainForScripts.toString()); properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : ""); if (sourcePath != null) { sourceDirs.addExisting(sourcePath); } parsePackages(packagesToDoc, sourceDirs); GroovyDocTool htmlTool = new GroovyDocTool( new ClasspathResourceManager(), // we're gonna get the default templates out of the dist jar file sourcePath.list(), getDocTemplates(), getPackageTemplates(), getClassTemplates(), links, properties ); try { htmlTool.add(sourceFilesToDoc); FileOutputTool output = new FileOutputTool(); htmlTool.renderToOutput(output, destDir.getCanonicalPath()); // TODO push destDir through APIs? } catch (Exception e) { e.printStackTrace(); } // try to override the default stylesheet with custom specified one if needed if (styleSheetFile != null) { try { String css = DefaultGroovyMethods.getText(styleSheetFile); File outfile = new File(destDir, "stylesheet.css"); DefaultGroovyMethods.setText(outfile, css); } catch (IOException e) { System.out.println("Warning: Unable to copy specified stylesheet '" + styleSheetFile.getAbsolutePath() + "'. Using default stylesheet instead. Due to: " + e.getMessage()); } } } private void checkScopeProperties(Properties properties) { // make protected the default scope and check for invalid duplication int scopeCount = 0; if (packageScope) scopeCount++; if (privateScope) scopeCount++; if (protectedScope) scopeCount++; if (publicScope) scopeCount++; if (scopeCount == 0) { protectedScope = true; } else if (scopeCount > 1) { throw new BuildException("More than one of public, private, package, or protected scopes specified."); } } /** * Create link to Javadoc/GroovyDoc output at the given URL. * * @return link argument to configure */ public LinkArgument createLink() { LinkArgument result = new LinkArgument(); links.add(result); return result; } /** * Creates and returns an array of package template classpath entries.

    * * This method is meant to be overridden by custom GroovyDoc implementations, using custom package templates. * * @return an array of package templates, whereas each entry is resolved as classpath entry, defaults to * {@link GroovyDocTemplateInfo#DEFAULT_PACKAGE_TEMPLATES}. */ protected String[] getPackageTemplates() { return GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES; } /** * Creates and returns an array of doc template classpath entries.

    * * This method is meant to be overridden by custom GroovyDoc implementations, using custom doc templates. * * @return an array of doc templates, whereas each entry is resolved as classpath entry, defaults to * {@link GroovyDocTemplateInfo#DEFAULT_DOC_TEMPLATES}. * */ protected String[] getDocTemplates() { return GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES; } /** * Creates and returns an array of class template classpath entries.

    * * This method is meant to be overridden by custom GroovyDoc implementations, using custom class templates. * * @return an array of class templates, whereas each entry is resolved as classpath entry, defaults to * {@link GroovyDocTemplateInfo#DEFAULT_CLASS_TEMPLATES}. */ protected String[] getClassTemplates() { return GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES; } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/AntProjectPropertiesDelegate.java0000644001501200150120000000741011627206700027224 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.Project; import java.util.Hashtable; import java.util.Collection; import java.util.Enumeration; import java.util.Map; import java.util.Set; import java.util.Iterator; /** * @author Guillaume Laforge */ public class AntProjectPropertiesDelegate extends Hashtable { private Project project; public AntProjectPropertiesDelegate(Project project) { super(); this.project = project; } public synchronized int hashCode() { return project.getProperties().hashCode(); } public synchronized int size() { return project.getProperties().size(); } /** * @throws UnsupportedOperationException is always thrown when this method is invoked. The Project properties are immutable. */ public synchronized void clear() { throw new UnsupportedOperationException("Impossible to clear the project properties."); } public synchronized boolean isEmpty() { return project.getProperties().isEmpty(); } public synchronized Object clone() { return project.getProperties().clone(); } public synchronized boolean contains(Object value) { return project.getProperties().contains(value); } public synchronized boolean containsKey(Object key) { return project.getProperties().containsKey(key); } public boolean containsValue(Object value) { return project.getProperties().containsValue(value); } public synchronized boolean equals(Object o) { return project.getProperties().equals(o); } public synchronized String toString() { return project.getProperties().toString(); } public Collection values() { return project.getProperties().values(); } public synchronized Enumeration elements() { return project.getProperties().elements(); } public synchronized Enumeration keys() { return project.getProperties().keys(); } public AntProjectPropertiesDelegate(Map t) { super(t); } public synchronized void putAll(Map t) { Set keySet = t.keySet(); for (Iterator iterator = keySet.iterator(); iterator.hasNext();) { Object key = iterator.next(); Object value = t.get(key); put(key, value); } } public Set entrySet() { return project.getProperties().entrySet(); } public Set keySet() { return project.getProperties().keySet(); } public synchronized Object get(Object key) { return project.getProperties().get(key); } /** * @throws UnsupportedOperationException is always thrown when this method is invoked. The Project properties are immutable. */ public synchronized Object remove(Object key) { throw new UnsupportedOperationException("Impossible to remove a property from the project properties."); } public synchronized Object put(Object key, Object value) { Object oldValue = null; if (containsKey(key)) { oldValue = get(key); } project.setProperty(key.toString(), value.toString()); return oldValue; } }groovy-1.8.6/src/main/org/codehaus/groovy/ant/Groovy.java0000644001501200150120000005025211707612044022733 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import groovy.lang.Binding; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyShell; import groovy.lang.MissingMethodException; import groovy.lang.Script; import groovy.util.AntBuilder; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.util.FileUtils; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.tools.ErrorReporter; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.Vector; /** * Executes a series of Groovy statements. *

    *

    Statements can either be read in from a text file using * the src attribute or from between the enclosing groovy tags.

    * * @version $Id$ */ public class Groovy extends Java { private static final String PREFIX = "embedded_script_in_"; private static final String SUFFIX = "groovy_Ant_task"; private final LoggingHelper log = new LoggingHelper(this); /** * files to load */ private Vector filesets = new Vector(); /** * input file */ private File srcFile = null; /** * input command */ private String command = ""; /** * Results Output file. */ private File output = null; /** * Append to an existing file or overwrite it? */ private boolean append = false; private Path classpath; private boolean fork = false; private boolean includeAntRuntime = true; private boolean useGroovyShell = false; /** * Compiler configuration. *

    * Used to specify the debug output to print stacktraces in case something fails. * TODO: Could probably be reused to specify the encoding of the files to load or other properties. */ private CompilerConfiguration configuration = new CompilerConfiguration(); private Commandline cmdline = new Commandline(); private boolean contextClassLoader; /** * Should the script be executed using a forked process. Defaults to false. * * @param fork true if the script should be executed in a forked process */ public void setFork(boolean fork) { this.fork = fork; } /** * Should a new GroovyShell be used when forking. Special variables won't be available * but you don't need Ant in the classpath. * * @param useGroovyShell true if GroovyShell should be used to run the script directly */ public void setUseGroovyShell(boolean useGroovyShell) { this.useGroovyShell = useGroovyShell; } /** * Should the system classpath be included on the classpath when forking. Defaults to true. * * @param includeAntRuntime true if the system classpath should be on the classpath */ public void setIncludeAntRuntime(boolean includeAntRuntime) { this.includeAntRuntime = includeAntRuntime; } /** * Enable compiler to report stack trace information if a problem occurs * during compilation. * * @param stacktrace set to true to enable stacktrace reporting */ public void setStacktrace(boolean stacktrace) { configuration.setDebug(stacktrace); } /** * Set the name of the file to be run. The folder of the file is automatically added to the classpath. * Required unless statements are enclosed in the build file * * @param srcFile the file containing the groovy script to execute */ public void setSrc(final File srcFile) { this.srcFile = srcFile; } /** * Set an inline command to execute. * NB: Properties are not expanded in this text. * * @param txt the inline groovy ommands to execute */ public void addText(String txt) { log("addText('" + txt + "')", Project.MSG_VERBOSE); this.command += txt; } /** * Adds a set of files (nested fileset attribute). * * @param set the fileset representing source files */ public void addFileset(FileSet set) { filesets.addElement(set); } /** * Set the output file; * optional, defaults to the Ant log. * * @param output the output file */ public void setOutput(File output) { this.output = output; } /** * Whether output should be appended to or overwrite * an existing file. Defaults to false. * * @param append set to true to append */ public void setAppend(boolean append) { this.append = append; } /** * Sets the classpath for loading. * * @param classpath The classpath to set */ public void setClasspath(final Path classpath) { this.classpath = classpath; } /** * Returns a new path element that can be configured. * Gets called for instance by Ant when it encounters a nested <classpath> element. * * @return the resulting created path */ public Path createClasspath() { if (this.classpath == null) { this.classpath = new Path(getProject()); } return this.classpath.createPath(); } /** * Set the classpath for loading * using the classpath reference. * * @param ref the refid to use */ public void setClasspathRef(final Reference ref) { createClasspath().setRefid(ref); } /** * Gets the classpath. * * @return Returns a Path */ public Path getClasspath() { return classpath; } /** * Load the file and then execute it */ public void execute() throws BuildException { log.debug("execute()"); command = command.trim(); if (srcFile == null && command.length() == 0 && filesets.isEmpty()) { throw new BuildException("Source file does not exist!", getLocation()); } if (srcFile != null && !srcFile.exists()) { throw new BuildException("Source file does not exist!", getLocation()); } // TODO: any of this used? // deal with the filesets for (int i = 0; i < filesets.size(); i++) { FileSet fs = filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File srcDir = fs.getDir(getProject()); String[] srcFiles = ds.getIncludedFiles(); } try { PrintStream out = System.out; try { if (output != null) { log.verbose("Opening PrintStream to output file " + output); out = new PrintStream( new BufferedOutputStream( new FileOutputStream(output.getAbsolutePath(), append))); } // if there are no groovy statements between the enclosing Groovy tags // then read groovy statements in from a text file using the src attribute if (command == null || command.trim().length() == 0) { createClasspath().add(new Path(getProject(), srcFile.getParentFile().getCanonicalPath())); command = getText(new BufferedReader(new FileReader(srcFile))); } if (command != null) { execGroovy(command, out); } else { throw new BuildException("Source file does not exist!", getLocation()); } } finally { if (out != null && out != System.out) { out.close(); } } } catch (IOException e) { throw new BuildException(e, getLocation()); } log.verbose("statements executed successfully"); } private static String getText(BufferedReader reader) throws IOException { StringBuffer answer = new StringBuffer(); // reading the content of the file within a char buffer allow to keep the correct line endings char[] charBuffer = new char[4096]; int nbCharRead = 0; while ((nbCharRead = reader.read(charBuffer)) != -1) { // appends buffer answer.append(charBuffer, 0, nbCharRead); } reader.close(); return answer.toString(); } public Commandline.Argument createArg() { return cmdline.createArgument(); } /** * Read in lines and execute them. * * @param reader the reader from which to get the groovy source to exec * @param out the outputstream to use * @throws java.io.IOException if something goes wrong */ protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuffer txt = new StringBuffer(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } } /** * Exec the statement. * * @param txt the groovy source to exec * @param out not used? */ protected void execGroovy(final String txt, final PrintStream out) { log.debug("execGroovy()"); // Check and ignore empty statements if ("".equals(txt.trim())) { return; } log.verbose("Script: " + txt); if (classpath != null) { log.debug("Explicit Classpath: " + classpath.toString()); } if (fork) { log.debug("Using fork mode"); try { createClasspathParts(); createNewArgs(txt); super.setFork(fork); super.setClassname(useGroovyShell ? "groovy.lang.GroovyShell" : "org.codehaus.groovy.ant.Groovy"); super.execute(); } catch (Exception e) { StringWriter writer = new StringWriter(); new ErrorReporter(e, false).write(new PrintWriter(writer)); String message = writer.toString(); throw new BuildException("Script Failed: " + message, e, getLocation()); } return; } Object mavenPom = null; final Project project = getProject(); final ClassLoader baseClassLoader; ClassLoader savedLoader = null; final Thread thread = Thread.currentThread(); boolean maven = "org.apache.commons.grant.GrantProject".equals(project.getClass().getName()); // treat the case Ant is run through Maven, and if (maven) { if (contextClassLoader) { throw new BuildException("Using setContextClassLoader not permitted when using Maven.", getLocation()); } try { final Object propsHandler = project.getClass().getMethod("getPropsHandler").invoke(project); final Field contextField = propsHandler.getClass().getDeclaredField("context"); contextField.setAccessible(true); final Object context = contextField.get(propsHandler); mavenPom = InvokerHelper.invokeMethod(context, "getProject", new Object[0]); } catch (Exception e) { throw new BuildException("Impossible to retrieve Maven's Ant project: " + e.getMessage(), getLocation()); } // load groovy into "root.maven" classloader instead of "root" so that // groovy script can access Maven classes baseClassLoader = mavenPom.getClass().getClassLoader(); } else { baseClassLoader = GroovyShell.class.getClassLoader(); } if (contextClassLoader || maven) { savedLoader = thread.getContextClassLoader(); thread.setContextClassLoader(GroovyShell.class.getClassLoader()); } final String scriptName = computeScriptName(); final GroovyClassLoader classLoader = new GroovyClassLoader(baseClassLoader); addClassPathes(classLoader); final GroovyShell groovy = new GroovyShell(classLoader, new Binding(), configuration); try { parseAndRunScript(groovy, txt, mavenPom, scriptName, null, new AntBuilder(this)); } finally { groovy.resetLoadedClasses(); groovy.getClassLoader().clearCache(); if (contextClassLoader || maven) thread.setContextClassLoader(savedLoader); } } private void parseAndRunScript(GroovyShell shell, String txt, Object mavenPom, String scriptName, File scriptFile, AntBuilder builder) { try { final Script script; if (scriptFile != null) { script = shell.parse(scriptFile); } else { script = shell.parse(txt, scriptName); } final Project project = getProject(); script.setProperty("ant", builder); script.setProperty("project", project); script.setProperty("properties", new AntProjectPropertiesDelegate(project)); script.setProperty("target", getOwningTarget()); script.setProperty("task", this); script.setProperty("args", cmdline.getCommandline()); if (mavenPom != null) { script.setProperty("pom", mavenPom); } script.run(); } catch (final MissingMethodException mme) { // not a script, try running through run method but properties will not be available if (scriptFile != null) { try { shell.run(scriptFile, cmdline.getCommandline()); } catch (IOException e) { processError(e); } } else { shell.run(txt, scriptName, cmdline.getCommandline()); } } catch (final CompilationFailedException e) { processError(e); } catch (IOException e) { processError(e); } } private void processError(Exception e) { StringWriter writer = new StringWriter(); new ErrorReporter(e, false).write(new PrintWriter(writer)); String message = writer.toString(); throw new BuildException("Script Failed: " + message, e, getLocation()); } public static void main(String[] args) { final GroovyShell shell = new GroovyShell(new Binding()); final Groovy groovy = new Groovy(); for (int i = 1; i < args.length; i++) { final Commandline.Argument argument = groovy.createArg(); argument.setValue(args[i]); } final AntBuilder builder = new AntBuilder(); groovy.setProject(builder.getProject()); groovy.parseAndRunScript(shell, null, null, null, new File(args[0]), builder); } private void createClasspathParts() { Path path; if (classpath != null) { path = super.createClasspath(); path.setPath(classpath.toString()); } if (includeAntRuntime) { path = super.createClasspath(); path.setPath(System.getProperty("java.class.path")); } String groovyHome = null; final String[] strings = getSysProperties().getVariables(); if (strings != null) { for (String prop : strings) { if (prop.startsWith("-Dgroovy.home=")) { groovyHome = prop.substring("-Dgroovy.home=".length()); } } } if (groovyHome == null) { groovyHome = System.getProperty("groovy.home"); } if (groovyHome == null) { groovyHome = System.getenv("GROOVY_HOME"); } if (groovyHome == null) { throw new IllegalStateException("Neither ${groovy.home} nor GROOVY_HOME defined."); } File jarDir = new File(groovyHome, "embeddable"); if (!jarDir.exists()) { throw new IllegalStateException("GROOVY_HOME incorrectly defined. No embeddable directory found in: " + groovyHome); } final File[] files = jarDir.listFiles(); for (File file : files) { try { log.debug("Adding jar to classpath: " + file.getCanonicalPath()); } catch (IOException e) { // ignore } path = super.createClasspath(); path.setLocation(file); } } private void createNewArgs(String txt) throws IOException { final String[] args = cmdline.getCommandline(); // Temporary file - delete on exit, create (assured unique name). final File tempFile = FileUtils.getFileUtils().createTempFile(PREFIX, SUFFIX, null, true, true); final String[] commandline = new String[args.length + 1]; DefaultGroovyMethods.write(tempFile, txt); commandline[0] = tempFile.getCanonicalPath(); System.arraycopy(args, 0, commandline, 1, args.length); super.clearArgs(); for (String arg : commandline) { final Commandline.Argument argument = super.createArg(); argument.setValue(arg); } } /** * Try to build a script name for the script of the groovy task to have an helpful value in stack traces in case of exception * * @return the name to use when compiling the script */ private String computeScriptName() { if (srcFile != null) { return srcFile.getAbsolutePath(); } else { String name = PREFIX; if (getLocation().getFileName().length() > 0) name += getLocation().getFileName().replaceAll("[^\\w_\\.]", "_").replaceAll("[\\.]", "_dot_"); else name += SUFFIX; return name; } } /** * Adds the class paths (if any) * * @param classLoader the classloader to configure */ protected void addClassPathes(final GroovyClassLoader classLoader) { if (classpath != null) { for (int i = 0; i < classpath.list().length; i++) { classLoader.addClasspath(classpath.list()[i]); } } } /** * print any results in the statement. * * @param out the output PrintStream to print to */ protected void printResults(PrintStream out) { log.debug("printResults()"); StringBuffer line = new StringBuffer(); out.println(line); out.println(); } /** * Setting to true will cause the contextClassLoader to be set with * the classLoader of the shell used to run the script. Not used if * fork is true. Not allowed when running from Maven but in that * case the context classLoader is set appropriately for Maven. * * @param contextClassLoader set to true to set the context classloader */ public void setContextClassLoader(boolean contextClassLoader) { this.contextClassLoader = contextClassLoader; } } groovy-1.8.6/src/main/org/codehaus/groovy/ant/GroovycTask.java0000644001501200150120000000647011627206700023723 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import groovy.lang.GroovyClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.SourceFileScanner; import org.codehaus.groovy.control.CompilationUnit; import java.io.File; /** * Compiles Groovy source files. * * @version $Id$ * @author Jason Dillon */ public class GroovycTask extends CompileTaskSupport { protected boolean force; public void setForce(final boolean flag) { this.force = flag; } protected void compile() { Path path = getClasspath(); if (path != null) { config.setClasspath(path.toString()); } config.setTargetDirectory(destdir); GroovyClassLoader gcl = createClassLoader(); CompilationUnit compilation = new CompilationUnit(config, null, gcl); GlobPatternMapper mapper = new GlobPatternMapper(); mapper.setFrom("*.groovy"); mapper.setTo("*.class"); int count = 0; String[] list = src.list(); for (int i = 0; i < list.length; i++) { File basedir = getProject().resolveFile(list[i]); if (!basedir.exists()) { throw new BuildException("Source directory does not exist: " + basedir, getLocation()); } DirectoryScanner scanner = getDirectoryScanner(basedir); String[] includes = scanner.getIncludedFiles(); if (force) { log.debug("Forcefully including all files from: " + basedir); for (int j=0; j < includes.length; j++) { File file = new File(basedir, includes[j]); log.debug(" " + file); compilation.addSource(file); count++; } } else { log.debug("Including changed files from: " + basedir); SourceFileScanner sourceScanner = new SourceFileScanner(this); File[] files = sourceScanner.restrictAsFiles(includes, basedir, destdir, mapper); for (int j=0; j < files.length; j++) { log.debug(" " + files[j]); compilation.addSource(files[j]); count++; } } } if (count > 0) { log.info("Compiling " + count + " source file" + (count > 1 ? "s" : "") + " to " + destdir); compilation.compile(); } else { log.info("No sources found to compile"); } } }groovy-1.8.6/src/main/org/codehaus/groovy/control/0000755001501200150120000000000011715031256021474 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/control/Phases.java0000644001501200150120000000417511627206700023571 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; /** * Compilation phase identifiers. * * @author Chris Poirier * * @version $Id$ */ public class Phases { public static final int INITIALIZATION = 1; // Opening of files and such public static final int PARSING = 2; // Lexing, parsing, and AST building public static final int CONVERSION = 3; // CST to AST conversion public static final int SEMANTIC_ANALYSIS = 4; // AST semantic analysis and elucidation public static final int CANONICALIZATION = 5; // AST completion public static final int INSTRUCTION_SELECTION = 6; // Class generation, phase 1 public static final int CLASS_GENERATION = 7; // Class generation, phase 2 public static final int OUTPUT = 8; // Output of class to disk public static final int FINALIZATION = 9; // Cleanup public static final int ALL = 9; // Synonym for full compilation public static String[] descriptions = { "startup" , "initialization" , "parsing" , "conversion" , "semantic analysis" , "canonicalization" , "instruction selection" , "class generation" , "output" , "cleanup" }; /** * Returns a description of the specified phase. */ public static String getDescription( int phase ) { return descriptions[phase]; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/LabelVerifier.java0000644001501200150120000001317611627206700025062 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import java.util.Iterator; import java.util.LinkedList; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; /** * This class checks the handling of labels in the AST * * @author Jochen Theodorou */ public class LabelVerifier extends ClassCodeVisitorSupport { private SourceUnit source; private LinkedList visitedLabels; private LinkedList continueLabels; private LinkedList breakLabels; boolean inLoop=false; boolean inSwitch=false; public LabelVerifier(SourceUnit src) { source = src; } protected SourceUnit getSourceUnit() { return source; } private void init(){ visitedLabels = new LinkedList(); continueLabels = new LinkedList(); breakLabels = new LinkedList(); inLoop=false; inSwitch=false; } protected void visitClassCodeContainer(Statement code) { init(); super.visitClassCodeContainer(code); assertNoLabelsMissed(); } public void visitStatement(Statement statement) { String label = statement.getStatementLabel(); if (label!=null) { for (Iterator iter = breakLabels.iterator(); iter.hasNext();) { BreakStatement element = (BreakStatement) iter.next(); if (element.getLabel().equals(label)) iter.remove(); } for (Iterator iter = continueLabels.iterator(); iter.hasNext();) { ContinueStatement element = (ContinueStatement) iter.next(); if (element.getLabel().equals(label)) iter.remove(); } visitedLabels.add(label); } super.visitStatement(statement); } public void visitForLoop(ForStatement forLoop) { boolean oldInLoop = inLoop; inLoop = true; super.visitForLoop(forLoop); inLoop = oldInLoop; } public void visitDoWhileLoop(DoWhileStatement loop) { boolean oldInLoop = inLoop; inLoop = true; super.visitDoWhileLoop(loop); inLoop = oldInLoop; } public void visitWhileLoop(WhileStatement loop) { boolean oldInLoop = inLoop; inLoop = true; super.visitWhileLoop(loop); inLoop = oldInLoop; } public void visitBreakStatement(BreakStatement statement) { String label = statement.getLabel(); boolean hasNamedLabel = label!=null; if (!hasNamedLabel && !inLoop && !inSwitch) { addError("the break statement is only allowed inside loops or switches",statement); } else if (hasNamedLabel && !inLoop) { addError("the break statement with named label is only allowed inside loops",statement); } if (label!=null) { boolean found=false; for (Iterator iter = visitedLabels.iterator(); iter.hasNext();) { String element = (String) iter.next(); if (element.equals(label)) { found = true; break; } } if (!found) breakLabels.add(statement); } super.visitBreakStatement(statement); } public void visitContinueStatement(ContinueStatement statement) { String label = statement.getLabel(); boolean hasNamedLabel = label!=null; if (!hasNamedLabel && !inLoop) { addError("the continue statement is only allowed inside loops",statement); } if (label!=null) { boolean found=false; for (Iterator iter = visitedLabels.iterator(); iter.hasNext();) { String element = (String) iter.next(); if (element.equals(label)) { found = true; break; } } if (!found) continueLabels.add(statement); } super.visitContinueStatement(statement); } protected void assertNoLabelsMissed() { //TODO: report multiple missing labels of the same name only once for (Iterator iter = continueLabels.iterator(); iter.hasNext();) { ContinueStatement element = (ContinueStatement) iter.next(); addError("continue to missing label",element); } for (Iterator iter = breakLabels.iterator(); iter.hasNext();) { BreakStatement element = (BreakStatement) iter.next(); addError("break to missing label",element); } } public void visitSwitch(SwitchStatement statement) { boolean oldInSwitch = inSwitch; inSwitch = true; super.visitSwitch(statement); inSwitch = oldInSwitch; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/ResolveVisitor.java0000644001501200150120000017305111707612046025350 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyClassLoader; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.GroovyBugError; import org.objectweb.asm.Opcodes; import java.io.File; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.*; /** * Visitor to resolve Types and convert VariableExpression to * ClassExpressions if needed. The ResolveVisitor will try to * find the Class for a ClassExpression and prints an error if * it fails to do so. Constructions like C[], foo as C, (C) foo * will force creation of a ClassExpression for C *

    * Note: the method to start the resolving is startResolving(ClassNode, SourceUnit). * * @author Jochen Theodorou * @author Roshan Dawrani * @author Alex Tkachman */ public class ResolveVisitor extends ClassCodeExpressionTransformer { private ClassNode currentClass; // note: BigInteger and BigDecimal are also imported by default public static final String[] DEFAULT_IMPORTS = {"java.lang.", "java.io.", "java.net.", "java.util.", "groovy.lang.", "groovy.util."}; private CompilationUnit compilationUnit; private Map cachedClasses = new HashMap(); private static final Object NO_CLASS = new Object(); private SourceUnit source; private VariableScope currentScope; private boolean isTopLevelProperty = true; private boolean inPropertyExpression = false; private boolean inClosure = false; private Map genericParameterNames = new HashMap(); private Set fieldTypesChecked = new HashSet(); private boolean checkingVariableTypeInDeclaration = false; private ImportNode currImportNode = null; private MethodNode currentMethod; /** * we use ConstructedClassWithPackage to limit the resolving the compiler * does when combining package names and class names. The idea * that if we use a package, then we do not want to replace the * '.' with a '$' for the package part, only for the class name * part. There is also the case of a imported class, so this logic * can't be done in these cases... */ private static class ConstructedClassWithPackage extends ClassNode { String prefix; String className; public ConstructedClassWithPackage(String pkg, String name) { super(pkg+name, Opcodes.ACC_PUBLIC,ClassHelper.OBJECT_TYPE); isPrimaryNode = false; this.prefix = pkg; this.className = name; } public String getName() { if (redirect()!=this) return super.getName(); return prefix+className; } public boolean hasPackageName() { if (redirect()!=this) return super.hasPackageName(); return className.indexOf('.')!=-1; } public String setName(String name) { if (redirect()!=this) { return super.setName(name); } else { throw new GroovyBugError("ConstructedClassWithPackage#setName should not be called"); } } } /** * we use LowerCaseClass to limit the resolving the compiler * does for vanilla names starting with a lower case letter. The idea * that if we use a vanilla name with a lower case letter, that this * is in most cases no class. If it is a class the class needs to be * imported explicitly. The efffect is that in an expression like * "def foo = bar" we do not have to use a loadClass call to check the * name foo and bar for being classes. Instead we will ask the module * for an alias for this name which is much faster. */ private static class LowerCaseClass extends ClassNode { String className; public LowerCaseClass(String name) { super(name, Opcodes.ACC_PUBLIC,ClassHelper.OBJECT_TYPE); isPrimaryNode = false; this.className = name; } public String getName() { if (redirect()!=this) return super.getName(); return className; } public boolean hasPackageName() { if (redirect()!=this) return super.hasPackageName(); return false; } public String setName(String name) { if (redirect()!=this) { return super.setName(name); } else { throw new GroovyBugError("ConstructedClassWithPackage#setName should not be called"); } } } public ResolveVisitor(CompilationUnit cu) { compilationUnit = cu; } public void startResolving(ClassNode node, SourceUnit source) { this.source = source; visitClass(node); } protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { VariableScope oldScope = currentScope; currentScope = node.getVariableScope(); Map oldPNames = genericParameterNames; genericParameterNames = new HashMap(genericParameterNames); resolveGenericsHeader(node.getGenericsTypes()); Parameter[] paras = node.getParameters(); for (Parameter p : paras) { p.setInitialExpression(transform(p.getInitialExpression())); resolveOrFail(p.getType(), p.getType()); visitAnnotations(p); } ClassNode[] exceptions = node.getExceptions(); for (ClassNode t : exceptions) { resolveOrFail(t, node); } resolveOrFail(node.getReturnType(), node); MethodNode oldCurrentMethod = currentMethod; currentMethod = node; super.visitConstructorOrMethod(node, isConstructor); currentMethod = oldCurrentMethod; genericParameterNames = oldPNames; currentScope = oldScope; } public void visitField(FieldNode node) { ClassNode t = node.getType(); if(!fieldTypesChecked.contains(node)) { resolveOrFail(t, node); } super.visitField(node); } public void visitProperty(PropertyNode node) { ClassNode t = node.getType(); resolveOrFail(t, node); super.visitProperty(node); fieldTypesChecked.add(node.getField()); } private boolean resolveToInner (ClassNode type) { // we do not do our name mangling to find an inner class // if the type is a ConstructedClassWithPackage, because in this case we // are resolving the name at a different place already if (type instanceof ConstructedClassWithPackage) return false; String name = type.getName(); String saved = name; while (true) { int len = name.lastIndexOf('.'); if (len == -1) break; name = name.substring(0,len) + "$" + name.substring(len+1); type.setName(name); if (resolve(type)) return true; } if(resolveToInnerEnum (type)) return true; type.setName(saved); return false; } private boolean resolveToInnerEnum (ClassNode type) { // GROOVY-3110: It may be an inner enum defined by this class itself, in which case it does not need to be // explicitly qualified by the currentClass name String name = type.getName(); if(currentClass != type && !name.contains(".") && type.getClass().equals(ClassNode.class)) { type.setName(currentClass.getName() + "$" + name); if (resolve(type)) return true; } return false; } private void resolveOrFail(ClassNode type, String msg, ASTNode node) { if (resolve(type)) return; if (resolveToInner(type)) return; addError("unable to resolve class " + type.getName() + " " + msg, node); } private void resolveOrFail(ClassNode type, ASTNode node, boolean prefereImports) { resolveGenericsTypes(type.getGenericsTypes()); if (prefereImports && resolveAliasFromModule(type)) return; resolveOrFail(type, node); } private void resolveOrFail(ClassNode type, ASTNode node) { resolveOrFail(type, "", node); } private boolean resolve(ClassNode type) { return resolve(type, true, true, true); } private boolean resolve(ClassNode type, boolean testModuleImports, boolean testDefaultImports, boolean testStaticInnerClasses) { resolveGenericsTypes(type.getGenericsTypes()); if (type.isResolved() || type.isPrimaryClassNode()) return true; if (type.isArray()) { ClassNode element = type.getComponentType(); boolean resolved = resolve(element, testModuleImports, testDefaultImports, testStaticInnerClasses); if (resolved) { ClassNode cn = element.makeArray(); type.setRedirect(cn); } return resolved; } // test if vanilla name is current class name if (currentClass == type) return true; if (genericParameterNames.get(type.getName()) != null) { GenericsType gt = genericParameterNames.get(type.getName()); type.setRedirect(gt.getType()); type.setGenericsTypes(new GenericsType[]{gt}); type.setGenericsPlaceHolder(true); return true; } if (currentClass.getNameWithoutPackage().equals(type.getName())) { type.setRedirect(currentClass); return true; } return resolveNestedClass(type) || resolveFromModule(type, testModuleImports) || resolveFromCompileUnit(type) || resolveFromDefaultImports(type, testDefaultImports) || resolveFromStaticInnerClasses(type, testStaticInnerClasses) || resolveToClass(type); } private boolean resolveNestedClass(ClassNode type) { // we have for example a class name A, are in class X // and there is a nested class A$X. we want to be able // to access that class directly, so A becomes a valid // name in X. // GROOVY-4043: Do this check up the hierarchy, if needed Map hierClasses = new LinkedHashMap(); ClassNode val; String name; for(ClassNode classToCheck = currentClass; classToCheck != ClassHelper.OBJECT_TYPE; classToCheck = classToCheck.getSuperClass()) { if(classToCheck == null || hierClasses.containsKey(classToCheck.getName())) break; hierClasses.put(classToCheck.getName(), classToCheck); } for (ClassNode classToCheck : hierClasses.values()) { name = classToCheck.getName()+"$"+type.getName(); val = ClassHelper.make(name); if (resolveFromCompileUnit(val)) { type.setRedirect(val); return true; } } // another case we want to check here is if we are in a // nested class A$B$C and want to access B without // qualifying it by A.B. A alone will work, since that // is the qualified (minus package) name of that class // anyway. // That means if the current class is not an InnerClassNode // there is nothing to be done. if (!(currentClass instanceof InnerClassNode)) return false; // since we have B and want to get A we start with the most // outer class, put them together and then see if that does // already exist. In case of B from within A$B we are done // after the first step already. In case of for example // A.B.C.D.E.F and accessing E from F we test A$E=failed, // A$B$E=failed, A$B$C$E=fail, A$B$C$D$E=success LinkedList outerClasses = new LinkedList(); ClassNode outer = currentClass.getOuterClass(); while (outer!=null) { outerClasses.addFirst(outer); outer = outer.getOuterClass(); } // most outer class is now element 0 for (ClassNode testNode : outerClasses) { name = testNode.getName()+"$"+type.getName(); val = ClassHelper.make(name); if (resolveFromCompileUnit(val)) { type.setRedirect(val); return true; } } return false; } // NOTE: copied from GroovyClassLoader private long getTimeStamp(Class cls) { return Verifier.getTimestamp(cls); } // NOTE: copied from GroovyClassLoader private boolean isSourceNewer(URL source, Class cls) { try { long lastMod; // Special handling for file:// protocol, as getLastModified() often reports // incorrect results (-1) if (source.getProtocol().equals("file")) { // Coerce the file URL to a File String path = source.getPath().replace('/', File.separatorChar).replace('|', ':'); File file = new File(path); lastMod = file.lastModified(); } else { URLConnection conn = source.openConnection(); lastMod = conn.getLastModified(); conn.getInputStream().close(); } return lastMod > getTimeStamp(cls); } catch (IOException e) { // if the stream can't be opened, let's keep the old reference return false; } } private boolean resolveToScript(ClassNode type) { String name = type.getName(); if (name.startsWith("java.")) return type.isResolved(); //TODO: don't ignore inner static classes completely if (name.indexOf('$') != -1) return type.isResolved(); ModuleNode module = currentClass.getModule(); if (module.hasPackageName() && name.indexOf('.') == -1) return type.isResolved(); // try to find a script from classpath GroovyClassLoader gcl = compilationUnit.getClassLoader(); URL url = null; try { url = gcl.getResourceLoader().loadGroovySource(name); } catch (MalformedURLException e) { // fall through and let the URL be null } if (url != null) { if (type.isResolved()) { Class cls = type.getTypeClass(); // if the file is not newer we don't want to recompile if (!isSourceNewer(url, cls)) return true; // since we came to this, we want to recompile cachedClasses.remove(type.getName()); type.setRedirect(null); } SourceUnit su = compilationUnit.addSource(url); currentClass.getCompileUnit().addClassNodeToCompile(type, su); return true; } // type may be resolved through the classloader before return type.isResolved(); } private String replaceLastPoint(String name) { int lastPoint = name.lastIndexOf('.'); name = new StringBuffer() .append(name.substring(0, lastPoint)) .append("$") .append(name.substring(lastPoint + 1)) .toString(); return name; } private boolean resolveFromStaticInnerClasses(ClassNode type, boolean testStaticInnerClasses) { // a class consisting of a vanilla name can never be // a static inner class, because at least one dot is // required for this. Example: foo.bar -> foo$bar if (type instanceof LowerCaseClass) return false; // try to resolve a public static inner class' name testStaticInnerClasses &= type.hasPackageName(); if (testStaticInnerClasses) { if (type instanceof ConstructedClassWithPackage) { // we replace '.' only in the className part // with '$' to find an inner class. The case that // the package is really a class is handled elsewhere ConstructedClassWithPackage tmp = (ConstructedClassWithPackage) type; String savedName = tmp.className; tmp.className = replaceLastPoint(savedName); if (resolve(tmp, false, true, true)) { type.setRedirect(tmp.redirect()); return true; } tmp.className = savedName; } else { String savedName = type.getName(); String replacedPointType = replaceLastPoint(savedName); type.setName(replacedPointType); if (resolve(type, false, true, true)) return true; type.setName(savedName); } } return false; } private boolean resolveFromDefaultImports(ClassNode type, boolean testDefaultImports) { // test default imports testDefaultImports &= !type.hasPackageName(); // we do not resolve a vanilla name starting with a lower case letter // try to resolve against a default import, because we know that the // default packages do not contain classes like these testDefaultImports &= !(type instanceof LowerCaseClass); if (testDefaultImports) { for (int i = 0, size = DEFAULT_IMPORTS.length; i < size; i++) { String packagePrefix = DEFAULT_IMPORTS[i]; String name = type.getName(); // We limit the inner class lookups here by using ConstructedClassWithPackage. // This way only the name will change, the packagePrefix will // not be included in the lookup. The case where the // packagePrefix is really a class is handled elsewhere. // WARNING: This code does not expect a class that has a static // inner class in DEFAULT_IMPORTS ConstructedClassWithPackage tmp = new ConstructedClassWithPackage(packagePrefix,name); if (resolve(tmp, false, false, false)) { type.setRedirect(tmp.redirect()); return true; } } String name = type.getName(); if (name.equals("BigInteger")) { type.setRedirect(ClassHelper.BigInteger_TYPE); return true; } else if (name.equals("BigDecimal")) { type.setRedirect(ClassHelper.BigDecimal_TYPE); return true; } } return false; } private boolean resolveFromCompileUnit(ClassNode type) { // look into the compile unit if there is a class with that name CompileUnit compileUnit = currentClass.getCompileUnit(); if (compileUnit == null) return false; ClassNode cuClass = compileUnit.getClass(type.getName()); if (cuClass != null) { if (type != cuClass) type.setRedirect(cuClass); return true; } return false; } private void ambiguousClass(ClassNode type, ClassNode iType, String name) { if (type.getName().equals(iType.getName())) { addError("reference to " + name + " is ambiguous, both class " + type.getName() + " and " + iType.getName() + " match", type); } else { type.setRedirect(iType); } } private boolean resolveAliasFromModule(ClassNode type) { // In case of getting a ConstructedClassWithPackage here we do not do checks for partial // matches with imported classes. The ConstructedClassWithPackage is already a constructed // node and any subclass resolving will then take place elsewhere if (type instanceof ConstructedClassWithPackage) return false; ModuleNode module = currentClass.getModule(); if (module == null) return false; String name = type.getName(); // check module node imports aliases // the while loop enables a check for inner classes which are not fully imported, // but visible as the surrounding class is imported and the inner class is public/protected static String pname = name; int index = name.length(); /* * we have a name foo.bar and an import foo.foo. This means foo.bar is possibly * foo.foo.bar rather than foo.bar. This means to cut at the dot in foo.bar and * foo for import */ while (true) { pname = name.substring(0, index); ClassNode aliasedNode = null; ImportNode importNode = module.getImport(pname); if (importNode != null && importNode != currImportNode) { aliasedNode = importNode.getType(); } if (aliasedNode == null) { importNode = module.getStaticImports().get(pname); if (importNode != null && importNode != currImportNode) { // static alias only for inner classes and must be at end of chain ClassNode tmp = ClassHelper.make(importNode.getType().getName() + "$" + importNode.getFieldName()); if (resolve(tmp, false, false, true)) { if ((tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) { type.setRedirect(tmp.redirect()); return true; } } } } if (aliasedNode != null) { if (pname.length() == name.length()) { // full match // We can compare here by length, because pname is always // a substring of name, so same length means they are equal. type.setRedirect(aliasedNode); return true; } else { //partial match // At this point we know that we have a match for pname. This may // mean, that name[pname.length()..<-1] is a static inner class. // For this the rest of the name does not need any dots in its name. // It is either completely a inner static class or it is not. // Since we do not want to have useless lookups we create the name // completely and use a ConstructedClassWithPackage to prevent lookups against the package. String className = aliasedNode.getNameWithoutPackage() + '$' + name.substring(pname.length() + 1).replace('.', '$'); ConstructedClassWithPackage tmp = new ConstructedClassWithPackage(aliasedNode.getPackageName()+".", className); if (resolve(tmp, true, true, false)) { type.setRedirect(tmp.redirect()); return true; } } } index = pname.lastIndexOf('.'); if (index == -1) break; } return false; } private boolean resolveFromModule(ClassNode type, boolean testModuleImports) { // we decided if we have a vanilla name starting with a lower case // letter that we will not try to resolve this name against .* // imports. Instead a full import is needed for these. // resolveAliasFromModule will do this check for us. This method // does also check the module contains a class in the same package // of this name. This check is not done for vanilla names starting // with a lower case letter anymore if (type instanceof LowerCaseClass) { return resolveAliasFromModule(type); } String name = type.getName(); ModuleNode module = currentClass.getModule(); if (module == null) return false; boolean newNameUsed = false; // we add a package if there is none yet and the module has one. But we // do not add that if the type is a ConstructedClassWithPackage. The code in ConstructedClassWithPackage // hasPackageName() will return true if ConstructedClassWithPackage#className has no dots. // but since the prefix may have them and the code there does ignore that // fact. We check here for ConstructedClassWithPackage. if (!type.hasPackageName() && module.hasPackageName() && !(type instanceof ConstructedClassWithPackage)) { type.setName(module.getPackageName() + name); newNameUsed = true; } // look into the module node if there is a class with that name List moduleClasses = module.getClasses(); for (ClassNode mClass : moduleClasses) { if (mClass.getName().equals(type.getName())) { if (mClass != type) type.setRedirect(mClass); return true; } } if (newNameUsed) type.setName(name); if (testModuleImports) { if (resolveAliasFromModule(type)) return true; if (module.hasPackageName()) { // check package this class is defined in. The usage of ConstructedClassWithPackage here // means, that the module package will not be involved when the // compiler tries to find an inner class. ConstructedClassWithPackage tmp = new ConstructedClassWithPackage(module.getPackageName(), name); if (resolve(tmp, false, false, false)) { ambiguousClass(type, tmp, name); type.setRedirect(tmp.redirect()); return true; } } // check module static imports (for static inner classes) for (ImportNode importNode : module.getStaticImports().values()) { if (importNode.getFieldName().equals(name)) { ClassNode tmp = ClassHelper.make(importNode.getType().getName() + "$" + name); if (resolve(tmp, false, false, true)) { if ((tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) { type.setRedirect(tmp.redirect()); return true; } } } } // check module node import packages for (ImportNode importNode : module.getStarImports()) { String packagePrefix = importNode.getPackageName(); // We limit the inner class lookups here by using ConstructedClassWithPackage. // This way only the name will change, the packagePrefix will // not be included in the lookup. The case where the // packagePrefix is really a class is handled elsewhere. ConstructedClassWithPackage tmp = new ConstructedClassWithPackage(packagePrefix, name); if (resolve(tmp, false, false, true)) { ambiguousClass(type, tmp, name); type.setRedirect(tmp.redirect()); return true; } } // check for star imports (import static pkg.Outer.*) matching static inner classes for (ImportNode importNode : module.getStaticStarImports().values()) { ClassNode tmp = ClassHelper.make(importNode.getClassName() + "$" + name); if (resolve(tmp, false, false, true)) { if ((tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) { ambiguousClass(type, tmp, name); type.setRedirect(tmp.redirect()); return true; } } } } return false; } private boolean resolveToClass(ClassNode type) { String name = type.getName(); // We use here the class cache cachedClasses to prevent // calls to ClassLoader#loadClass. disabling this cache will // cause a major performance hit. Unlike at the end of this // method we do not return true or false depending on if we // want to recompile or not. If the class was cached, then // we do not want to recompile, recompilation is already // scheduled then Object cached = cachedClasses.get(name); if (cached == NO_CLASS) return false; if (cached != null) { // cached == SCRIPT should not happen here! type.setRedirect((ClassNode) cached); return true; } // We do not need to check instances of LowerCaseClass // to be a Class, because unless there was an import for // for this we do not lookup these cases. This was a decision // made on the mailing list. To ensure we will not visit this // method again we set a NO_CLASS for this name if (type instanceof LowerCaseClass) { cachedClasses.put(name,NO_CLASS); return false; } if (currentClass.getModule().hasPackageName() && name.indexOf('.') == -1) return false; GroovyClassLoader loader = compilationUnit.getClassLoader(); Class cls; try { // NOTE: it's important to do no lookup against script files // here since the GroovyClassLoader would create a new CompilationUnit cls = loader.loadClass(name, false, true); } catch (ClassNotFoundException cnfe) { cachedClasses.put(name, NO_CLASS); return resolveToScript(type); } catch (CompilationFailedException cfe) { compilationUnit.getErrorCollector().addErrorAndContinue(new ExceptionMessage(cfe, true, source)); return resolveToScript(type); } //TODO: the case of a NoClassDefFoundError needs a bit more research // a simple recompilation is not possible it seems. The current class // we are searching for is there, so we should mark that somehow. // Basically the missing class needs to be completely compiled before // we can again search for the current name. /*catch (NoClassDefFoundError ncdfe) { cachedClasses.put(name,SCRIPT); return false; }*/ if (cls == null) return false; ClassNode cn = ClassHelper.make(cls); cachedClasses.put(name, cn); type.setRedirect(cn); //NOTE: we might return false here even if we found a class, // because we want to give a possible script a chance to // recompile. This can only be done if the loader was not // the instance defining the class. return cls.getClassLoader() == loader || resolveToScript(type); } public Expression transform(Expression exp) { if (exp == null) return null; Expression ret = null; if (exp instanceof VariableExpression) { ret = transformVariableExpression((VariableExpression) exp); } else if (exp.getClass() == PropertyExpression.class) { ret = transformPropertyExpression((PropertyExpression) exp); } else if (exp instanceof DeclarationExpression) { ret = transformDeclarationExpression((DeclarationExpression) exp); } else if (exp instanceof BinaryExpression) { ret = transformBinaryExpression((BinaryExpression) exp); } else if (exp instanceof MethodCallExpression) { ret = transformMethodCallExpression((MethodCallExpression) exp); } else if (exp instanceof ClosureExpression) { ret = transformClosureExpression((ClosureExpression) exp); } else if (exp instanceof ConstructorCallExpression) { ret = transformConstructorCallExpression((ConstructorCallExpression) exp); } else if (exp instanceof AnnotationConstantExpression) { ret = transformAnnotationConstantExpression((AnnotationConstantExpression) exp); } else { resolveOrFail(exp.getType(), exp); ret = exp.transformExpression(this); } if (ret!=null && ret!=exp) ret.setSourcePosition(exp); return ret; } private String lookupClassName(PropertyExpression pe) { boolean doInitialClassTest=true; String name = ""; // this loop builds a name from right to left each name part // separated by "." for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof VariableExpression) { VariableExpression ve = (VariableExpression) it; // stop at super and this if (ve.isSuperExpression() || ve.isThisExpression()) { return null; } String varName = ve.getName(); if (doInitialClassTest) { // we are at the first name part. This is the right most part. // If this part is in lower case, then we do not need a class // check. other parts of the property expression will be tested // by a different method call to this method, so foo.Bar.bar // can still be resolved to the class foo.Bar and the static // field bar. if (!testVanillaNameForClass(varName)) return null; doInitialClassTest = false; name = varName; } else { name = varName + "." + name; } break; } // anything other than PropertyExpressions or // VariableExpressions will stop resolving else if (it.getClass() != PropertyExpression.class) { return null; } else { PropertyExpression current = (PropertyExpression) it; String propertyPart = current.getPropertyAsString(); // the class property stops resolving, dynamic property names too if (propertyPart == null || propertyPart.equals("class")) { return null; } if (doInitialClassTest) { // we are at the first name part. This is the right most part. // If this part is in lower case, then we do not need a class // check. other parts of the property expression will be tested // by a different method call to this method, so foo.Bar.bar // can still be resolved to the class foo.Bar and the static // field bar. if (!testVanillaNameForClass(propertyPart)) return null; doInitialClassTest= false; name = propertyPart; } else { name = propertyPart + "." + name; } } } if (name.length() == 0) return null; return name; } // iterate from the inner most to the outer and check for classes // this check will ignore a .class property, for Example Integer.class will be // a PropertyExpression with the ClassExpression of Integer as objectExpression // and class as property private Expression correctClassClassChain(PropertyExpression pe) { LinkedList stack = new LinkedList(); ClassExpression found = null; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof ClassExpression) { found = (ClassExpression) it; break; } else if (!(it.getClass() == PropertyExpression.class)) { return pe; } stack.addFirst(it); } if (found == null) return pe; if (stack.isEmpty()) return pe; Object stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpression = (PropertyExpression) stackElement; String propertyNamePart = classPropertyExpression.getPropertyAsString(); if (propertyNamePart == null || !propertyNamePart.equals("class")) return pe; found.setSourcePosition(classPropertyExpression); if (stack.isEmpty()) return found; stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement; classPropertyExpressionContainer.setObjectExpression(found); return pe; } protected Expression transformPropertyExpression(PropertyExpression pe) { boolean itlp = isTopLevelProperty; boolean ipe = inPropertyExpression; Expression objectExpression = pe.getObjectExpression(); inPropertyExpression = true; isTopLevelProperty = (objectExpression.getClass() != PropertyExpression.class); objectExpression = transform(objectExpression); // we handle the property part as if it were not part of the property inPropertyExpression = false; Expression property = transform(pe.getProperty()); isTopLevelProperty = itlp; inPropertyExpression = ipe; boolean spreadSafe = pe.isSpreadSafe(); PropertyExpression old = pe; pe = new PropertyExpression(objectExpression, property, pe.isSafe()); pe.setSpreadSafe(spreadSafe); pe.setSourcePosition(old); String className = lookupClassName(pe); if (className != null) { ClassNode type = ClassHelper.make(className); if (resolve(type)) { Expression ret = new ClassExpression(type); ret.setSourcePosition(pe); return ret; } } if (objectExpression instanceof ClassExpression && pe.getPropertyAsString() != null) { // possibly an inner class ClassExpression ce = (ClassExpression) objectExpression; ClassNode type = ClassHelper.make(ce.getType().getName() + "$" + pe.getPropertyAsString()); if (resolve(type, false, false, false)) { Expression ret = new ClassExpression(type); ret.setSourcePosition(ce); return ret; } } Expression ret = pe; checkThisAndSuperAsPropertyAccess(pe); if (isTopLevelProperty) ret = correctClassClassChain(pe); return ret; } private void checkThisAndSuperAsPropertyAccess(PropertyExpression expression) { if (expression.isImplicitThis()) return; String prop = expression.getPropertyAsString(); if (prop == null) return; if (!prop.equals("this") && !prop.equals("super")) return; if (expression.getObjectExpression() instanceof ClassExpression) { if (!(currentClass instanceof InnerClassNode)) { addError("The usage of 'Class.this' and 'Class.super' is only allowed in nested/inner classes.", expression); return; } ClassNode type = expression.getObjectExpression().getType(); ClassNode iterType = currentClass; while (iterType != null) { if (iterType.equals(type)) break; iterType = iterType.getOuterClass(); } if (iterType == null) { addError("The class '" + type.getName() + "' needs to be an outer class of '" + currentClass.getName() + "' when using '.this' or '.super'.", expression); } if ((currentClass.getModifiers() & Opcodes.ACC_STATIC) == 0) return; if (!currentScope.isInStaticContext()) return; addError("The usage of 'Class.this' and 'Class.super' within static nested class '" + currentClass.getName() + "' is not allowed in a static context.", expression); } } protected Expression transformVariableExpression(VariableExpression ve) { visitAnnotations(ve); Variable v = ve.getAccessedVariable(); if(!(v instanceof DynamicVariable) && !checkingVariableTypeInDeclaration) { /* * GROOVY-4009: when a normal variable is simply being used, there is no need to try to * resolve its type. Variable type resolve should proceed only if the variable is being declared. */ return ve; } if (v instanceof DynamicVariable){ String name = ve.getName(); ClassNode t = ClassHelper.make(name); // asking isResolved here allows to check if a primitive // type name like "int" was used to make t. In such a case // we have nothing left to do. boolean isClass = t.isResolved(); if (!isClass) { // It was no primitive type, so next we see if the name, // which is a vanilla name, starts with a lower case letter. // In that case we change it to a LowerCaseClass to let the // compiler skip the resolving at several places in this class. if (Character.isLowerCase(name.charAt(0))) { t = new LowerCaseClass(name); } isClass = resolve(t); if(!isClass) isClass = resolveToInnerEnum(t); } if (isClass) { // the name is a type so remove it from the scoping // as it is only a classvariable, it is only in // referencedClassVariables, but must be removed // for each parentscope too for (VariableScope scope = currentScope; scope != null && !scope.isRoot(); scope = scope.getParent()) { if (scope.isRoot()) break; if (scope.removeReferencedClassVariable(ve.getName()) == null) break; } ClassExpression ce = new ClassExpression(t); ce.setSourcePosition(ve); return ce; } } resolveOrFail(ve.getType(), ve); return ve; } private boolean testVanillaNameForClass(String name) { if (name==null || name.length()==0) return false; return !Character.isLowerCase(name.charAt(0)); } protected Expression transformBinaryExpression(BinaryExpression be) { Expression left = transform(be.getLeftExpression()); int type = be.getOperation().getType(); if ((type == Types.ASSIGNMENT_OPERATOR || type == Types.EQUAL) && left instanceof ClassExpression) { ClassExpression ce = (ClassExpression) left; String error = "you tried to assign a value to the class '" + ce.getType().getName() + "'"; if (ce.getType().isScript()) { error += ". Do you have a script with this name?"; } addError(error, be.getLeftExpression()); return be; } if (left instanceof ClassExpression) { if (be.getRightExpression() instanceof ListExpression) { ListExpression list = (ListExpression) be.getRightExpression(); if (list.getExpressions().isEmpty()) { // we have C[] if the list is empty -> should be an array then! final ClassExpression ce = new ClassExpression(left.getType().makeArray()); ce.setSourcePosition(be); return ce; } else { // may be we have C[k1:v1, k2:v2] -> should become (C)([k1:v1, k2:v2]) boolean map = true; for (Expression expression : list.getExpressions()) { if(!(expression instanceof MapEntryExpression)) { map = false; break; } } if (map) { final MapExpression me = new MapExpression(); for (Expression expression : list.getExpressions()) { me.addMapEntryExpression((MapEntryExpression) transform(expression)); } me.setSourcePosition(list); final CastExpression ce = new CastExpression(left.getType(), me); ce.setSourcePosition(be); return ce; } } } if (be.getRightExpression() instanceof MapEntryExpression) { // may be we have C[k1:v1] -> should become (C)([k1:v1]) final MapExpression me = new MapExpression(); me.addMapEntryExpression((MapEntryExpression) transform(be.getRightExpression())); me.setSourcePosition(be.getRightExpression()); final CastExpression ce = new CastExpression(left.getType(), me); ce.setSourcePosition(be); return ce; } } Expression right = transform(be.getRightExpression()); be.setLeftExpression(left); be.setRightExpression(right); return be; } protected Expression transformClosureExpression(ClosureExpression ce) { boolean oldInClosure = inClosure; inClosure = true; Parameter[] paras = ce.getParameters(); if (paras != null) { for (Parameter para : paras) { ClassNode t = para.getType(); resolveOrFail(t, ce); visitAnnotations(para); if (para.hasInitialExpression()) { Object initialVal = para.getInitialExpression(); if (initialVal instanceof Expression) { para.setInitialExpression(transform((Expression) initialVal)); } } visitAnnotations(para); } } Statement code = ce.getCode(); if (code != null) code.visit(this); inClosure = oldInClosure; return ce; } protected Expression transformConstructorCallExpression(ConstructorCallExpression cce) { ClassNode type = cce.getType(); resolveOrFail(type, cce); if (Modifier.isAbstract(type.getModifiers())) { addError("You cannot create an instance from the abstract " + getDescription(type) + ".", cce); } Expression ret = cce.transformExpression(this); return ret; } private String getDescription(ClassNode node) { return (node.isInterface() ? "interface" : "class") + " '" + node.getName() + "'"; } protected Expression transformMethodCallExpression(MethodCallExpression mce) { Expression args = transform(mce.getArguments()); Expression method = transform(mce.getMethod()); Expression object = transform(mce.getObjectExpression()); resolveGenericsTypes(mce.getGenericsTypes()); MethodCallExpression result = new MethodCallExpression(object, method, args); result.setSafe(mce.isSafe()); result.setImplicitThis(mce.isImplicitThis()); result.setSpreadSafe(mce.isSpreadSafe()); result.setSourcePosition(mce); result.setGenericsTypes(mce.getGenericsTypes()); result.setMethodTarget(mce.getMethodTarget()); return result; } protected Expression transformDeclarationExpression(DeclarationExpression de) { visitAnnotations(de); Expression oldLeft = de.getLeftExpression(); checkingVariableTypeInDeclaration = true; Expression left = transform(oldLeft); checkingVariableTypeInDeclaration = false; if (left instanceof ClassExpression) { ClassExpression ce = (ClassExpression) left; addError("you tried to assign a value to the class " + ce.getType().getName(), oldLeft); return de; } Expression right = transform(de.getRightExpression()); if (right == de.getRightExpression()) { fixDeclaringClass(de); return de; } DeclarationExpression newDeclExpr = new DeclarationExpression(left, de.getOperation(), right); newDeclExpr.setDeclaringClass(de.getDeclaringClass()); fixDeclaringClass(newDeclExpr); newDeclExpr.setSourcePosition(de); newDeclExpr.addAnnotations(de.getAnnotations()); return newDeclExpr; } // TODO get normal resolving to set declaring class private void fixDeclaringClass(DeclarationExpression newDeclExpr) { if (newDeclExpr.getDeclaringClass() == null && currentMethod != null) { newDeclExpr.setDeclaringClass(currentMethod.getDeclaringClass()); } } protected Expression transformAnnotationConstantExpression(AnnotationConstantExpression ace) { AnnotationNode an = (AnnotationNode) ace.getValue(); ClassNode type = an.getClassNode(); resolveOrFail(type, ", unable to find class for annotation", an); for (Map.Entry member : an.getMembers().entrySet()) { member.setValue(transform(member.getValue())); } return ace; } public void visitAnnotations(AnnotatedNode node) { List annotations = node.getAnnotations(); if (annotations.isEmpty()) return; Map tmpAnnotations = new HashMap(); ClassNode annType; for (AnnotationNode an : annotations) { // skip built-in properties if (an.isBuiltIn()) continue; annType = an.getClassNode(); resolveOrFail(annType, ", unable to find class for annotation", an); for (Map.Entry member : an.getMembers().entrySet()) { Expression newValue = transform(member.getValue()); newValue = transformInlineConstants(newValue); member.setValue(newValue); checkAnnotationMemberValue(newValue); } if(annType.isResolved()) { Class annTypeClass = annType.getTypeClass(); Retention retAnn = (Retention) annTypeClass.getAnnotation(Retention.class); if (retAnn != null && retAnn.value().equals(RetentionPolicy.RUNTIME)) { AnnotationNode anyPrevAnnNode = tmpAnnotations.put(annTypeClass.getName(), an); if(anyPrevAnnNode != null) { addError("Cannot specify duplicate annotation on the same member : " + annType.getName(), an); } } } } } // resolve constant-looking expressions statically (do here as gets transformed away later) private Expression transformInlineConstants(Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum()) return exp; FieldNode fn = type.getField(pe.getPropertyAsString()); if (fn != null && !fn.isEnum() && fn.isStatic() && fn.isFinal()) { if (fn.getInitialValueExpression() instanceof ConstantExpression) { return fn.getInitialValueExpression(); } } } } else if (exp instanceof ListExpression) { ListExpression le = (ListExpression) exp; ListExpression result = new ListExpression(); for (Expression e : le.getExpressions()) { result.addExpression(transformInlineConstants(e)); } return result; } else if (exp instanceof AnnotationConstantExpression) { ConstantExpression ce = (ConstantExpression) exp; if (ce.getValue() instanceof AnnotationNode) { // replicate a little bit of AnnotationVisitor here // because we can't wait until later to do this AnnotationNode an = (AnnotationNode) ce.getValue(); for (Map.Entry member : an.getMembers().entrySet()) { member.setValue(transformInlineConstants(member.getValue())); } } } return exp; } private void checkAnnotationMemberValue(Expression newValue) { if (newValue instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) newValue; if (!(pe.getObjectExpression() instanceof ClassExpression)) { addError("unable to find class '" + pe.getText() + "' for annotation attribute constant", pe.getObjectExpression()); } } else if (newValue instanceof ListExpression) { ListExpression le = (ListExpression) newValue; for (Expression e : le.getExpressions()) { checkAnnotationMemberValue(e); } } } public void visitClass(ClassNode node) { ClassNode oldNode = currentClass; if (node instanceof InnerClassNode) { if (Modifier.isStatic(node.getModifiers())) { genericParameterNames = new HashMap(); } } else { genericParameterNames = new HashMap(); } currentClass = node; resolveGenericsHeader(node.getGenericsTypes()); ModuleNode module = node.getModule(); if (!module.hasImportsResolved()) { for (ImportNode importNode : module.getImports()) { currImportNode = importNode; ClassNode type = importNode.getType(); if (resolve(type, false, false, true)) { currImportNode = null; continue; } currImportNode = null; addError("unable to resolve class " + type.getName(), type); } for (ImportNode importNode : module.getStaticStarImports().values()) { ClassNode type = importNode.getType(); if (resolve(type, false, false, true)) continue; // Maybe this type belongs in the same package as the node that is doing the // static import. In that case, the package may not have been explicitly specified. // Try with the node's package too. If still not found, revert to original type name. if (type.getPackageName() == null && node.getPackageName() != null) { String oldTypeName = type.getName(); type.setName(node.getPackageName() + "." + oldTypeName); if (resolve(type, false, false, true)) continue; type.setName(oldTypeName); } addError("unable to resolve class " + type.getName(), type); } for (ImportNode importNode : module.getStaticImports().values()) { ClassNode type = importNode.getType(); if (resolve(type, true, true, true)) continue; addError("unable to resolve class " + type.getName(), type); } for (ImportNode importNode : module.getStaticStarImports().values()) { ClassNode type = importNode.getType(); if (resolve(type, true, true, true)) continue; addError("unable to resolve class " + type.getName(), type); } module.setImportsResolved(true); } ClassNode sn = node.getUnresolvedSuperClass(); if (sn != null) resolveOrFail(sn, node, true); for (ClassNode anInterface : node.getInterfaces()) { resolveOrFail(anInterface, node, true); } checkCyclicInheritence(node, node.getUnresolvedSuperClass(), node.getInterfaces()); super.visitClass(node); currentClass = oldNode; } private void checkCyclicInheritence(ClassNode originalNode, ClassNode parentToCompare, ClassNode[] interfacesToCompare) { if(!originalNode.isInterface()) { if(parentToCompare == null) return; if(originalNode == parentToCompare.redirect()) { addError("Cyclic inheritance involving " + parentToCompare.getName() + " in class " + originalNode.getName(), originalNode); return; } if(interfacesToCompare != null && interfacesToCompare.length > 0) { for(ClassNode intfToCompare : interfacesToCompare) { if(originalNode == intfToCompare.redirect()) { addError("Cycle detected: the type " + originalNode.getName() + " cannot implement itself" , originalNode); return; } } } if(parentToCompare == ClassHelper.OBJECT_TYPE) return; checkCyclicInheritence(originalNode, parentToCompare.getUnresolvedSuperClass(), null); } else { if(interfacesToCompare != null && interfacesToCompare.length > 0) { // check interfaces at this level first for(ClassNode intfToCompare : interfacesToCompare) { if(originalNode == intfToCompare.redirect()) { addError("Cyclic inheritance involving " + intfToCompare.getName() + " in interface " + originalNode.getName(), originalNode); return; } } // check next level of interfaces for(ClassNode intf : interfacesToCompare) { checkCyclicInheritence(originalNode, null, intf.getInterfaces()); } } else { return; } } } public void visitCatchStatement(CatchStatement cs) { resolveOrFail(cs.getExceptionType(), cs); if (cs.getExceptionType() == ClassHelper.DYNAMIC_TYPE) { cs.getVariable().setType(ClassHelper.make(Exception.class)); } super.visitCatchStatement(cs); } public void visitForLoop(ForStatement forLoop) { resolveOrFail(forLoop.getVariableType(), forLoop); super.visitForLoop(forLoop); } public void visitBlockStatement(BlockStatement block) { VariableScope oldScope = currentScope; currentScope = block.getVariableScope(); super.visitBlockStatement(block); currentScope = oldScope; } protected SourceUnit getSourceUnit() { return source; } private void resolveGenericsTypes(GenericsType[] types) { if (types == null) return; currentClass.setUsingGenerics(true); for (GenericsType type : types) { resolveGenericsType(type); } } private void resolveGenericsHeader(GenericsType[] types) { if (types == null) return; currentClass.setUsingGenerics(true); for (GenericsType type : types) { ClassNode classNode = type.getType(); String name = type.getName(); ClassNode[] bounds = type.getUpperBounds(); if (bounds != null) { boolean nameAdded = false; for (ClassNode upperBound : bounds) { if (!nameAdded && upperBound != null || !resolve(classNode)) { genericParameterNames.put(name, type); type.setPlaceholder(true); classNode.setRedirect(upperBound); nameAdded = true; } resolveOrFail(upperBound, classNode); } } else { genericParameterNames.put(name, type); classNode.setRedirect(ClassHelper.OBJECT_TYPE); type.setPlaceholder(true); } } } private void resolveGenericsType(GenericsType genericsType) { if (genericsType.isResolved()) return; currentClass.setUsingGenerics(true); ClassNode type = genericsType.getType(); // save name before redirect String name = type.getName(); ClassNode[] bounds = genericsType.getUpperBounds(); if (!genericParameterNames.containsKey(name)) { if (bounds != null) { for (ClassNode upperBound : bounds) { resolveOrFail(upperBound, genericsType); type.setRedirect(upperBound); resolveGenericsTypes(upperBound.getGenericsTypes()); } } else if (genericsType.isWildcard()) { type.setRedirect(ClassHelper.OBJECT_TYPE); } else { resolveOrFail(type, genericsType); } } else { GenericsType gt = genericParameterNames.get(name); type.setRedirect(gt.getType()); genericsType.setPlaceholder(true); } if (genericsType.getLowerBound() != null) { resolveOrFail(genericsType.getLowerBound(), genericsType); } resolveGenericsTypes(type.getGenericsTypes()); genericsType.setResolved(genericsType.getType().isResolved()); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/0000755001501200150120000000000011627206700022103 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/control/io/AbstractReaderSource.java0000644001501200150120000000707011627206700027021 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.BufferedReader; import java.io.IOException; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Janitor; /** * For ReaderSources that can choose a parent class, a base that * provides common functionality. * * @author Chris Poirier * @version $Id$ */ public abstract class AbstractReaderSource implements ReaderSource { protected CompilerConfiguration configuration; // Configuration data public AbstractReaderSource(CompilerConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException("Compiler configuration must not be null!"); // ... or more relaxed? // configuration = CompilerConfiguration.DEFAULT; } this.configuration = configuration; } /** * Returns true if the source can be restarted (ie. if getReader() * will return non-null on subsequent calls. */ public boolean canReopenSource() { return true; } private BufferedReader lineSource = null; // If set, a reader on the current source file private String line = null; // The last line read from the current source file private int number = 0; // The last line number read /** * Returns a line from the source, or null, if unavailable. If * you supply a Janitor, resources will be cached. */ public String getLine(int lineNumber, Janitor janitor) { // If the source is already open and is passed the line we // want, close it. if (lineSource != null && number > lineNumber) { cleanup(); } // If the line source is closed, try to open it. if (lineSource == null) { try { lineSource = new BufferedReader(getReader()); } catch (Exception e) { // Ignore } number = 0; } // Read until the appropriate line number. if (lineSource != null) { while (number < lineNumber) { try { line = lineSource.readLine(); number++; } catch (IOException e) { cleanup(); } } if (janitor == null) { final String result = line; // otherwise cleanup() will wipe out value cleanup(); return result; } else { janitor.register(this); } } return line; } /** * Cleans up any cached resources used by getLine(). */ public void cleanup() { if (lineSource != null) { try { lineSource.close(); } catch (Exception e) { // Ignore } } lineSource = null; line = null; number = 0; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/package.html0000644001501200150120000000025011627206700024361 0ustar miguelmiguel package org.codehaus.groovy.control.io.*

    Internal classes for Groovier Input/Output.

    groovy-1.8.6/src/main/org/codehaus/groovy/control/io/NullWriter.java0000644001501200150120000000203611627206700025056 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.Writer; /** * An Writer than eats its input. * * @author Chris Poirier * * @version $Id$ */ public class NullWriter extends Writer { public static final NullWriter DEFAULT = new NullWriter(); public void close() {} public void flush() {} public void write( char[] cbuf, int off, int len ) {} } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/InputStreamReaderSource.java0000644001501200150120000000375211627206700027534 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.codehaus.groovy.control.CompilerConfiguration; /** * A ReaderSource for source strings. * * @author Chris Poirier * @version $Id$ */ public class InputStreamReaderSource extends AbstractReaderSource { private InputStream stream; // The InputStream from which we produce a Reader. /** * Creates the ReaderSource from a File descriptor. * * @param stream stream containing source * @param configuration configuration for compiling source */ public InputStreamReaderSource(InputStream stream, CompilerConfiguration configuration) { super(configuration); this.stream = stream; } /** * Returns a new Reader on the underlying source object. */ public Reader getReader() throws IOException { if (stream != null) { Reader reader = new InputStreamReader(stream, configuration.getSourceEncoding()); stream = null; return reader; } return null; } /** * Returns true if the source can be restarted (ie. if getReader() * will return non-null on subsequent calls. */ public boolean canReopenSource() { return false; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/FileReaderSource.java0000644001501200150120000000444311627206700026136 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.*; import java.nio.charset.Charset; import org.codehaus.groovy.control.CompilerConfiguration; /** * A ReaderSource for source files. * * @author Chris Poirier * @version $Id$ */ public class FileReaderSource extends AbstractReaderSource { private File file; // The File from which we produce Readers. private final Charset UTF8 = Charset.forName("UTF-8"); /** * Creates the ReaderSource from a File descriptor. * @param file script source file * @param configuration configuration for compiling source */ public FileReaderSource( File file, CompilerConfiguration configuration ) { super( configuration ); this.file = file; } /** * Returns a new Reader on the underlying source object. */ public Reader getReader() throws IOException { // we want to remove the BOM windows adds from a file if the encoding is UTF-8 // in other cases we depend on the charsets Charset cs = Charset.forName(configuration.getSourceEncoding()); InputStream in = new BufferedInputStream(new FileInputStream(file)); if (UTF8.name().equalsIgnoreCase(cs.name())) { in.mark(3); boolean hasBOM = true; try { int i = in.read(); hasBOM &= i == 0xEF; i = in.read(); hasBOM &= i == 0xBB; i = in.read(); hasBOM &= i == 0xFF; } catch (IOException ioe) { hasBOM= false; } if (!hasBOM) in.reset(); } return new InputStreamReader( in, cs ); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/URLReaderSource.java0000644001501200150120000000317111627206700025716 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import org.codehaus.groovy.control.CompilerConfiguration; /** * A ReaderSource for source files hosted at a URL. * * @author Chris Poirier * * @version $Id$ */ public class URLReaderSource extends AbstractReaderSource { private URL url; // The URL from which we produce Readers. /** * Creates the ReaderSource from a File descriptor. * @param url url pointing to script source * @param configuration configuration for compiling source */ public URLReaderSource( URL url, CompilerConfiguration configuration ) { super( configuration ); this.url = url; } /** * Returns a new Reader on the underlying source object. */ public Reader getReader() throws IOException { return new InputStreamReader( url.openStream(), configuration.getSourceEncoding() ); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/ReaderSource.java0000644001501200150120000000374611627206700025343 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.IOException; import java.io.Reader; import org.codehaus.groovy.control.HasCleanup; import org.codehaus.groovy.control.Janitor; /** * An interface for things that can supply (and potentially resupply) a Reader * on a source stream. * * @author Chris Poirier * * @version $Id$ */ public interface ReaderSource extends HasCleanup { /** * Returns a new Reader on the underlying source object. Returns * null if the source can't be reopened. * @throws java.io.IOException if there was an error opening for stream * @return the reader to the resource */ Reader getReader() throws IOException; /** * Returns true if the source can be restarted (ie. if getReader() * will return non-null on subsequent calls. * @return true if the resource can be reopened for reading */ boolean canReopenSource(); /** * Returns a line from the source, or null, if unavailable. If * you supply a Janitor, resources will be cached. * @param lineNumber the number of the line of interest * @param janitor helper to clean up afterwards * @return the line of interest */ String getLine( int lineNumber, Janitor janitor ); /** * Cleans up any cached resources used by getLine(). */ void cleanup(); } groovy-1.8.6/src/main/org/codehaus/groovy/control/io/StringReaderSource.java0000644001501200150120000000310611627206700026520 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.io; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import org.codehaus.groovy.control.CompilerConfiguration; /** * A ReaderSource for source strings. * * @author Chris Poirier * * @version $Id$ */ public class StringReaderSource extends AbstractReaderSource { private final String string; // The String from which we produce Readers. /** * Creates the ReaderSource from a File descriptor. * * @param string string containing script source * @param configuration configuration for compiling source */ public StringReaderSource( String string, CompilerConfiguration configuration ) { super( configuration ); this.string = string; } /** * Returns a new Reader on the underlying source object. */ public Reader getReader() throws IOException { return new StringReader( string ); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/OptimizerVisitor.java0000644001501200150120000000721111707612046025705 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.ast.ClassCodeExpressionTransformer; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.objectweb.asm.Opcodes; import java.util.*; /** * Visitor to produce several optimizations * - to replace numbered constants with references to static fields * * @author Alex Tkachman */ public class OptimizerVisitor extends ClassCodeExpressionTransformer { private ClassNode currentClass; private SourceUnit source; private Map const2Var = new HashMap(); private List missingFields = new LinkedList(); public OptimizerVisitor(CompilationUnit cu) { } public void visitClass(ClassNode node, SourceUnit source) { this.currentClass = node; this.source = source; const2Var.clear(); missingFields.clear(); super.visitClass(node); addMissingFields(); } private void addMissingFields() { for (Object missingField : missingFields) { FieldNode f = (FieldNode) missingField; currentClass.addField(f); } } private void setConstField(ConstantExpression constantExpression) { final Object n = constantExpression.getValue(); if (!(n instanceof Number || n instanceof Character)) return; if (n instanceof Integer || n instanceof Double) return; FieldNode field = (FieldNode) const2Var.get(n); if (field!=null) { constantExpression.setConstantName(field.getName()); return; } final String name = "$const$" + const2Var.size(); //TODO: this part here needs a bit of rethinking. If it can happen that the field is defined already, // then is this code still valid? field = currentClass.getDeclaredField(name); if (field==null) { field = new FieldNode(name, Opcodes.ACC_PRIVATE|Opcodes.ACC_STATIC|Opcodes.ACC_SYNTHETIC| Opcodes.ACC_FINAL, constantExpression.getType(), currentClass, constantExpression ); field.setSynthetic(true); missingFields.add(field); } constantExpression.setConstantName(field.getName()); const2Var.put(n, field); } public Expression transform(Expression exp) { if (exp == null) return null; if (!currentClass.isInterface() && exp.getClass() == ConstantExpression.class) { setConstField((ConstantExpression)exp); } return exp.transformExpression(this); } protected SourceUnit getSourceUnit() { return source; } public void visitClosureExpression(ClosureExpression expression) { /* * GROOVY-3339 - do nothing - so that numbers don't get replaced by cached constants in closure classes */ } } groovy-1.8.6/src/main/org/codehaus/groovy/control/GenericsVisitor.java0000644001501200150120000001301311707612046025457 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; /** * class used to verify correct usage of generics in * class header (class and superclass declaration) * @author Jochen Theodorou */ public class GenericsVisitor extends ClassCodeVisitorSupport { private SourceUnit source; public GenericsVisitor(SourceUnit source) { this.source = source; } protected SourceUnit getSourceUnit() { return source; } public void visitClass(ClassNode node) { boolean error=checkWildcard(node); if (error) return; checkGenericsUsage(node.getUnresolvedSuperClass(false), node.getSuperClass()); ClassNode[] interfaces = node.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { checkGenericsUsage(interfaces[i], interfaces[i].redirect()); } node.visitContents(this); } public void visitField(FieldNode node) { ClassNode type = node.getType(); checkGenericsUsage(type, type.redirect()); } public void visitMethod(MethodNode node) { Parameter[] parameters = node.getParameters(); for (Parameter param : parameters) { ClassNode paramType = param.getType(); checkGenericsUsage(paramType, paramType.redirect()); } ClassNode returnType = node.getReturnType(); checkGenericsUsage(returnType, returnType.redirect()); } private boolean checkWildcard(ClassNode cn) { ClassNode sn = cn.getUnresolvedSuperClass(false); if (sn==null) return false; GenericsType[] generics = sn.getGenericsTypes(); if (generics==null) return false; boolean error=false; for (int i = 0; i < generics.length; i++) { if(generics[i].isWildcard()) { addError("A supertype may not specify a wildcard type",sn); error = true; } } return error; } private void checkGenericsUsage(ClassNode n, ClassNode cn) { if(n.isGenericsPlaceHolder()) return; GenericsType[] nTypes = n.getGenericsTypes(); GenericsType[] cnTypes = cn.getGenericsTypes(); // raw type usage is always allowed if (nTypes==null) return; // parameterize a type by using all of the parameters only if (cnTypes==null) { addError( "The class "+n.getName()+" refers to the class "+ cn.getName()+" and uses "+nTypes.length+ " parameters, but the referred class takes no parameters", n); return; } if (nTypes.length!=cnTypes.length) { addError( "The class "+n.getName()+" refers to the class "+ cn.getName()+" and uses "+nTypes.length+ " parameters, but the referred class needs "+ cnTypes.length, n); return; } // check bounds for (int i=0; i",n); } } } private String getPrintName(GenericsType gt) { String ret = gt.getName(); ClassNode[] upperBounds = gt.getUpperBounds(); ClassNode lowerBound = gt.getLowerBound(); if (upperBounds!=null) { ret += " extends "; for (int i = 0; i < upperBounds.length; i++) { ret += getPrintName(upperBounds[i]); if (i+1Roshan Dawrani */ public class StaticVerifier extends ClassCodeVisitorSupport { private boolean inSpecialConstructorCall; private boolean inPropertyExpression; private boolean inClosure; private MethodNode currentMethod; private SourceUnit source; public void visitClass(ClassNode node, SourceUnit source) { this.source = source; super.visitClass(node); } @Override public void visitVariableExpression(VariableExpression ve) { Variable v = ve.getAccessedVariable(); if (v != null && v instanceof DynamicVariable) { if (!inPropertyExpression || inSpecialConstructorCall) addStaticVariableError(ve); } } @Override public void visitClosureExpression(ClosureExpression ce) { boolean oldInClosure = inClosure; inClosure = true; super.visitClosureExpression(ce); inClosure = oldInClosure; } @Override public void visitConstructorCallExpression(ConstructorCallExpression cce) { boolean oldIsSpecialConstructorCall = inSpecialConstructorCall; inSpecialConstructorCall = cce.isSpecialCall(); super.visitConstructorCallExpression(cce); inSpecialConstructorCall = oldIsSpecialConstructorCall; } @Override public void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { MethodNode oldCurrentMethod = currentMethod; currentMethod = node; super.visitConstructorOrMethod(node, isConstructor); currentMethod = oldCurrentMethod; } @Override public void visitMethodCallExpression(MethodCallExpression mce) { checkSuperAccess(mce, mce.getObjectExpression()); super.visitMethodCallExpression(mce); } @Override public void visitPropertyExpression(PropertyExpression pe) { boolean oldInPropertyExpression = inPropertyExpression; inPropertyExpression = true; checkSuperAccess(pe, pe.getObjectExpression()); inPropertyExpression = oldInPropertyExpression; if (!inSpecialConstructorCall) checkStaticScope(pe); } @Override protected SourceUnit getSourceUnit() { return source; } private void checkSuperAccess(Expression expr, Expression object) { if (object instanceof VariableExpression) { VariableExpression ve = (VariableExpression) object; boolean isExplicitSuper = ve.getName().equals("super"); if (isExplicitSuper && currentMethod != null && currentMethod.isStatic()) { addError("'super' cannot be used in a static context, use the explicit class instead.", expr); } } } private void checkStaticScope(PropertyExpression pe) { if (inClosure) return; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof PropertyExpression) continue; if (it instanceof VariableExpression) { addStaticVariableError((VariableExpression) it); } return; } } private void addStaticVariableError(VariableExpression ve) { // closures are always dynamic // propertyExpressions will handle the error a bit differently if (!inSpecialConstructorCall && (inClosure || !ve.isInStaticContext())) return; if (ve.isThisExpression() || ve.isSuperExpression()) return; Variable v = ve.getAccessedVariable(); if (currentMethod != null && currentMethod.isStatic()) { FieldNode fieldNode = currentMethod.getDeclaringClass().getField(ve.getName()); if (fieldNode != null && fieldNode.isStatic()) return; } if (v != null && !(v instanceof DynamicVariable) && v.isInStaticContext()) return; addError("Apparent variable '" + ve.getName() + "' was found in a static scope but doesn't refer" + " to a local variable, static field or class. Possible causes:\n" + "You attempted to reference a variable in the binding or an instance variable from a static context.\n" + "You misspelled a classname or statically imported field. Please check the spelling.\n" + "You attempted to use a method '" + ve.getName() + "' but left out brackets in a place not allowed by the grammar.", ve); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/ErrorCollector.java0000644001501200150120000002400211707612046025300 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import java.io.PrintWriter; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.LocatedMessage; import org.codehaus.groovy.control.messages.Message; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.control.messages.WarningMessage; import org.codehaus.groovy.syntax.CSTNode; import org.codehaus.groovy.syntax.SyntaxException; /** * A base class for collecting messages and errors during processing. * Each CompilationUnit should have an ErrorCollector, and the SourceUnits * should share their ErrorCollector with the CompilationUnit. * * @author Chris Poirier * @author Jochen Theodorou * @version $Id$ */ public class ErrorCollector { /** * WarningMessages collected during processing */ protected LinkedList warnings; /** * ErrorMessages collected during processing */ protected LinkedList errors; /** * Configuration and other settings that control processing */ protected CompilerConfiguration configuration; /** * Initialize the ErrorReporter. */ public ErrorCollector(CompilerConfiguration configuration) { this.warnings = null; this.errors = null; this.configuration = configuration; } public void addCollectorContents(ErrorCollector er) { if (er.errors!=null) { if (errors==null) { errors = er.errors; } else { errors.addAll(er.errors); } } if (er.warnings!=null) { if (warnings==null) { warnings = er.warnings; } else { warnings.addAll(er.warnings); } } } /** * Adds an error to the message set, but does not cause a failure. The message is not required to have a source * line and column specified, but it is best practice to try and include that information. */ public void addErrorAndContinue(Message message) { if (this.errors == null) { this.errors = new LinkedList(); } this.errors.add(message); } /** * Adds a non-fatal error to the message set, which may cause a failure if the error threshold is exceeded. * The message is not required to have a source line and column specified, but it is best practice to try * and include that information. */ public void addError(Message message) throws CompilationFailedException { addErrorAndContinue(message); if (errors!=null && this.errors.size() >= configuration.getTolerance()) { failIfErrors(); } } /** * Adds an optionally-fatal error to the message set. * The message is not required to have a source line and column specified, but it is best practice to try * and include that information. * @param fatal * if true then then processing will stop */ public void addError(Message message, boolean fatal) throws CompilationFailedException { if (fatal) { addFatalError(message); } else { addError(message); } } /** * Convenience wrapper for addError(). */ public void addError(SyntaxException error, SourceUnit source) throws CompilationFailedException { addError(Message.create(error, source), error.isFatal()); } /** * Convenience wrapper for addError(). */ public void addError(String text, CSTNode context, SourceUnit source) throws CompilationFailedException { addError(new LocatedMessage(text, context, source)); } /** * Adds a fatal exception to the message set and throws * the unit as a PhaseFailedException. */ public void addFatalError(Message message) throws CompilationFailedException { addError(message); failIfErrors(); } public void addException(Exception cause, SourceUnit source) throws CompilationFailedException { addError(new ExceptionMessage(cause,configuration.getDebug(),source)); failIfErrors(); } /** * Returns true if there are any errors pending. */ public boolean hasErrors() { return this.errors != null; } /** * Returns true if there are any warnings pending. */ public boolean hasWarnings() { return this.warnings != null; } /** * Returns the list of warnings, or null if there are none. */ public List getWarnings() { return this.warnings; } /** * Returns the list of errors, or null if there are none. */ public List getErrors() { return this.errors; } /** * Returns the number of warnings. */ public int getWarningCount() { return ((this.warnings == null) ? 0 : this.warnings.size()); } /** * Returns the number of errors. */ public int getErrorCount() { return ((this.errors == null) ? 0 : this.errors.size()); } /** * Returns the specified warning message, or null. */ public WarningMessage getWarning(int index) { if (index < getWarningCount()) { return (WarningMessage) this.warnings.get(index); } return null; } /** * Returns the specified error message, or null. */ public Message getError(int index) { if (index < getErrorCount()) { return (Message) this.errors.get(index); } return null; } /** * Returns the last error reported */ public Message getLastError() { return (Message) this.errors.getLast(); } /** * Convenience routine to return the specified error's * underlying SyntaxException, or null if it isn't one. */ public SyntaxException getSyntaxError(int index) { SyntaxException exception = null; Message message = getError(index); if (message != null && message instanceof SyntaxErrorMessage) { exception = ((SyntaxErrorMessage) message).getCause(); } return exception; } /** * Convenience routine to return the specified error's * underlying Exception, or null if it isn't one. */ public Exception getException(int index) { Exception exception = null; Message message = getError(index); if (message != null) { if (message instanceof ExceptionMessage) { exception = ((ExceptionMessage) message).getCause(); } else if (message instanceof SyntaxErrorMessage) { exception = ((SyntaxErrorMessage) message).getCause(); } } return exception; } /** * Adds a WarningMessage to the message set. */ public void addWarning(WarningMessage message) { if (message.isRelevant(configuration.getWarningLevel())) { if (this.warnings == null) { this.warnings = new LinkedList(); } this.warnings.add(message); } } /** * Convenience wrapper for addWarning() that won't create an object * unless it is relevant. */ public void addWarning(int importance, String text, CSTNode context, SourceUnit source) { if (WarningMessage.isRelevant(importance, configuration.getWarningLevel())) { addWarning(new WarningMessage(importance, text, context, source)); } } /** * Convenience wrapper for addWarning() that won't create an object * unless it is relevant. */ public void addWarning(int importance, String text, Object data, CSTNode context, SourceUnit source) { if (WarningMessage.isRelevant(importance, configuration.getWarningLevel())) { addWarning(new WarningMessage(importance, text, data, context, source)); } } /** * Causes the current phase to fail by throwing a * CompilationFailedException. */ protected void failIfErrors() throws CompilationFailedException { if (hasErrors()) { throw new MultipleCompilationErrorsException(this); } } //--------------------------------------------------------------------------- // OUTPUT private void write(PrintWriter writer, Janitor janitor, List messages, String txt) { if (messages==null || messages.size()==0) return; Iterator iterator = messages.iterator(); while (iterator.hasNext()) { Message message = (Message) iterator.next(); message.write(writer, janitor); if (configuration.getDebug() && (message instanceof SyntaxErrorMessage)){ SyntaxErrorMessage sem = (SyntaxErrorMessage) message; sem.getCause().printStackTrace(writer); } writer.println(); } writer.print(messages.size()); writer.print(" "+txt); if (messages.size()>1) writer.print("s"); writer.println(); } /** * Writes error messages to the specified PrintWriter. */ public void write(PrintWriter writer, Janitor janitor) { write(writer,janitor,warnings,"warning"); write(writer,janitor,errors,"error"); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/0000755001501200150120000000000011627206700023303 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/control/messages/SimpleMessage.java0000644001501200150120000000361011627206700026704 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.ProcessingUnit; import org.codehaus.groovy.control.SourceUnit; /** * A base class for compilation messages. * * @author Chris Poirier * * @version $Id$ */ public class SimpleMessage extends Message { protected String message; // Message text protected Object data; // Data, when the message text is an I18N identifier protected ProcessingUnit owner; public SimpleMessage( String message, ProcessingUnit source ) { this( message, null, source ); } public SimpleMessage( String message, Object data, ProcessingUnit source ) { this.message = message; this.data = null; this.owner = source; } public void write( PrintWriter writer, Janitor janitor ) { if( owner instanceof SourceUnit ) { String name = ((SourceUnit)owner).getName(); writer.println( "" + name + ": " + message ); } else { writer.println( message ); } } public String getMessage() { return message; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/LocatedMessage.java0000644001501200150120000000434011627206700027027 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.CSTNode; /** * A base class for compilation messages. * * @author Chris Poirier * * @version $Id$ */ public class LocatedMessage extends SimpleMessage { protected CSTNode context; // The CSTNode that indicates the location to which the message applies public LocatedMessage( String message, CSTNode context, SourceUnit source ) { super( message, source ); this.context = context; } public LocatedMessage( String message, Object data, CSTNode context, SourceUnit source ) { super( message, data, source ); this.context = context; } public void write( PrintWriter writer, Janitor janitor ) { if (owner instanceof SourceUnit) { SourceUnit source = (SourceUnit) owner; String name = source.getName(); int line = context.getStartLine(); int column = context.getStartColumn(); String sample = source.getSample( line, column, janitor ); if( sample != null ) { writer.println( source.getSample(line, column, janitor) ); } writer.println( name + ": " + line + ": " + this.message ); writer.println(""); } else { writer.println( ": " + this.message ); writer.println(""); } } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/Message.java0000644001501200150120000000443211627206700025535 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.ProcessingUnit; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.SyntaxException; /** * A base class for compilation messages. * * @author Chris Poirier * * @version $Id$ */ public abstract class Message { /** * Writes the message to the specified PrintWriter. The supplied * ProcessingUnit is the unit that holds this Message. */ public abstract void write( PrintWriter writer, Janitor janitor ); /** * A synonym for write( writer, owner, null ). */ public final void write( PrintWriter writer) { write( writer, null ); } //--------------------------------------------------------------------------- // FACTORY METHODS /** * Creates a new Message from the specified text. */ public static Message create( String text, ProcessingUnit owner ) { return new SimpleMessage( text, owner ); } /** * Creates a new Message from the specified text. */ public static Message create( String text, Object data, ProcessingUnit owner ) { return new SimpleMessage( text, data, owner); } /** * Creates a new Message from the specified SyntaxException. */ public static Message create( SyntaxException error, SourceUnit owner ) { return new SyntaxErrorMessage( error, owner ); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/SyntaxErrorMessage.java0000644001501200150120000000373511627206700027763 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.SyntaxException; /** * A class for error messages produced by the parser system. * * @author Chris Poirier * @version $Id$ */ public class SyntaxErrorMessage extends Message { protected SyntaxException cause; protected SourceUnit source; public SyntaxErrorMessage(SyntaxException cause, SourceUnit source) { this.cause = cause; this.source = source; cause.setSourceLocator(source.getName()); } /** * Returns the underlying SyntaxException. */ public SyntaxException getCause() { return this.cause; } /** * Writes out a nicely formatted summary of the syntax error. */ public void write(PrintWriter output, Janitor janitor) { String name = source.getName(); int line = getCause().getStartLine(); int column = getCause().getStartColumn(); String sample = source.getSample(line, column, janitor); output.print(name + ": " + line + ": " + getCause().getMessage()); if (sample != null) { output.println(); output.print(sample); output.println(); } } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/ExceptionMessage.java0000644001501200150120000000405511627206700027415 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.ProcessingUnit; /** * A class for error messages produced by the parser system. * * @author Chris Poirier * * @version $Id$ */ public class ExceptionMessage extends Message { protected boolean verbose = true; private Exception cause = null; // The exception source of the message, if any ProcessingUnit owner = null; public ExceptionMessage( Exception cause, boolean v, ProcessingUnit owner ) { this.verbose = v; this.cause = cause; this.owner = owner; } /** * Returns the underlying Exception. */ public Exception getCause() { return this.cause; } /** * Writes out a nicely formatted summary of the exception. */ public void write( PrintWriter output, Janitor janitor ) { String description = "General error during " + owner.getPhaseDescription() + ": "; String message = cause.getMessage(); if( message != null ) { output.println( description + message ); } else { output.println( description + cause ); } output.println(); //if (verbose) { cause.printStackTrace(output); //} } } groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/package.html0000644001501200150120000000023111627206700025560 0ustar miguelmiguel package org.codehaus.groovy.control.messages.*

    Error message classes.

    groovy-1.8.6/src/main/org/codehaus/groovy/control/messages/WarningMessage.java0000644001501200150120000000632611627206700027067 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.messages; import java.io.PrintWriter; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.CSTNode; /** * A class for warning messages. * * @author Chris Poirier * * @version $Id$ */ public class WarningMessage extends LocatedMessage { //--------------------------------------------------------------------------- // WARNING LEVELS public static final int NONE = 0; // For querying, ignore all errors public static final int LIKELY_ERRORS = 1; // Warning indicates likely error public static final int POSSIBLE_ERRORS = 2; // Warning indicates possible error public static final int PARANOIA = 3; // Warning indicates paranoia on the part of the compiler /** * Returns true if a warning would be relevant to the specified level. */ public static boolean isRelevant( int actual, int limit ) { return actual <= limit; } /** * Returns true if this message is as or more important than the * specified importance level. */ public boolean isRelevant( int importance ) { return isRelevant( this.importance, importance ); } //--------------------------------------------------------------------------- // CONSTRUCTION AND DATA ACCESS private int importance; // The warning level, for filtering /** * Creates a new warning message. * * @param importance the warning level * @param message the message text * @param context context information for locating the offending source text */ public WarningMessage( int importance, String message, CSTNode context, SourceUnit owner ) { super( message, context, owner ); this.importance = importance; } /** * Creates a new warning message. * * @param importance the warning level * @param message the message text * @param data additional data needed when generating the message * @param context context information for locating the offending source text */ public WarningMessage( int importance, String message, Object data, CSTNode context, SourceUnit owner ) { super( message, data, context, owner ); this.importance = importance; } public void write( PrintWriter writer, Janitor janitor ) { writer.print( "warning: " ); super.write( writer, janitor ); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/customizers/0000755001501200150120000000000011715031256024063 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/control/customizers/CompilationCustomizer.java0000644001501200150120000000265111707612046031300 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.customizers; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilePhase; /** * Users wanting to customize the configuration process such as adding imports, restricting the * language features or apply AST transformations by default should implement this class, then * call the {@link org.codehaus.groovy.control.CompilerConfiguration#addCompilationCustomizers(CompilationCustomizer...)} * method. * * @author Cedric Champeau * * @since 1.8.0 * */ public abstract class CompilationCustomizer extends CompilationUnit.PrimaryClassNodeOperation { private final CompilePhase phase; public CompilationCustomizer(CompilePhase phase) { this.phase = phase; } public CompilePhase getPhase() { return phase; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/customizers/ImportCustomizer.java0000644001501200150120000001356611707612046030303 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.customizers; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import java.util.*; /** * This compilation customizer allows addiing various types of imports to the compilation unit. Supports adding : *
      *
    • standard imports thanks to {@link #addImport(String)}, {@link #addImport(String, String)} or {@link #addImports(String...)}
    • *
    • star imports thanks to {@link #addStarImport(String)} or {@link #addStarImports(String...)}
    • *
    • static imports thanks to {@link #addStaticImport(String, String)} or {@link #addStaticImport(String, String, String)}
    • *
    • static star imports thanks to {@link #addStaticStar(String)} or {@link #addStaticStars(String...)}
    • *
    * * @author Cedric Champeau * * @since 1.8.0 * */ public class ImportCustomizer extends CompilationCustomizer { private final List imports = new LinkedList(); public ImportCustomizer() { super(CompilePhase.CONVERSION); } @Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException { final ModuleNode ast = source.getAST(); for (Import anImport : imports) { switch (anImport.type) { case regular: ast.addImport(anImport.alias, anImport.classNode); break; case staticImport: ast.addStaticImport(anImport.classNode, anImport.field, anImport.alias); break; case staticStar: ast.addStaticStarImport(anImport.alias, anImport.classNode); break; case star: ast.addStarImport(anImport.star); break; } } } public ImportCustomizer addImport(final String alias, final String className) { imports.add(new Import(ImportType.regular, alias, ClassHelper.make(className))); return this; } public ImportCustomizer addStaticImport(final String className, final String fieldName) { final ClassNode node = ClassHelper.make(className); imports.add(new Import(ImportType.staticImport, fieldName, node, fieldName)); return this; } public ImportCustomizer addStaticStars(final String... classNames) { for (String className : classNames) { addStaticStar(className); } return this; } public ImportCustomizer addStaticImport(final String alias, final String className, final String fieldName) { imports.add(new Import(ImportCustomizer.ImportType.staticImport, alias, ClassHelper.make(className), fieldName)); return this; } public ImportCustomizer addImports(final String... imports) { for (String anImport : imports) { addImport(anImport); } return this; } public ImportCustomizer addStarImports(final String... packageNames) { for (String packageName : packageNames) { addStarImport(packageName); } return this; } private void addImport(final String className) { final ClassNode node = ClassHelper.make(className); imports.add(new Import(ImportType.regular, node.getNameWithoutPackage(), node)); } private void addStaticStar(final String className) { imports.add(new Import(ImportCustomizer.ImportType.staticStar, className, ClassHelper.make(className))); } private void addStarImport(final String packagename) { final String packageNameEndingWithDot = packagename.endsWith(".")?packagename:packagename+'.'; imports.add(new Import(ImportType.star,packageNameEndingWithDot)); } // -------------------- Helper classes ------------------------- /** * Represents imports which are possibly aliased. */ private static class Import { final ImportType type; final ClassNode classNode; final String alias; final String field; final String star; // only used for star imports private Import(final ImportType type, final String alias, final ClassNode classNode, final String field) { this.alias = alias; this.classNode = classNode; this.field = field; this.type = type; this.star = null; } private Import(final ImportType type, final String alias, final ClassNode classNode) { this.alias = alias; this.classNode = classNode; this.type = type; this.field = null; this.star = null; } private Import(final ImportType type, final String star) { this.type = type; this.star = star; this.alias = null; this.classNode = null; this.field = null; } } private enum ImportType { regular, staticImport, staticStar, star } } groovy-1.8.6/src/main/org/codehaus/groovy/control/customizers/SecureASTCustomizer.java0000644001501200150120000013362411714271434030625 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.customizers; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.classgen.BytecodeExpression; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Token; import java.util.*; /** * This customizer allows securing source code by controlling what code constructs are allowed. For example, if you only * want to allow arithmetic operations in a groovy shell, you can configure this customizer to restrict package imports, * method calls and so on. *

    * Most of the securization options found in this class work with either blacklist or whitelist. This means that, for a * single option, you can set a whitelist OR a blacklist, but not both. You can mix whitelist/blacklist strategies for * different options. For example, you can have import whitelist and tokens blacklist. *

    * The recommanded way of securing shells is to use whitelists because it is guaranteed that future features of the * Groovy language won't be allowed by defaut. Using blacklists, you can limit the features of the languages by opting * out, but new language features would require you to update your configuration. *

    * If you set neither a whitelist nor a blacklist, then everything is authorized. *

    * Combinations of import and star imports constraints are authorized as long as you use the same type of list for both. * For example, you may use an import whitelist and a star import whitelist together, but you cannot use an import white * list with a star import blacklist. static imports are handled separately, meaning that blacklisting an import * does not prevent from using a static import. *

    *

    * Eventually, if the features provided here are not sufficient, you may implement custom AST filtering handlers, either * implementing the {@link StatementChecker} interface or {@link ExpressionChecker} interface then register your * handlers thanks to the {@link #addExpressionCheckers(org.codehaus.groovy.control.customizers.SecureASTCustomizer.ExpressionChecker...)} * and {@link #addStatementCheckers(org.codehaus.groovy.control.customizers.SecureASTCustomizer.StatementChecker...)} * methods. *

    * Here is an example of usage. We will create a groovy classloader which only supports arithmetic operations and imports * the java.lang.Math classes by default. * *

     * final ImportCustomizer imports = new ImportCustomizer().addStaticStars('java.lang.Math') // add static import of java.lang.Math
     *             final SecureASTCustomizer secure = new SecureASTCustomizer()
     *             secure.with {
     *                 closuresAllowed = false
     *                 methodDefinitionAllowed = false
     *
     *                 importsWhitelist = []
     *                 staticImportsWhitelist = []
     *                 staticStarImportsWhitelist = ['java.lang.Math'] // only java.lang.Math is allowed
     *
     *                 tokensWhitelist = [
     *                         PLUS,
     *                         MINUS,
     *                         MULTIPLY,
     *                         DIVIDE,
     *                         MOD,
     *                         POWER,
     *                         PLUS_PLUS,
     *                         MINUS_MINUS,
     *                         COMPARE_EQUAL,
     *                         COMPARE_NOT_EQUAL,
     *                         COMPARE_LESS_THAN,
     *                         COMPARE_LESS_THAN_EQUAL,
     *                         COMPARE_GREATER_THAN,
     *                         COMPARE_GREATER_THAN_EQUAL,
     *                 ].asImmutable()
     *
     *                 constantTypesClassesWhiteList = [
     *                         Integer,
     *                         Float,
     *                         Long,
     *                         Double,
     *                         BigDecimal,
     *                         Integer.TYPE,
     *                         Long.TYPE,
     *                         Float.TYPE,
     *                         Double.TYPE
     *                 ].asImmutable()
     *
     *                 receiversClassesWhiteList = [
     *                         Math,
     *                         Integer,
     *                         Float,
     *                         Double,
     *                         Long,
     *                         BigDecimal
     *                 ].asImmutable()
     *             }
     *             CompilerConfiguration config = new CompilerConfiguration()
     *             config.addCompilationCustomizers(imports, secure)
     *             GroovyClassLoader loader = new GroovyClassLoader(this.class.classLoader, config)
     *  
    * * @author Cedric Champeau * @author Guillaume Laforge * @author Hamlet D'Arcy * * @since 1.8.0 */ public class SecureASTCustomizer extends CompilationCustomizer { private boolean isPackageAllowed = true; private boolean isMethodDefinitionAllowed = true; private boolean isClosuresAllowed = true; // imports private List importsWhitelist; private List importsBlacklist; // static imports private List staticImportsWhitelist; private List staticImportsBlacklist; // star imports private List starImportsWhitelist; private List starImportsBlacklist; // static star imports private List staticStarImportsWhitelist; private List staticStarImportsBlacklist; // indirect import checks // if set to true, then security rules on imports will also be applied on classnodes. // Direct instantiation of classes without imports will therefore also fail if this option is enabled private boolean isIndirectImportCheckEnabled; // statements private List> statementsWhitelist; private List> statementsBlacklist; private final List statementCheckers = new LinkedList(); // expressions private List> expressionsWhitelist; private List> expressionsBlacklist; private final List expressionCheckers = new LinkedList(); // tokens from Types private List tokensWhitelist; private List tokensBlacklist; // constant types private List constantTypesWhiteList; private List constantTypesBlackList; // receivers private List receiversWhiteList; private List receiversBlackList; public SecureASTCustomizer() { super(CompilePhase.CANONICALIZATION); } public boolean isMethodDefinitionAllowed() { return isMethodDefinitionAllowed; } public void setMethodDefinitionAllowed(final boolean methodDefinitionAllowed) { isMethodDefinitionAllowed = methodDefinitionAllowed; } public boolean isPackageAllowed() { return isPackageAllowed; } public boolean isClosuresAllowed() { return isClosuresAllowed; } public void setClosuresAllowed(final boolean closuresAllowed) { isClosuresAllowed = closuresAllowed; } public void setPackageAllowed(final boolean packageAllowed) { isPackageAllowed = packageAllowed; } public List getImportsBlacklist() { return importsBlacklist; } public void setImportsBlacklist(final List importsBlacklist) { if (importsWhitelist != null || starImportsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.importsBlacklist = importsBlacklist; } public List getImportsWhitelist() { return importsWhitelist; } public void setImportsWhitelist(final List importsWhitelist) { if (importsBlacklist != null || starImportsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.importsWhitelist = importsWhitelist; } public List getStarImportsBlacklist() { return starImportsBlacklist; } public void setStarImportsBlacklist(final List starImportsBlacklist) { if (importsWhitelist != null || starImportsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.starImportsBlacklist = normalizeStarImports(starImportsBlacklist); if (this.importsBlacklist == null) importsBlacklist = Collections.emptyList(); } public List getStarImportsWhitelist() { return starImportsWhitelist; } public void setStarImportsWhitelist(final List starImportsWhitelist) { if (importsBlacklist != null || starImportsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.starImportsWhitelist = normalizeStarImports(starImportsWhitelist); if (this.importsWhitelist == null) importsWhitelist = Collections.emptyList(); } /** * Ensures that every star import ends with .* as this is the expected syntax in import checks. */ private static List normalizeStarImports(List starImports) { List result = new ArrayList(starImports.size()); for (String starImport : starImports) { if (starImport.endsWith(".*")) { result.add(starImport); } else if (starImport.endsWith(".")) { result.add(starImport + "*"); } else { result.add(starImport + ".*"); } } return Collections.unmodifiableList(result); } public List getStaticImportsBlacklist() { return staticImportsBlacklist; } public void setStaticImportsBlacklist(final List staticImportsBlacklist) { if (staticImportsWhitelist != null || staticStarImportsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.staticImportsBlacklist = staticImportsBlacklist; } public List getStaticImportsWhitelist() { return staticImportsWhitelist; } public void setStaticImportsWhitelist(final List staticImportsWhitelist) { if (staticImportsBlacklist != null || staticStarImportsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.staticImportsWhitelist = staticImportsWhitelist; } public List getStaticStarImportsBlacklist() { return staticStarImportsBlacklist; } public void setStaticStarImportsBlacklist(final List staticStarImportsBlacklist) { if (staticImportsWhitelist != null || staticStarImportsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.staticStarImportsBlacklist = normalizeStarImports(staticStarImportsBlacklist); if (this.staticImportsBlacklist == null) this.staticImportsBlacklist = Collections.emptyList(); } public List getStaticStarImportsWhitelist() { return staticStarImportsWhitelist; } public void setStaticStarImportsWhitelist(final List staticStarImportsWhitelist) { if (staticImportsBlacklist != null || staticStarImportsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.staticStarImportsWhitelist = normalizeStarImports(staticStarImportsWhitelist); if (this.staticImportsWhitelist == null) this.staticImportsWhitelist = Collections.emptyList(); } public List> getExpressionsBlacklist() { return expressionsBlacklist; } public void setExpressionsBlacklist(final List> expressionsBlacklist) { if (expressionsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.expressionsBlacklist = expressionsBlacklist; } public List> getExpressionsWhitelist() { return expressionsWhitelist; } public void setExpressionsWhitelist(final List> expressionsWhitelist) { if (expressionsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.expressionsWhitelist = expressionsWhitelist; } public List> getStatementsBlacklist() { return statementsBlacklist; } public void setStatementsBlacklist(final List> statementsBlacklist) { if (statementsWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.statementsBlacklist = statementsBlacklist; } public List> getStatementsWhitelist() { return statementsWhitelist; } public void setStatementsWhitelist(final List> statementsWhitelist) { if (statementsBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.statementsWhitelist = statementsWhitelist; } public List getTokensBlacklist() { return tokensBlacklist; } public boolean isIndirectImportCheckEnabled() { return isIndirectImportCheckEnabled; } /** * Set this option to true if you want your import rules to be checked against every class node. This means that if * someone uses a fully qualified class name, then it will also be checked against the import rules, preventing, for * example, instantiation of classes without imports thanks to FQCN. * * @param indirectImportCheckEnabled set to true to enable indirect checks */ public void setIndirectImportCheckEnabled(final boolean indirectImportCheckEnabled) { isIndirectImportCheckEnabled = indirectImportCheckEnabled; } /** * Sets the list of tokens which are blacklisted. * * @param tokensBlacklist the tokens. The values of the tokens must be those of {@link org.codehaus.groovy.syntax.Types} */ public void setTokensBlacklist(final List tokensBlacklist) { if (tokensWhitelist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.tokensBlacklist = tokensBlacklist; } public List getTokensWhitelist() { return tokensWhitelist; } /** * Sets the list of tokens which are whitelisted. * * @param tokensWhitelist the tokens. The values of the tokens must be those of {@link org.codehaus.groovy.syntax.Types} */ public void setTokensWhitelist(final List tokensWhitelist) { if (tokensBlacklist != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.tokensWhitelist = tokensWhitelist; } public void addStatementCheckers(StatementChecker... checkers) { statementCheckers.addAll(Arrays.asList(checkers)); } public void addExpressionCheckers(ExpressionChecker... checkers) { expressionCheckers.addAll(Arrays.asList(checkers)); } public List getConstantTypesBlackList() { return constantTypesBlackList; } public void setConstantTypesBlackList(final List constantTypesBlackList) { if (constantTypesWhiteList != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.constantTypesBlackList = constantTypesBlackList; } public List getConstantTypesWhiteList() { return constantTypesWhiteList; } public void setConstantTypesWhiteList(final List constantTypesWhiteList) { if (constantTypesBlackList != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.constantTypesWhiteList = constantTypesWhiteList; } /** * An alternative way of setting constant types. * * @param constantTypesWhiteList a list of classes. */ public void setConstantTypesClassesWhiteList(final List constantTypesWhiteList) { List values = new LinkedList(); for (Class aClass : constantTypesWhiteList) { values.add(aClass.getName()); } setConstantTypesWhiteList(values); } /** * An alternative way of setting constant types. * * @param constantTypesBlackList a list of classes. */ public void setConstantTypesClassesBlackList(final List constantTypesBlackList) { List values = new LinkedList(); for (Class aClass : constantTypesBlackList) { values.add(aClass.getName()); } setConstantTypesBlackList(values); } public List getReceiversBlackList() { return receiversBlackList; } /** * Sets the list of classes which deny method calls. * * @param receiversBlackList the list of refused classes, as fully qualified names */ public void setReceiversBlackList(final List receiversBlackList) { if (receiversWhiteList != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.receiversBlackList = receiversBlackList; } /** * An alternative way of setting {@link #setReceiversBlackList(java.util.List) receiver classes}. * * @param receiversBlacklist a list of classes. */ public void setReceiversClassesBlackList(final List receiversBlacklist) { List values = new LinkedList(); for (Class aClass : receiversBlacklist) { values.add(aClass.getName()); } setReceiversBlackList(values); } public List getReceiversWhiteList() { return receiversWhiteList; } /** * Sets the list of classes which may accept method calls. * * @param receiversWhiteList the list of accepted classes, as fully qualified names */ public void setReceiversWhiteList(final List receiversWhiteList) { if (receiversBlackList != null) { throw new IllegalArgumentException("You are not allowed to set both whitelist and blacklist"); } this.receiversWhiteList = receiversWhiteList; } /** * An alternative way of setting {@link #setReceiversWhiteList(java.util.List) receiver classes}. * * @param receiversWhitelist a list of classes. */ public void setReceiversClassesWhiteList(final List receiversWhitelist) { List values = new LinkedList(); for (Class aClass : receiversWhitelist) { values.add(aClass.getName()); } setReceiversWhiteList(values); } @Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException { final ModuleNode ast = source.getAST(); if (!isPackageAllowed && ast.getPackage() != null) { throw new SecurityException("Package definitions are not allowed"); } checkMethodDefinitionAllowed(classNode); // verify imports if (importsBlacklist != null || importsWhitelist != null || starImportsBlacklist != null || starImportsWhitelist != null) { for (ImportNode importNode : ast.getImports()) { final String className = importNode.getClassName(); assertImportIsAllowed(className); } for (ImportNode importNode : ast.getStarImports()) { final String className = importNode.getPackageName(); assertStarImportIsAllowed(className + "*"); } } // verify static imports if (staticImportsBlacklist != null || staticImportsWhitelist != null || staticStarImportsBlacklist != null || staticStarImportsWhitelist != null) { for (Map.Entry entry : ast.getStaticImports().entrySet()) { final String className = entry.getValue().getClassName(); assertStaticImportIsAllowed(entry.getKey(), className); } for (Map.Entry entry : ast.getStaticStarImports().entrySet()) { final String className = entry.getValue().getClassName(); assertStaticImportIsAllowed(entry.getKey(), className); } } final SecuringCodeVisitor visitor = new SecuringCodeVisitor(); ast.getStatementBlock().visit(visitor); for (ClassNode clNode : ast.getClasses()) { if (clNode!=classNode) { checkMethodDefinitionAllowed(clNode); for (MethodNode methodNode : clNode.getMethods()) { if (!methodNode.isSynthetic()) { methodNode.getCode().visit(visitor); } } } } List methods = filterMethods(classNode); if (isMethodDefinitionAllowed) { for (MethodNode method : methods) { if (method.getDeclaringClass()==classNode) method.getCode().visit(visitor); } } } private void checkMethodDefinitionAllowed(ClassNode owner) { if (isMethodDefinitionAllowed) return; List methods = filterMethods(owner); if (!methods.isEmpty()) throw new SecurityException("Method definitions are not allowed"); } private List filterMethods(ClassNode owner) { List result = new LinkedList(); List methods = owner.getMethods(); for (MethodNode method : methods) { if (method.getDeclaringClass() == owner && !method.isSynthetic()) { if ("main".equals(method.getName()) || "run".equals(method.getName()) && owner.isScriptBody()) continue; result.add(method); } } return result; } private void assertStarImportIsAllowed(final String packageName) { if (starImportsWhitelist != null && !starImportsWhitelist.contains(packageName)) { throw new SecurityException("Importing [" + packageName + "] is not allowed"); } if (starImportsBlacklist != null && starImportsBlacklist.contains(packageName)) { throw new SecurityException("Importing [" + packageName + "] is not allowed"); } } private void assertImportIsAllowed(final String className) { if (importsWhitelist != null && !importsWhitelist.contains(className)) { if (starImportsWhitelist != null) { // we should now check if the import is in the star imports ClassNode node = ClassHelper.make(className); final String packageName = node.getPackageName(); if (!starImportsWhitelist.contains(packageName + ".*")) { throw new SecurityException("Importing [" + className + "] is not allowed"); } } else { throw new SecurityException("Importing [" + className + "] is not allowed"); } } if (importsBlacklist != null && importsBlacklist.contains(className)) { throw new SecurityException("Importing [" + className + "] is not allowed"); } // check that there's no star import blacklist if (starImportsBlacklist != null) { ClassNode node = ClassHelper.make(className); final String packageName = node.getPackageName(); if (starImportsBlacklist.contains(packageName + ".*")) { throw new SecurityException("Importing [" + className + "] is not allowed"); } } } private void assertStaticImportIsAllowed(final String member, final String className) { final String fqn = member.equals(className) ? member : className + "." + member; if (staticImportsWhitelist != null && !staticImportsWhitelist.contains(fqn)) { if (staticStarImportsWhitelist != null) { // we should now check if the import is in the star imports if (!staticStarImportsWhitelist.contains(className + ".*")) { throw new SecurityException("Importing [" + fqn + "] is not allowed"); } } else { throw new SecurityException("Importing [" + fqn + "] is not allowed"); } } if (staticImportsBlacklist != null && staticImportsBlacklist.contains(fqn)) { throw new SecurityException("Importing [" + fqn + "] is not allowed"); } // check that there's no star import blacklist if (staticStarImportsBlacklist != null) { if (staticStarImportsBlacklist.contains(className + ".*")) { throw new SecurityException("Importing [" + fqn + "] is not allowed"); } } } /** * This visitor directly implements the {@link GroovyCodeVisitor} interface instead of using the {@link * CodeVisitorSupport} class to make sure that future features of the language gets managed by this visitor. Thus, * adding a new feature would result in a compilation error if this visitor is not updated. */ private class SecuringCodeVisitor implements GroovyCodeVisitor { /** * Checks that a given statement is either in the whitelist or not in the blacklist. * * @param statement the statement to be checked * @throws SecurityException if usage of this statement class is forbidden */ private void assertStatementAuthorized(final Statement statement) throws SecurityException { final Class clazz = statement.getClass(); if (statementsBlacklist != null && statementsBlacklist.contains(clazz)) { throw new SecurityException(clazz.getSimpleName() + "s are not allowed"); } else if (statementsWhitelist != null && !statementsWhitelist.contains(clazz)) { throw new SecurityException(clazz.getSimpleName() + "s are not allowed"); } for (StatementChecker statementChecker : statementCheckers) { if (!statementChecker.isAuthorized(statement)) { throw new SecurityException("Statement [" + clazz.getSimpleName() + "] is not allowed"); } } } /** * Checks that a given expression is either in the whitelist or not in the blacklist. * * @param expression the expression to be checked * @throws SecurityException if usage of this expression class is forbidden */ private void assertExpressionAuthorized(final Expression expression) throws SecurityException { final Class clazz = expression.getClass(); if (expressionsBlacklist != null && expressionsBlacklist.contains(clazz)) { throw new SecurityException(clazz.getSimpleName() + "s are not allowed: " + expression.getText()); } else if (expressionsWhitelist != null && !expressionsWhitelist.contains(clazz)) { throw new SecurityException(clazz.getSimpleName() + "s are not allowed: " + expression.getText()); } for (ExpressionChecker expressionChecker : expressionCheckers) { if (!expressionChecker.isAuthorized(expression)) { throw new SecurityException("Expression [" + clazz.getSimpleName() + "] is not allowed: " + expression.getText()); } } if (isIndirectImportCheckEnabled) { try { if (expression instanceof ConstructorCallExpression) { assertImportIsAllowed(expression.getType().getName()); } else if (expression instanceof MethodCallExpression) { MethodCallExpression expr = (MethodCallExpression) expression; final String typename = expr.getObjectExpression().getType().getName(); assertImportIsAllowed(typename); assertStaticImportIsAllowed(expr.getMethodAsString(), typename); } else if (expression instanceof StaticMethodCallExpression) { StaticMethodCallExpression expr = (StaticMethodCallExpression) expression; final String typename = expr.getOwnerType().getName(); assertImportIsAllowed(typename); assertStaticImportIsAllowed(expr.getMethod(), typename); } else if (expression instanceof MethodPointerExpression) { MethodPointerExpression expr = (MethodPointerExpression) expression; final String typename = expr.getType().getName(); assertImportIsAllowed(typename); assertStaticImportIsAllowed(expr.getText(), typename); } } catch (SecurityException e) { throw new SecurityException("Indirect import checks prevents usage of expression", e); } } } /** * Checks that a given token is either in the whitelist or not in the blacklist. * * @param token the token to be checked * @throws SecurityException if usage of this token is forbidden */ private void assertTokenAuthorized(final Token token) throws SecurityException { final int value = token.getType(); if (tokensBlacklist != null && tokensBlacklist.contains(value)) { throw new SecurityException("Token " + token + " is not allowed"); } else if (tokensWhitelist != null && !tokensWhitelist.contains(value)) { throw new SecurityException("Token " + token + " is not allowed"); } } public void visitBlockStatement(final BlockStatement block) { assertStatementAuthorized(block); for (Statement statement : block.getStatements()) { statement.visit(this); } } public void visitForLoop(final ForStatement forLoop) { assertStatementAuthorized(forLoop); forLoop.getCollectionExpression().visit(this); forLoop.getLoopBlock().visit(this); } public void visitWhileLoop(final WhileStatement loop) { assertStatementAuthorized(loop); loop.getBooleanExpression().visit(this); loop.getLoopBlock().visit(this); } public void visitDoWhileLoop(final DoWhileStatement loop) { assertStatementAuthorized(loop); loop.getBooleanExpression().visit(this); loop.getLoopBlock().visit(this); } public void visitIfElse(final IfStatement ifElse) { assertStatementAuthorized(ifElse); ifElse.getBooleanExpression().visit(this); ifElse.getIfBlock().visit(this); Statement elseBlock = ifElse.getElseBlock(); if (elseBlock instanceof EmptyStatement) { // dispatching to EmptyStatement will not call back visitor, // must call our visitEmptyStatement explicitly visitEmptyStatement((EmptyStatement) elseBlock); } else { elseBlock.visit(this); } } public void visitExpressionStatement(final ExpressionStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); } public void visitReturnStatement(final ReturnStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); } public void visitAssertStatement(final AssertStatement statement) { assertStatementAuthorized(statement); statement.getBooleanExpression().visit(this); statement.getMessageExpression().visit(this); } public void visitTryCatchFinally(final TryCatchStatement statement) { assertStatementAuthorized(statement); statement.getTryStatement().visit(this); for (CatchStatement catchStatement : statement.getCatchStatements()) { catchStatement.visit(this); } Statement finallyStatement = statement.getFinallyStatement(); if (finallyStatement instanceof EmptyStatement) { // dispatching to EmptyStatement will not call back visitor, // must call our visitEmptyStatement explicitly visitEmptyStatement((EmptyStatement) finallyStatement); } else { finallyStatement.visit(this); } } protected void visitEmptyStatement(EmptyStatement statement) { // noop } public void visitSwitch(final SwitchStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); for (CaseStatement caseStatement : statement.getCaseStatements()) { caseStatement.visit(this); } statement.getDefaultStatement().visit(this); } public void visitCaseStatement(final CaseStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); statement.getCode().visit(this); } public void visitBreakStatement(final BreakStatement statement) { assertStatementAuthorized(statement); } public void visitContinueStatement(final ContinueStatement statement) { assertStatementAuthorized(statement); } public void visitThrowStatement(final ThrowStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); } public void visitSynchronizedStatement(final SynchronizedStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); statement.getCode().visit(this); } public void visitCatchStatement(final CatchStatement statement) { assertStatementAuthorized(statement); statement.getCode().visit(this); } public void visitMethodCallExpression(final MethodCallExpression call) { assertExpressionAuthorized(call); Expression receiver = call.getObjectExpression(); final String typeName = receiver.getType().getName(); if (receiversWhiteList != null && !receiversWhiteList.contains(typeName)) { throw new SecurityException("Method calls not allowed on [" + typeName + "]"); } else if (receiversBlackList != null && receiversBlackList.contains(typeName)) { throw new SecurityException("Method calls not allowed on [" + typeName + "]"); } receiver.visit(this); final Expression method = call.getMethod(); checkConstantTypeIfNotMethodNameOrProperty(method); call.getArguments().visit(this); } public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) { assertExpressionAuthorized(call); final String typeName = call.getOwnerType().getName(); if (receiversWhiteList != null && !receiversWhiteList.contains(typeName)) { throw new SecurityException("Method calls not allowed on [" + typeName + "]"); } else if (receiversBlackList != null && receiversBlackList.contains(typeName)) { throw new SecurityException("Method calls not allowed on [" + typeName + "]"); } call.getArguments().visit(this); } public void visitConstructorCallExpression(final ConstructorCallExpression call) { assertExpressionAuthorized(call); call.getArguments().visit(this); } public void visitTernaryExpression(final TernaryExpression expression) { assertExpressionAuthorized(expression); expression.getBooleanExpression().visit(this); expression.getTrueExpression().visit(this); expression.getFalseExpression().visit(this); } public void visitShortTernaryExpression(final ElvisOperatorExpression expression) { assertExpressionAuthorized(expression); visitTernaryExpression(expression); } public void visitBinaryExpression(final BinaryExpression expression) { assertExpressionAuthorized(expression); assertTokenAuthorized(expression.getOperation()); expression.getLeftExpression().visit(this); expression.getRightExpression().visit(this); } public void visitPrefixExpression(final PrefixExpression expression) { assertExpressionAuthorized(expression); assertTokenAuthorized(expression.getOperation()); expression.getExpression().visit(this); } public void visitPostfixExpression(final PostfixExpression expression) { assertExpressionAuthorized(expression); assertTokenAuthorized(expression.getOperation()); expression.getExpression().visit(this); } public void visitBooleanExpression(final BooleanExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitClosureExpression(final ClosureExpression expression) { assertExpressionAuthorized(expression); if (!isClosuresAllowed) throw new SecurityException("Closures are not allowed"); expression.getCode().visit(this); } public void visitTupleExpression(final TupleExpression expression) { assertExpressionAuthorized(expression); visitListOfExpressions(expression.getExpressions()); } public void visitMapExpression(final MapExpression expression) { assertExpressionAuthorized(expression); visitListOfExpressions(expression.getMapEntryExpressions()); } public void visitMapEntryExpression(final MapEntryExpression expression) { assertExpressionAuthorized(expression); expression.getKeyExpression().visit(this); expression.getValueExpression().visit(this); } public void visitListExpression(final ListExpression expression) { assertExpressionAuthorized(expression); visitListOfExpressions(expression.getExpressions()); } public void visitRangeExpression(final RangeExpression expression) { assertExpressionAuthorized(expression); expression.getFrom().visit(this); expression.getTo().visit(this); } public void visitPropertyExpression(final PropertyExpression expression) { assertExpressionAuthorized(expression); expression.getObjectExpression().visit(this); final Expression property = expression.getProperty(); checkConstantTypeIfNotMethodNameOrProperty(property); } private void checkConstantTypeIfNotMethodNameOrProperty(final Expression expr) { if (expr instanceof ConstantExpression) { if (!"java.lang.String".equals(expr.getType().getName())) { expr.visit(this); } } else { expr.visit(this); } } public void visitAttributeExpression(final AttributeExpression expression) { assertExpressionAuthorized(expression); expression.getObjectExpression().visit(this); final Expression property = expression.getProperty(); checkConstantTypeIfNotMethodNameOrProperty(property); } public void visitFieldExpression(final FieldExpression expression) { assertExpressionAuthorized(expression); } public void visitMethodPointerExpression(final MethodPointerExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); expression.getMethodName().visit(this); } public void visitConstantExpression(final ConstantExpression expression) { assertExpressionAuthorized(expression); final String type = expression.getType().getName(); if (constantTypesWhiteList != null && !constantTypesWhiteList.contains(type)) { throw new SecurityException("Constant expression type [" + type + "] is not allowed"); } if (constantTypesBlackList != null && constantTypesBlackList.contains(type)) { throw new SecurityException("Constant expression type [" + type + "] is not allowed"); } } public void visitClassExpression(final ClassExpression expression) { assertExpressionAuthorized(expression); } public void visitVariableExpression(final VariableExpression expression) { assertExpressionAuthorized(expression); } public void visitDeclarationExpression(final DeclarationExpression expression) { assertExpressionAuthorized(expression); visitBinaryExpression(expression); } protected void visitListOfExpressions(List list) { if (list == null) return; for (Expression expression : list) { if (expression instanceof SpreadExpression) { Expression spread = ((SpreadExpression) expression).getExpression(); spread.visit(this); } else { expression.visit(this); } } } public void visitGStringExpression(final GStringExpression expression) { assertExpressionAuthorized(expression); visitListOfExpressions(expression.getStrings()); visitListOfExpressions(expression.getValues()); } public void visitArrayExpression(final ArrayExpression expression) { assertExpressionAuthorized(expression); visitListOfExpressions(expression.getExpressions()); visitListOfExpressions(expression.getSizeExpression()); } public void visitSpreadExpression(final SpreadExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitSpreadMapExpression(final SpreadMapExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitNotExpression(final NotExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitUnaryMinusExpression(final UnaryMinusExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitUnaryPlusExpression(final UnaryPlusExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitCastExpression(final CastExpression expression) { assertExpressionAuthorized(expression); expression.getExpression().visit(this); } public void visitArgumentlistExpression(final ArgumentListExpression expression) { assertExpressionAuthorized(expression); visitTupleExpression(expression); } public void visitClosureListExpression(final ClosureListExpression closureListExpression) { assertExpressionAuthorized(closureListExpression); if (!isClosuresAllowed) throw new SecurityException("Closures are not allowed"); visitListOfExpressions(closureListExpression.getExpressions()); } public void visitBytecodeExpression(final BytecodeExpression expression) { assertExpressionAuthorized(expression); } } /** * This interface allows the user to plugin custom expression checkers if expression blacklist or whitelist are not * sufficient */ public static interface ExpressionChecker { boolean isAuthorized(Expression expression); } /** * This interface allows the user to plugin custom statement checkers if statement blacklist or whitelist are not * sufficient */ public static interface StatementChecker { boolean isAuthorized(Statement expression); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/customizers/ASTTransformationCustomizer.groovy0000644001501200150120000002522611715031256033004 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control.customizers import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.transform.GroovyASTTransformation import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.classgen.GeneratorContext import org.codehaus.groovy.ast.ClassNode import org.codehaus.groovy.ast.AnnotationNode import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.ast.ClassHelper import org.codehaus.groovy.transform.GroovyASTTransformationClass import java.lang.annotation.Annotation import org.codehaus.groovy.ast.expr.ClosureExpression import org.codehaus.groovy.ast.expr.ConstantExpression import org.codehaus.groovy.ast.expr.ClassExpression import org.codehaus.groovy.ast.Parameter import org.codehaus.groovy.ast.expr.ListExpression /** * This customizer allows applying an AST transformation to a source unit with * several strategies. * * Creating a customizer with the {@link ASTTransformationCustomizer#ASTTransformationCustomizer(Class) * class constructor} will trigger an AST transformation for * each class node of a source unit. However, you cannot pass parameters to the annotation so the default values * will be used. Writing : *
     *     def configuration = new CompilerConfiguration()
     *     configuration.addCompilationCustomizers(new ASTTransformationCustomizer(Log))
     *     def shell = new GroovyShell(configuration)
     *     shell.evaluate("""
     *        class MyClass {
     *
     *        }""")
     * 
    * * is equivalent to : * *
     *     def shell = new GroovyShell()
     *     shell.evaluate("""
     *        @Log
     *        class MyClass {
     *
     *        }""")
     * 
    * * The class passed as a constructor parameter must be an AST transformation annotation. * * Alternatively, you can apply a global AST transformation by calling the * {@link ASTTransformationCustomizer#ASTTransformationCustomizer(ASTTransformation) AST transformation * constructor}. In that case, the transformation is applied once for the whole source unit. * * Unlike a global AST transformation declared in the META-INF/services/org.codehaus.groovy.transform.ASTTransformation * file, which are applied if the file is in the classpath, using this customizer you'll have the choice to apply * your transformation selectively. It can also be useful to debug global AST transformations without having to * package your annotation in a jar file. * * @author Cedric Champeau * * @since 1.8.0 * */ class ASTTransformationCustomizer extends CompilationCustomizer { private final AnnotationNode annotationNode; private final ASTTransformation transformation private boolean applied = false; // used for global AST transformations /** * Creates an AST transformation customizer using the specified annotation. The transformation classloader can * be used if the transformation class cannot be loaded from the same class loader as the annotation class. * @param transformationAnnotation * @param transformationClassLoader */ ASTTransformationCustomizer(final Class transformationAnnotation, ClassLoader transformationClassLoader) { super(findPhase(transformationAnnotation, transformationClassLoader)) final Class clazz = findASTTranformationClass(transformationAnnotation, transformationClassLoader) this.transformation = clazz.newInstance() this.annotationNode = new AnnotationNode(ClassHelper.make(transformationAnnotation)) } /** * Creates an AST transformation customizer using the specified annotation. * @param transformationAnnotation */ ASTTransformationCustomizer(final Class transformationAnnotation) { this(transformationAnnotation, transformationAnnotation.classLoader) } /** * Creates an AST transformation customizer using the specified transformation. */ ASTTransformationCustomizer(final ASTTransformation transformation) { super(findPhase(transformation)) this.transformation = transformation this.annotationNode = null } /** * Creates an AST transformation customizer using the specified annotation. The transformation classloader can * be used if the transformation class cannot be loaded from the same class loader as the annotation class. * Additionally, you can pass a map of parameters that will be used to parameterize the annotation. * @param transformationAnnotation * @param transformationClassLoader */ ASTTransformationCustomizer(final Map annotationParams, final Class transformationAnnotation, ClassLoader transformationClassLoader) { super(findPhase(transformationAnnotation, transformationClassLoader)) final Class clazz = findASTTranformationClass(transformationAnnotation, transformationClassLoader) this.transformation = clazz.newInstance() this.annotationNode = new AnnotationNode(ClassHelper.make(transformationAnnotation)) setAnnotationParameters(annotationParams) } ASTTransformationCustomizer(final Map annotationParams, final Class transformationAnnotation) { this(annotationParams, transformationAnnotation, transformationAnnotation.classLoader) } ASTTransformationCustomizer(final Map annotationParams, final ASTTransformation transformation) { this(transformation) setAnnotationParameters(annotationParams) } private static Class findASTTranformationClass(Class anAnnotationClass, ClassLoader transformationClassLoader) { final GroovyASTTransformationClass annotation = anAnnotationClass.getAnnotation(GroovyASTTransformationClass) if (annotation==null) throw new IllegalArgumentException("Provided class doesn't look like an AST @interface") Class[] classes = annotation.classes() String[] classesAsStrings = annotation.value() if (classes.length+classesAsStrings.length>1) { throw new IllegalArgumentException("AST transformation customizer doesn't support AST transforms with multiple classes") } return classes?classes[0]:Class.forName(classesAsStrings[0], true, transformationClassLoader?:anAnnotationClass.classLoader) } private static CompilePhase findPhase(ASTTransformation transformation) { if (transformation==null) throw new IllegalArgumentException("Provided transformation must not be null") final Class clazz = transformation.class final GroovyASTTransformation annotation = clazz.getAnnotation(GroovyASTTransformation) if (annotation==null) throw new IllegalArgumentException("Provided ast transformation is not annotated with "+GroovyASTTransformation.name) annotation.phase() } private static CompilePhase findPhase(Class annotationClass, ClassLoader transformationClassLoader) { Class clazz = findASTTranformationClass(annotationClass, transformationClassLoader); findPhase(clazz.newInstance()) } /** * Specify annotation parameters. For example, if the annotation is : *
    @Log(value='logger')
    * You could create an AST transformation customizer and specify the "value" parameter thanks to this method: *
    annotationParameters = [value: 'logger']
         *
         * Note that you cannot specify annotation closure values directly. If the annotation you want to add takes
         * a closure as an argument, you will have to set a {@link ClosureExpression} instead. This can be done by either
         * creating a custom {@link ClosureExpression} from code, or using the {@link org.codehaus.groovy.ast.builder.AstBuilder}.
         *
         * Here is an example :
         * 
         *        // add @Contract({distance >= 0 })
         *        customizer = new ASTTransformationCustomizer(Contract)
         *        final expression = new AstBuilder().buildFromCode(CompilePhase.CONVERSION) {->
         *            distance >= 0
         *        }.expression[0]
         *        customizer.annotationParameters = [value: expression]
    * * @param params the annotation parameters * * @since 1.8.1 */ public void setAnnotationParameters(Map params) { if (params==null || annotationNode==null) return; params.each { key, value -> if (!annotationNode.classNode.getMethod(key)) { throw new IllegalArgumentException("${annotationNode.classNode.name} does not accept any [$key] parameter") } if (value instanceof Closure) { throw new IllegalArgumentException("Direct usage of closure is not supported by the AST " + "compilation customizer. Please use ClosureExpression instead.") } else if (value instanceof ClosureExpression) { // avoid NPEs due to missing source code value.setLineNumber(0) value.setLastLineNumber(0) annotationNode.addMember(key, value) } else if (value instanceof Class) { annotationNode.addMember(key, new ClassExpression(ClassHelper.make(value))) } else if (value instanceof List) { annotationNode.addMember(key, new ListExpression(value.collect { it instanceof Class ? new ClassExpression(ClassHelper.make(it)) : new ConstantExpression(it) })) } else { annotationNode.addMember(key, new ConstantExpression(value)) } } } @Override void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { if (annotationNode!=null) { // this is a local ast transformation which is applied on every class node annotationNode.sourcePosition = classNode transformation.visit([annotationNode, classNode] as ASTNode[], source) } else { // this is a global AST transformation if (!applied) transformation.visit(null, source) } applied = true } } groovy-1.8.6/src/main/org/codehaus/groovy/control/HasCleanup.java0000644001501200150120000000160411627206700024363 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; /** * An interface for things that need to be cleaned up after * operations complete. * * @author Chris Poirier * * @version $Id$ */ public interface HasCleanup { void cleanup(); } groovy-1.8.6/src/main/org/codehaus/groovy/control/package.html0000644001501200150120000000022311627206700023752 0ustar miguelmiguel package org.codehaus.groovy.control.*

    Compiler control classes.

    groovy-1.8.6/src/main/org/codehaus/groovy/control/ParserPlugin.java0000644001501200150120000000227711627206700024762 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.syntax.Reduction; import org.codehaus.groovy.syntax.ParserException; import org.codehaus.groovy.ast.ModuleNode; import java.io.Reader; /** * A simple extension point to allow us to switch between the classic Groovy parser and the new Antlr based parser * * @version $Revision$ */ public interface ParserPlugin { Reduction parseCST(SourceUnit sourceUnit, Reader reader) throws CompilationFailedException; ModuleNode buildAST(SourceUnit sourceUnit, ClassLoader classLoader, Reduction cst) throws ParserException; } groovy-1.8.6/src/main/org/codehaus/groovy/control/ParserPluginFactory.java0000644001501200150120000000441211627206700026303 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.antlr.AntlrParserPluginFactory; /** * A factory of parser plugin instances * * @version $Revision$ */ public abstract class ParserPluginFactory { public static ParserPluginFactory newInstance(boolean useNewParser) { if (useNewParser) { Class type = null; String name = "org.codehaus.groovy.antlr.AntlrParserPluginFactory"; try { type = Class.forName(name); } catch (ClassNotFoundException e) { try { type = ParserPluginFactory.class.getClassLoader().loadClass(name); } catch (ClassNotFoundException e1) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { type = contextClassLoader.loadClass(name); } catch (ClassNotFoundException e2) { // ignore } } } } if (type != null) { try { return (ParserPluginFactory) type.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not create AntlrParserPluginFactory: " + e, e); } } // can't find Antlr parser, so lets use the Classic one } return new AntlrParserPluginFactory(); } public abstract ParserPlugin createParserPlugin(); } groovy-1.8.6/src/main/org/codehaus/groovy/control/SourceExtensionHandler.java0000644001501200150120000000444311713765676027021 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyRuntimeException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; /** * Looks for source file extensions in META-INF/services/org.codehaus.groovy.source.Extensions */ public class SourceExtensionHandler { public static Set getRegisteredExtensions(ClassLoader loader) { Set extensions = new LinkedHashSet(); extensions.add("groovy"); URL service = null; try { Enumeration globalServices = loader.getResources("META-INF/services/org.codehaus.groovy.source.Extensions"); while (globalServices.hasMoreElements()) { service = globalServices.nextElement(); String extension; BufferedReader svcIn = new BufferedReader(new InputStreamReader(service.openStream())); extension = svcIn.readLine(); while (extension != null) { extension = extension.trim(); if (!extension.startsWith("#") && extension.length() > 0) { extensions.add(extension); } extension = svcIn.readLine(); } } } catch (IOException ex) { throw new GroovyRuntimeException("IO Exception attempting to load source extension registerers. Exception: " + ex.toString() + (service == null ? "" : service.toExternalForm())); } return extensions; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/SourceUnit.java0000644001501200150120000003051011707612046024441 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyClassLoader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.control.io.FileReaderSource; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.control.io.StringReaderSource; import org.codehaus.groovy.control.io.URLReaderSource; import org.codehaus.groovy.control.messages.Message; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.*; import org.codehaus.groovy.tools.Utilities; import antlr.CharScanner; import antlr.MismatchedTokenException; import antlr.MismatchedCharException; import antlr.NoViableAltException; import antlr.NoViableAltForCharException; import com.thoughtworks.xstream.XStream; /** * Provides an anchor for a single source unit (usually a script file) * as it passes through the compiler system. * * @author Chris Poirier * @author Bing Ran * @version $Id$ */ public class SourceUnit extends ProcessingUnit { /** * The pluggable parser used to generate the AST - we allow * pluggability currently as we need to have Classic and JSR support */ private ParserPlugin parserPlugin; /** * Where we can get Readers for our source unit */ protected ReaderSource source; /** * A descriptive name of the source unit. This name shouldn't * be used for controlling the SourceUnit, it is only for error * messages and to determine the name of the class for * a script. */ protected String name; /** * A Concrete Syntax Tree of the source */ protected Reduction cst; /** * The root of the Abstract Syntax Tree for the source */ protected ModuleNode ast; /** * Initializes the SourceUnit from existing machinery. */ public SourceUnit(String name, ReaderSource source, CompilerConfiguration flags, GroovyClassLoader loader, ErrorCollector er) { super(flags, loader, er); this.name = name; this.source = source; } /** * Initializes the SourceUnit from the specified file. */ public SourceUnit(File source, CompilerConfiguration configuration, GroovyClassLoader loader, ErrorCollector er) { this(source.getPath(), new FileReaderSource(source, configuration), configuration, loader, er); } /** * Initializes the SourceUnit from the specified URL. */ public SourceUnit(URL source, CompilerConfiguration configuration, GroovyClassLoader loader, ErrorCollector er) { this(source.getPath(), new URLReaderSource(source, configuration), configuration, loader, er); } /** * Initializes the SourceUnit for a string of source. */ public SourceUnit(String name, String source, CompilerConfiguration configuration, GroovyClassLoader loader, ErrorCollector er) { this(name, new StringReaderSource(source, configuration), configuration, loader, er); } /** * Returns the name for the SourceUnit. This name shouldn't * be used for controlling the SourceUnit, it is only for error * messages */ public String getName() { return name; } /** * Returns the Concrete Syntax Tree produced during parse()ing. */ public Reduction getCST() { return this.cst; } /** * Returns the Abstract Syntax Tree produced during convert()ing * and expanded during later phases. */ public ModuleNode getAST() { return this.ast; } /** * Convenience routine, primarily for use by the InteractiveShell, * that returns true if parse() failed with an unexpected EOF. */ public boolean failedWithUnexpectedEOF() { // Implementation note - there are several ways for the Groovy compiler // to report an unexpected EOF. Perhaps this implementation misses some. // If you find another way, please add it. if (getErrorCollector().hasErrors()) { Message last = (Message) getErrorCollector().getLastError(); Throwable cause = null; if (last instanceof SyntaxErrorMessage) { cause = ((SyntaxErrorMessage) last).getCause().getCause(); } if (cause != null) { if (cause instanceof NoViableAltException) { return isEofToken(((NoViableAltException) cause).token); } else if (cause instanceof NoViableAltForCharException) { char badChar = ((NoViableAltForCharException) cause).foundChar; return badChar == CharScanner.EOF_CHAR; } else if (cause instanceof MismatchedCharException) { char badChar = (char) ((MismatchedCharException) cause).foundChar; return badChar == CharScanner.EOF_CHAR; } else if (cause instanceof MismatchedTokenException) { return isEofToken(((MismatchedTokenException) cause).token); } } } return false; } protected boolean isEofToken(antlr.Token token) { return token.getType() == antlr.Token.EOF_TYPE; } //--------------------------------------------------------------------------- // FACTORIES /** * A convenience routine to create a standalone SourceUnit on a String * with defaults for almost everything that is configurable. */ public static SourceUnit create(String name, String source) { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setTolerance(1); return new SourceUnit(name, source, configuration, null, new ErrorCollector(configuration)); } /** * A convenience routine to create a standalone SourceUnit on a String * with defaults for almost everything that is configurable. */ public static SourceUnit create(String name, String source, int tolerance) { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setTolerance(tolerance); return new SourceUnit(name, source, configuration, null, new ErrorCollector(configuration)); } //--------------------------------------------------------------------------- // PROCESSING /** * Parses the source to a CST. You can retrieve it with getCST(). */ public void parse() throws CompilationFailedException { if (this.phase > Phases.PARSING) { throw new GroovyBugError("parsing is already complete"); } if (this.phase == Phases.INITIALIZATION) { nextPhase(); } // // Create a reader on the source and run the parser. Reader reader = null; try { reader = source.getReader(); // let's recreate the parser each time as it tends to keep around state parserPlugin = getConfiguration().getPluginFactory().createParserPlugin(); cst = parserPlugin.parseCST(this, reader); reader.close(); } catch (IOException e) { getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), this)); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Ignore } } } } /** * Generates an AST from the CST. You can retrieve it with getAST(). */ public void convert() throws CompilationFailedException { if (this.phase == Phases.PARSING && this.phaseComplete) { gotoPhase(Phases.CONVERSION); } if (this.phase != Phases.CONVERSION) { throw new GroovyBugError("SourceUnit not ready for convert()"); } // // Build the AST try { this.ast = parserPlugin.buildAST(this, this.classLoader, this.cst); this.ast.setDescription(this.name); } catch (SyntaxException e) { if (this.ast == null) { // Create a dummy ModuleNode to represent a failed parse - in case a later phase attempts to use the ast this.ast = new ModuleNode(this); } getErrorCollector().addError(new SyntaxErrorMessage(e, this)); } String property = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("groovy.ast"); } }); if ("xml".equals(property)) { saveAsXML(name, ast); } } private void saveAsXML(String name, ModuleNode ast) { XStream xstream = new XStream(); try { xstream.toXML(ast, new FileWriter(name + ".xml")); System.out.println("Written AST to " + name + ".xml"); } catch (Exception e) { System.out.println("Couldn't write to " + name + ".xml"); e.printStackTrace(); } } //--------------------------------------------------------------------------- // SOURCE SAMPLING /** * Returns a sampling of the source at the specified line and column, * of null if it is unavailable. */ public String getSample(int line, int column, Janitor janitor) { String sample = null; String text = source.getLine(line, janitor); if (text != null) { if (column > 0) { String marker = Utilities.repeatString(" ", column - 1) + "^"; if (column > 40) { int start = column - 30 - 1; int end = (column + 10 > text.length() ? text.length() : column + 10 - 1); sample = " " + text.substring(start, end) + Utilities.eol() + " " + marker.substring(start, marker.length()); } else { sample = " " + text + Utilities.eol() + " " + marker; } } else { sample = text; } } return sample; } /** * This method adds an exception to the error collector. The Exception most likely has no line number attached to it. * For this reason you should use this method sparingly. Prefer using addError for syntax errors or add an error * to the {@link ErrorCollector} directly by retrieving it with getErrorCollector(). * @param e * the exception that occurred * @throws CompilationFailedException * on error */ public void addException(Exception e) throws CompilationFailedException { getErrorCollector().addException(e, this); } /** * This method adds a SyntaxException to the error collector. The exception should specify the line and column * number of the error. This method should be reserved for real errors in the syntax of the SourceUnit. If * your error is not in syntax, and is a semantic error, or more general error, then use addException or use * the error collector directly by retrieving it with getErrorCollector(). * @param se * the exception, which should have line and column information * @throws CompilationFailedException * on error */ public void addError(SyntaxException se) throws CompilationFailedException { getErrorCollector().addError(se, this); } public ReaderSource getSource() { return source; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/CompilationFailedException.java0000644001501200150120000000401311627206700027577 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyRuntimeException; /** * Thrown when compilation fails from source errors. * * @author Chris Poirier * @version $Id$ */ public class CompilationFailedException extends GroovyRuntimeException { protected int phase; // The phase in which the failures occurred protected ProcessingUnit unit; // The *Unit object this exception wraps public CompilationFailedException(int phase, ProcessingUnit unit, Throwable cause) { super(Phases.getDescription(phase) + " failed", cause); this.phase = phase; this.unit = unit; } public CompilationFailedException(int phase, ProcessingUnit unit) { super(Phases.getDescription(phase) + " failed"); this.phase = phase; this.unit = unit; } /** * Formats the error data as a String. */ /*public String toString() { StringWriter data = new StringWriter(); PrintWriter writer = new PrintWriter(data); Janitor janitor = new Janitor(); try { unit.getErrorReporter().write(writer, janitor); } finally { janitor.cleanup(); } return data.toString(); }*/ /** * Returns the ProcessingUnit in which the error occurred. */ public ProcessingUnit getUnit() { return this.unit; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/CompilerConfiguration.java0000644001501200150120000006114211715031256026645 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.control.io.NullWriter; import org.codehaus.groovy.control.messages.WarningMessage; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; /** * Compilation control flags and coordination stuff. * * @author Chris Poirier * @author Jochen Theodorou * @author Jim White * @version $Id$ */ public class CompilerConfiguration { private static final String JDK5_CLASSNAME_CHECK = "java.lang.annotation.Annotation"; /** This ("1.5") is the value for targetBytecode to compile for a JDK 1.5 or later JVM. **/ public static final String POST_JDK5 = "1.5"; /** This ("1.4") is the value for targetBytecode to compile for a JDK 1.4 JVM. **/ public static final String PRE_JDK5 = "1.4"; // Just call getVMVersion() once. public static final String currentJVMVersion = getVMVersion(); // Static initializers are executed in text order, // therefore we must do this one last! /** * A convenience for getting a default configuration. Do not modify it! * See {@link #CompilerConfiguration(Properties)} for an example on how to * make a suitable copy to modify. But if you're really starting from a * default context, then you probably just want new CompilerConfiguration(). */ public static final CompilerConfiguration DEFAULT = new CompilerConfiguration(); /** * See {@link WarningMessage} for levels. */ private int warningLevel; /** * Encoding for source files */ private String sourceEncoding; /** * A PrintWriter for communicating with the user */ private PrintWriter output; /** * Directory into which to write classes */ private File targetDirectory; /** * Classpath for use during compilation */ private LinkedList classpath; /** * If true, the compiler should produce action information */ private boolean verbose; /** * If true, debugging code should be activated */ private boolean debug; /** * The number of non-fatal errors to allow before bailing */ private int tolerance; /** * Base class name for scripts (must derive from Script) */ private String scriptBaseClass; private ParserPluginFactory pluginFactory; /** * extension used to find a groovy file */ private String defaultScriptExtension; /** * extensions used to find a groovy files */ private Set scriptExtensions = new LinkedHashSet(); /** * if set to true recompilation is enabled */ private boolean recompileGroovySource; /** * sets the minimum of time after a script can be recompiled. */ private int minimumRecompilationInterval; /** * sets the bytecode version target */ private String targetBytecode; /** * options for joint compilation (null by default == no joint compilation) */ private Map jointCompilationOptions; /** * options for optimizations (empty map by default) */ private Map optimizationOptions; private List compilationCustomizers = new LinkedList(); /** * Sets the Flags to defaults. */ public CompilerConfiguration() { // // Set in safe defaults setWarningLevel(WarningMessage.LIKELY_ERRORS); setOutput(null); setTargetDirectory((File) null); setClasspath(""); setVerbose(false); setDebug(false); setTolerance(10); setScriptBaseClass(null); setRecompileGroovySource(false); setMinimumRecompilationInterval(100); // Target bytecode String targetByteCode = null; try { targetByteCode = System.getProperty("groovy.target.bytecode", targetByteCode); } catch (Exception e) { // IGNORE } if(targetByteCode != null) { setTargetBytecode(targetByteCode); } else { setTargetBytecode(getVMVersion()); } String tmpDefaultScriptExtension = null; try { tmpDefaultScriptExtension = System.getProperty("groovy.default.scriptExtension"); } catch (Exception e) { // IGNORE } if(tmpDefaultScriptExtension != null) { setDefaultScriptExtension(tmpDefaultScriptExtension); } else { setDefaultScriptExtension(".groovy"); } // // Source file encoding String encoding = null; try { encoding = System.getProperty("file.encoding", "US-ASCII"); } catch (Exception e) { // IGNORE } try { encoding = System.getProperty("groovy.source.encoding", encoding); } catch (Exception e) { // IGNORE } setSourceEncoding(encoding); try { setOutput(new PrintWriter(System.err)); } catch (Exception e) { // IGNORE } try { String target = System.getProperty("groovy.target.directory"); if (target != null) { setTargetDirectory(target); } } catch (Exception e) { // IGNORE } setOptimizationOptions(new HashMap(2)); } /** * Copy constructor. Use this if you have a mostly correct configuration * for your compilation but you want to make a some changes programatically. * An important reason to prefer this approach is that your code will most * likely be forward compatible with future changes to this configuration API.
    * An example of this copy constructor at work:
    *
         *    // In all likelihood there is already a configuration in your code's context
         *    // for you to copy, but for the sake of this example we'll use the global default.
         *    CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
         *    myConfiguration.setDebug(true);
         *
    * @param configuration The configuration to copy. */ public CompilerConfiguration(CompilerConfiguration configuration) { setWarningLevel(configuration.getWarningLevel()); setOutput(configuration.getOutput()); setTargetDirectory(configuration.getTargetDirectory()); setClasspathList(new LinkedList(configuration.getClasspath())); setVerbose(configuration.getVerbose()); setDebug(configuration.getDebug()); setTolerance(configuration.getTolerance()); setScriptBaseClass(configuration.getScriptBaseClass()); setRecompileGroovySource(configuration.getRecompileGroovySource()); setMinimumRecompilationInterval(configuration.getMinimumRecompilationInterval()); setTargetBytecode(configuration.getTargetBytecode()); setDefaultScriptExtension(configuration.getDefaultScriptExtension()); setSourceEncoding(configuration.getSourceEncoding()); setOutput(configuration.getOutput()); setTargetDirectory(configuration.getTargetDirectory()); Map jointCompilationOptions = configuration.getJointCompilationOptions(); if (jointCompilationOptions != null) { jointCompilationOptions = new HashMap(jointCompilationOptions); } setJointCompilationOptions(jointCompilationOptions); setPluginFactory(configuration.getPluginFactory()); setScriptExtensions(configuration.getScriptExtensions()); setOptimizationOptions(new HashMap(configuration.getOptimizationOptions())); } /** * Sets the Flags to the specified configuration, with defaults * for those not supplied. * Note that those "defaults" here do not include checking the * settings in {@link System#getProperties()} in general, only file.encoding, * groovy.target.directory and groovy.source.encoding are.
    * If you want to set a few flags but keep Groovy's default * configuration behavior then be sure to make your settings in * a Properties that is backed by System.getProperties() (which * is done using this constructor).
    * That might be done like this:
    *
         *    Properties myProperties = new Properties(System.getProperties());
         *    myProperties.setProperty("groovy.output.debug", "true");
         *    myConfiguration = new CompilerConfiguration(myProperties);
         * 
    * And you also have to contend with a possible SecurityException when * getting the system properties (See {@link java.lang.System#getProperties()}).
    * An safer method would be to copy a default * CompilerConfiguration and make your changes there using the * setter.
    *
         *    // In all likelihood there is already a configuration for you to copy,
         *    // but for the sake of this example we'll use the global default.
         *    CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
         *    myConfiguration.setDebug(true);
         * 
    * Another reason to use the copy constructor rather than this one is that you * must call {@link #setOutput}. Calling setOutput(null) is valid and will * set up a PrintWriter to a bit bucket. The copy constructor will of course set * the same one as the original. * *
    Property KeyGet/Set Property Name
    "groovy.warnings"{@link #getWarningLevel}
    "groovy.source.encoding"{@link #getSourceEncoding}
    "groovy.target.directory"{@link #getTargetDirectory}
    "groovy.target.bytecode"{@link #getTargetBytecode}
    "groovy.classpath"{@link #getClasspath}
    "groovy.output.verbose"{@link #getVerbose}
    "groovy.output.debug"{@link #getDebug}
    "groovy.errors.tolerance"{@link #getTolerance}
    "groovy.script.extension"{@link #getDefaultScriptExtension}
    "groovy.script.base"{@link #getScriptBaseClass}
    "groovy.recompile"{@link #getRecompileGroovySource}
    "groovy.recompile.minimumInterval"{@link #getMinimumRecompilationInterval}

    * @param configuration The properties to get flag values from. */ public CompilerConfiguration(Properties configuration) throws ConfigurationException { this(); configure(configuration); } /** * Method to configure a this CompilerConfiguration by using Properties. * For a list of available properties look at {link {@link #CompilerConfiguration(Properties)}. * @param configuration The properties to get flag values from. */ public void configure(Properties configuration) throws ConfigurationException { String text = null; int numeric = 0; // // Warning level numeric = getWarningLevel(); try { text = configuration.getProperty("groovy.warnings", "likely errors"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { text = text.toLowerCase(); if (text.equals("none")) { numeric = WarningMessage.NONE; } else if (text.startsWith("likely")) { numeric = WarningMessage.LIKELY_ERRORS; } else if (text.startsWith("possible")) { numeric = WarningMessage.POSSIBLE_ERRORS; } else if (text.startsWith("paranoia")) { numeric = WarningMessage.PARANOIA; } else { throw new ConfigurationException("unrecognized groovy.warnings: " + text); } } setWarningLevel(numeric); // // Source file encoding // text = configuration.getProperty("groovy.source.encoding"); if (text == null) { text = configuration.getProperty("file.encoding", "US-ASCII"); } setSourceEncoding(text); // // Target directory for classes // text = configuration.getProperty("groovy.target.directory"); if (text != null) setTargetDirectory(text); text = configuration.getProperty("groovy.target.bytecode"); if (text != null) setTargetBytecode(text); // // Classpath // text = configuration.getProperty("groovy.classpath"); if (text != null) setClasspath(text); // // Verbosity // text = configuration.getProperty("groovy.output.verbose"); if (text != null && text.equalsIgnoreCase("true")) setVerbose(true); // // Debugging // text = configuration.getProperty("groovy.output.debug"); if (text != null && text.equalsIgnoreCase("true")) setDebug(true); // // Tolerance // numeric = 10; try { text = configuration.getProperty("groovy.errors.tolerance", "10"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { throw new ConfigurationException(e); } setTolerance(numeric); // // Script Base Class // text = configuration.getProperty("groovy.script.base"); if (text!=null) setScriptBaseClass(text); // // recompilation options // text = configuration.getProperty("groovy.recompile"); if (text != null) { setRecompileGroovySource(text.equalsIgnoreCase("true")); } numeric = 100; try { text = configuration.getProperty("groovy.recompile.minimumIntervall"); if (text==null) text = configuration.getProperty("groovy.recompile.minimumInterval"); if (text!=null) { numeric = Integer.parseInt(text); } else { numeric = 100; } } catch (NumberFormatException e) { throw new ConfigurationException(e); } setMinimumRecompilationInterval(numeric); } /** * Gets the currently configured warning level. See WarningMessage * for level details. */ public int getWarningLevel() { return this.warningLevel; } /** * Sets the warning level. See WarningMessage for level details. */ public void setWarningLevel(int level) { if (level < WarningMessage.NONE || level > WarningMessage.PARANOIA) { this.warningLevel = WarningMessage.LIKELY_ERRORS; } else { this.warningLevel = level; } } /** * Gets the currently configured source file encoding. */ public String getSourceEncoding() { return this.sourceEncoding; } /** * Sets the encoding to be used when reading source files. */ public void setSourceEncoding(String encoding) { if (encoding == null) encoding = "US-ASCII"; this.sourceEncoding = encoding; } /** * Gets the currently configured output writer. */ public PrintWriter getOutput() { return this.output; } /** * Sets the output writer. */ public void setOutput(PrintWriter output) { if (output == null) { this.output = new PrintWriter(NullWriter.DEFAULT); } else { this.output = output; } } /** * Gets the target directory for writing classes. */ public File getTargetDirectory() { return this.targetDirectory; } /** * Sets the target directory. */ public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } } /** * Sets the target directory. */ public void setTargetDirectory(File directory) { this.targetDirectory = directory; } /** * @return the classpath */ public List getClasspath() { return this.classpath; } /** * Sets the classpath. */ public void setClasspath(String classpath) { this.classpath = new LinkedList(); StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { this.classpath.add(tokenizer.nextToken()); } } /** * sets the classpath using a list of Strings * @param parts list of strings containing the classpath parts */ public void setClasspathList(List parts) { this.classpath = new LinkedList(parts); } /** * Returns true if verbose operation has been requested. */ public boolean getVerbose() { return this.verbose; } /** * Turns verbose operation on or off. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Returns true if debugging operation has been requested. */ public boolean getDebug() { return this.debug; } /** * Turns debugging operation on or off. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Returns the requested error tolerance. */ public int getTolerance() { return this.tolerance; } /** * Sets the error tolerance, which is the number of * non-fatal errors (per unit) that should be tolerated before * compilation is aborted. */ public void setTolerance(int tolerance) { this.tolerance = tolerance; } /** * Gets the name of the base class for scripts. It must be a subclass * of Script. */ public String getScriptBaseClass() { return this.scriptBaseClass; } /** * Sets the name of the base class for scripts. It must be a subclass * of Script. */ public void setScriptBaseClass(String scriptBaseClass) { this.scriptBaseClass = scriptBaseClass; } public ParserPluginFactory getPluginFactory() { if (pluginFactory == null) { pluginFactory = ParserPluginFactory.newInstance(true); } return pluginFactory; } public void setPluginFactory(ParserPluginFactory pluginFactory) { this.pluginFactory = pluginFactory; } public void setScriptExtensions(Set scriptExtensions) { if(scriptExtensions == null) scriptExtensions = new LinkedHashSet(); this.scriptExtensions = scriptExtensions; } public Set getScriptExtensions() { if(scriptExtensions == null || scriptExtensions.isEmpty()) { /* * this happens * * when groovyc calls FileSystemCompiler in forked mode, or * * when FileSystemCompiler is run from the command line directly, or * * when groovy was not started using groovyc or FileSystemCompiler either */ scriptExtensions = SourceExtensionHandler.getRegisteredExtensions( this.getClass().getClassLoader()); } return scriptExtensions; } public String getDefaultScriptExtension() { return defaultScriptExtension; } public void setDefaultScriptExtension(String defaultScriptExtension) { this.defaultScriptExtension = defaultScriptExtension; } public void setRecompileGroovySource(boolean recompile) { recompileGroovySource = recompile; } public boolean getRecompileGroovySource(){ return recompileGroovySource; } public void setMinimumRecompilationInterval(int time) { minimumRecompilationInterval = Math.max(0,time); } public int getMinimumRecompilationInterval() { return minimumRecompilationInterval; } /** * Allow setting the bytecode compatibility. The parameter can take * one of the values 1.5 or 1.4. If wrong parameter * then the value will default to VM determined version. * * @param version the bytecode compatibility mode */ public void setTargetBytecode(String version) { if(PRE_JDK5.equals(version) || POST_JDK5.equals(version)) { this.targetBytecode = version; } } /** * Retrieves the compiler bytecode compatibility mode. * * @return bytecode compatibility mode. Can be either 1.5 or 1.4. */ public String getTargetBytecode() { return this.targetBytecode; } private static String getVMVersion() { try { Class.forName(JDK5_CLASSNAME_CHECK); return POST_JDK5; } catch(Exception ex) { // IGNORE } return PRE_JDK5; } /** * Gets the joint compilation options for this configuration. * @return the options */ public Map getJointCompilationOptions() { return jointCompilationOptions; } /** * Sets the joint compilation options for this configuration. * Using null will disable joint compilation. * @param options the options */ public void setJointCompilationOptions(Map options) { jointCompilationOptions = options; } /** * Gets the optimization options for this configuration. * @return the options (always not null) */ public Map getOptimizationOptions() { return optimizationOptions; } /** * Sets the optimization options for this configuration. * No entry or a true for that entry means to enable that optimization, * a false means the optimization is disabled. * Valid keys are "all" and "int". * @param options the options. * @throws IllegalArgumentException if the options are null */ public void setOptimizationOptions(Map options) { if (options==null) throw new IllegalArgumentException("provided option map must not be null"); optimizationOptions = options; } /** * Adds compilation customizers to the compilation process. A compilation customizer is a class node * operation which performs various operations going from adding imports to access control. * @param customizers the list of customizers to be added * @return this configuration instance */ public CompilerConfiguration addCompilationCustomizers(CompilationCustomizer... customizers) { if (customizers==null) throw new IllegalArgumentException("provided customizers list must not be null"); compilationCustomizers.addAll(Arrays.asList(customizers)); return this; } /** * Returns the list of compilation customizers. * @return the customizers (always not null) */ public List getCompilationCustomizers() { return compilationCustomizers; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/ConfigurationException.java0000644001501200150120000000361511627206700027032 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import org.codehaus.groovy.GroovyExceptionInterface; /** * Thrown when configuration data is invalid. * * @author Chris Poirier * * @version $Id$ */ public class ConfigurationException extends RuntimeException implements GroovyExceptionInterface { //--------------------------------------------------------------------------- // CONSTRUCTION AND SUCH protected Exception cause; // The phase in which the failures occurred /** * Initializes the exception from a cause exception. */ public ConfigurationException( Exception cause ) { super( cause.getMessage() ); this.cause = cause; } /** * Initializes the exception with just a message. */ public ConfigurationException( String message ) { super( message ); } /** * Returns the causing exception, if available. */ public Throwable getCause() { return cause; } /** * Its always fatal. */ public boolean isFatal() { return true; } /** * Set fatal is just ignored. */ public void setFatal( boolean fatal ) { } } groovy-1.8.6/src/main/org/codehaus/groovy/control/ProcessingUnit.java0000644001501200150120000001034711707612046025323 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyClassLoader; /** * A base class for data structures that can collect messages and errors * during processing. * * @author Chris Poirier * @version $Id$ */ public abstract class ProcessingUnit { /** * The current phase */ protected int phase; /** * Set true if phase is finished */ protected boolean phaseComplete; /** * Configuration and other settings that control processing */ protected CompilerConfiguration configuration; /** * The ClassLoader to use during processing */ protected GroovyClassLoader classLoader; /** * a helper to share errors and report them */ protected ErrorCollector errorCollector; /** * Initialize the ProcessingUnit to the empty state. */ public ProcessingUnit(CompilerConfiguration configuration, GroovyClassLoader classLoader, ErrorCollector er) { this.phase = Phases.INITIALIZATION; this.configuration = configuration; this.setClassLoader(classLoader); configure((configuration == null ? new CompilerConfiguration() : configuration)); if (er==null) er = new ErrorCollector(getConfiguration()); this.errorCollector = er; } /** * Reconfigures the ProcessingUnit. */ public void configure(CompilerConfiguration configuration) { this.configuration = configuration; } public CompilerConfiguration getConfiguration() { return configuration; } public void setConfiguration(CompilerConfiguration configuration) { this.configuration = configuration; } /** * Returns the class loader in use by this ProcessingUnit. */ public GroovyClassLoader getClassLoader() { return classLoader; } /** * Sets the class loader for use by this ProcessingUnit. */ public void setClassLoader(GroovyClassLoader loader) { ClassLoader parent = Thread.currentThread().getContextClassLoader(); if (parent == null) parent = ProcessingUnit.class.getClassLoader(); this.classLoader = (loader == null ? new GroovyClassLoader(parent, configuration) : loader); } /** * Returns the current phase. */ public int getPhase() { return this.phase; } /** * Returns the description for the current phase. */ public String getPhaseDescription() { return Phases.getDescription(this.phase); } /** * Errors found during the compilation should be reported through the ErrorCollector. * @return * the ErrorCollector for this ProcessingUnit */ public ErrorCollector getErrorCollector() { return errorCollector; } //--------------------------------------------------------------------------- // PROCESSING /** * Marks the current phase complete and processes any * errors. */ public void completePhase() throws CompilationFailedException { errorCollector.failIfErrors(); phaseComplete = true; } /** * A synonym for gotoPhase( phase + 1 ). */ public void nextPhase() throws CompilationFailedException { gotoPhase(this.phase + 1); } /** * Wraps up any pending operations for the current phase * and switches to the next phase. */ public void gotoPhase(int phase) throws CompilationFailedException { if (!this.phaseComplete) { completePhase(); } this.phase = phase; this.phaseComplete = false; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/StaticImportVisitor.java0000644001501200150120000005764011707612046026360 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import static org.codehaus.groovy.runtime.MetaClassHelper.capitalize; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.syntax.Types; import java.util.*; /** * Visitor to resolve constants and method calls from static Imports * * @author Jochen Theodorou * @author Paul King */ public class StaticImportVisitor extends ClassCodeExpressionTransformer { private ClassNode currentClass; private MethodNode currentMethod; private SourceUnit source; private boolean inSpecialConstructorCall; private boolean inClosure; private boolean inPropertyExpression; private Expression foundConstant; private Expression foundArgs; private boolean inAnnotation; private boolean inLeftExpression; public void visitClass(ClassNode node, SourceUnit source) { this.currentClass = node; this.source = source; super.visitClass(node); } @Override protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { this.currentMethod = node; super.visitConstructorOrMethod(node, isConstructor); this.currentMethod = null; } @Override public void visitAnnotations(AnnotatedNode node) { boolean oldInAnnotation = inAnnotation; inAnnotation = true; super.visitAnnotations(node); inAnnotation = oldInAnnotation; } public Expression transform(Expression exp) { if (exp == null) return null; if (exp.getClass() == VariableExpression.class) { return transformVariableExpression((VariableExpression) exp); } if (exp.getClass() == BinaryExpression.class) { return transformBinaryExpression((BinaryExpression) exp); } if (exp.getClass() == PropertyExpression.class) { return transformPropertyExpression((PropertyExpression) exp); } if (exp.getClass() == MethodCallExpression.class) { return transformMethodCallExpression((MethodCallExpression) exp); } if (exp.getClass() == ClosureExpression.class) { return transformClosureExpression((ClosureExpression) exp); } if (exp.getClass() == ConstructorCallExpression.class) { return transformConstructorCallExpression((ConstructorCallExpression) exp); } if (exp.getClass() == ArgumentListExpression.class) { Expression result = exp.transformExpression(this); if (inPropertyExpression) { foundArgs = result; } return result; } if (exp instanceof ConstantExpression) { Expression result = exp.transformExpression(this); if (inPropertyExpression) { foundConstant = result; } if (inAnnotation && exp instanceof AnnotationConstantExpression) { ConstantExpression ce = (ConstantExpression) result; if (ce.getValue() instanceof AnnotationNode) { // replicate a little bit of AnnotationVisitor here // because we can't wait until later to do this AnnotationNode an = (AnnotationNode) ce.getValue(); Map attributes = an.getMembers(); for (Map.Entry entry : attributes.entrySet()) { Expression attrExpr = transform(entry.getValue()); entry.setValue(attrExpr); } } } return result; } return exp.transformExpression(this); } // if you have a Bar class with a static foo property, and this: // import static Bar.foo as baz // then this constructor (not normal usage of statics): // new Bar(baz:1) // will become: // new Bar(foo:1) private Expression transformMapEntryExpression(MapEntryExpression me, ClassNode constructorCallType) { Expression key = me.getKeyExpression(); Expression value = me.getValueExpression(); ModuleNode module = currentClass.getModule(); if (module != null && key instanceof ConstantExpression) { Map importNodes = module.getStaticImports(); if (importNodes.containsKey(key.getText())) { ImportNode importNode = importNodes.get(key.getText()); if (importNode.getType().equals(constructorCallType)) { String newKey = importNode.getFieldName(); return new MapEntryExpression(new ConstantExpression(newKey), value.transformExpression(this)); } } } return me; } protected Expression transformBinaryExpression(BinaryExpression be) { int type = be.getOperation().getType(); boolean oldInLeftExpression; Expression right = transform(be.getRightExpression()); be.setRightExpression(right); Expression left; if (type == Types.EQUAL) { oldInLeftExpression = inLeftExpression; inLeftExpression = true; left = transform(be.getLeftExpression()); inLeftExpression = oldInLeftExpression; if (left instanceof StaticMethodCallExpression) { StaticMethodCallExpression smce = (StaticMethodCallExpression) left; StaticMethodCallExpression result = new StaticMethodCallExpression(smce.getOwnerType(), smce.getMethod(), right); setSourcePosition(result, be); return result; } } else { left = transform(be.getLeftExpression()); } be.setLeftExpression(left); return be; } protected Expression transformVariableExpression(VariableExpression ve) { Variable v = ve.getAccessedVariable(); if (v != null && v instanceof DynamicVariable) { Expression result = findStaticFieldOrPropAccessorImportFromModule(v.getName()); if (result != null) { setSourcePosition(result, ve); if (inAnnotation) { result = transformInlineConstants(result); } return result; } } return ve; } /** * Set the source position of toSet including its property expression if it has one. * * @param toSet resulting node * @param origNode original node */ private void setSourcePosition(Expression toSet, Expression origNode) { toSet.setSourcePosition(origNode); if (toSet instanceof PropertyExpression) { ((PropertyExpression) toSet).getProperty().setSourcePosition(origNode); } } // resolve constant-looking expressions statically (do here as gets transformed away later) private Expression transformInlineConstants(Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum()) return exp; Expression constant = findConstant(type.getField(pe.getPropertyAsString())); if (constant != null) return constant; } } else if (exp instanceof ListExpression) { ListExpression le = (ListExpression) exp; ListExpression result = new ListExpression(); for (Expression e : le.getExpressions()) { result.addExpression(transformInlineConstants(e)); } return result; } return exp; } private Expression findConstant(FieldNode fn) { if (fn != null && !fn.isEnum() && fn.isStatic() && fn.isFinal()) { if (fn.getInitialValueExpression() instanceof ConstantExpression) { return fn.getInitialValueExpression(); } } return null; } protected Expression transformMethodCallExpression(MethodCallExpression mce) { Expression args = transform(mce.getArguments()); Expression method = transform(mce.getMethod()); Expression object = transform(mce.getObjectExpression()); boolean isExplicitThisOrSuper = false; if (object instanceof VariableExpression) { VariableExpression ve = (VariableExpression) object; isExplicitThisOrSuper = !mce.isImplicitThis() && (ve.getName().equals("this") || ve.getName().equals("super")); } if (mce.isImplicitThis() || isExplicitThisOrSuper) { if (mce.isImplicitThis()) { Expression ret = findStaticMethodImportFromModule(method, args); if (ret != null) { setSourcePosition(ret, mce); return ret; } if (method instanceof ConstantExpression && !inLeftExpression) { // could be a closure field String methodName = (String) ((ConstantExpression) method).getValue(); ret = findStaticFieldOrPropAccessorImportFromModule(methodName); if (ret != null) { ret = new MethodCallExpression(ret, "call", args); setSourcePosition(ret, mce); return ret; } } } if (method instanceof ConstantExpression) { ConstantExpression ce = (ConstantExpression) method; Object value = ce.getValue(); if (value instanceof String) { String methodName = (String) value; boolean lookForPossibleStaticMethod = !methodName.equals("call"); if (currentMethod != null && !currentMethod.isStatic()) { if (currentClass.hasPossibleMethod(methodName, args)) { lookForPossibleStaticMethod = false; } } if (inSpecialConstructorCall || (lookForPossibleStaticMethod && currentClass.hasPossibleStaticMethod(methodName, args))) { StaticMethodCallExpression smce = new StaticMethodCallExpression(currentClass, methodName, args); setSourcePosition(smce, mce); return smce; } } } } MethodCallExpression result = new MethodCallExpression(object, method, args); result.setSafe(mce.isSafe()); result.setImplicitThis(mce.isImplicitThis()); result.setSpreadSafe(mce.isSpreadSafe()); result.setMethodTarget(mce.getMethodTarget()); setSourcePosition(result, mce); return result; } protected Expression transformConstructorCallExpression(ConstructorCallExpression cce) { inSpecialConstructorCall = cce.isSpecialCall(); Expression expression = cce.getArguments(); if (expression instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) expression; if (tuple.getExpressions().size() == 1) { expression = tuple.getExpression(0); if (expression instanceof NamedArgumentListExpression) { NamedArgumentListExpression namedArgs = (NamedArgumentListExpression) expression; List entryExpressions = namedArgs.getMapEntryExpressions(); for (int i = 0; i < entryExpressions.size(); i++) { entryExpressions.set(i, (MapEntryExpression) transformMapEntryExpression(entryExpressions.get(i), cce.getType())); } } } } Expression ret = cce.transformExpression(this); inSpecialConstructorCall = false; return ret; } protected Expression transformClosureExpression(ClosureExpression ce) { boolean oldInClosure = inClosure; inClosure = true; Statement code = ce.getCode(); if (code != null) code.visit(this); inClosure = oldInClosure; return ce; } protected Expression transformPropertyExpression(PropertyExpression pe) { boolean oldInPropertyExpression = inPropertyExpression; Expression oldFoundArgs = foundArgs; Expression oldFoundConstant = foundConstant; inPropertyExpression = true; foundArgs = null; foundConstant = null; Expression objectExpression = transform(pe.getObjectExpression()); boolean candidate = false; if (objectExpression instanceof MethodCallExpression) { candidate = ((MethodCallExpression)objectExpression).isImplicitThis(); } if (foundArgs != null && foundConstant != null && candidate) { Expression result = findStaticMethodImportFromModule(foundConstant, foundArgs); if (result != null) { objectExpression = result; objectExpression.setSourcePosition(pe); } } inPropertyExpression = oldInPropertyExpression; foundArgs = oldFoundArgs; foundConstant = oldFoundConstant; pe.setObjectExpression(objectExpression); return pe; } private Expression findStaticFieldOrPropAccessorImportFromModule(String name) { ModuleNode module = currentClass.getModule(); if (module == null) return null; Map importNodes = module.getStaticImports(); Expression expression; String accessorName = getAccessorName(name); // look for one of these: // import static MyClass.setProp [as setOtherProp] // import static MyClass.getProp [as getOtherProp] // when resolving prop reference if (importNodes.containsKey(accessorName)) { ImportNode importNode = importNodes.get(accessorName); expression = findStaticPropertyAccessorByFullName(importNode.getType(), importNode.getFieldName()); if (expression != null) return expression; expression = findStaticPropertyAccessor(importNode.getType(), getPropNameForAccessor(importNode.getFieldName())); if (expression != null) return expression; } if (accessorName.startsWith("get")) { accessorName = "is" + accessorName.substring(3); if (importNodes.containsKey(accessorName)) { ImportNode importNode = importNodes.get(accessorName); expression = findStaticPropertyAccessorByFullName(importNode.getType(), importNode.getFieldName()); if (expression != null) return expression; expression = findStaticPropertyAccessor(importNode.getType(), getPropNameForAccessor(importNode.getFieldName())); if (expression != null) return expression; } } // look for one of these: // import static MyClass.prop [as otherProp] // when resolving prop or field reference if (importNodes.containsKey(name)) { ImportNode importNode = importNodes.get(name); expression = findStaticPropertyAccessor(importNode.getType(), importNode.getFieldName()); if (expression != null) return expression; expression = findStaticField(importNode.getType(), importNode.getFieldName()); if (expression != null) return expression; } // look for one of these: // import static MyClass.* // when resolving prop or field reference for (ImportNode importNode : module.getStaticStarImports().values()) { ClassNode node = importNode.getType(); expression = findStaticPropertyAccessor(node, name); if (expression != null) return expression; expression = findStaticField(node, name); if (expression != null) return expression; } return null; } private Expression findStaticMethodImportFromModule(Expression method, Expression args) { ModuleNode module = currentClass.getModule(); if (module == null || !(method instanceof ConstantExpression)) return null; Map importNodes = module.getStaticImports(); ConstantExpression ce = (ConstantExpression) method; Expression expression; Object value = ce.getValue(); // skip non-Strings, e.g. Integer if (!(value instanceof String)) return null; final String name = (String) value; // look for one of these: // import static SomeClass.method [as otherName] // when resolving methodCall() or getProp() or setProp() if (importNodes.containsKey(name)) { ImportNode importNode = importNodes.get(name); expression = findStaticMethod(importNode.getType(), importNode.getFieldName(), args); if (expression != null) return expression; expression = findStaticPropertyAccessorGivenArgs(importNode.getType(), getPropNameForAccessor(importNode.getFieldName()), args); if (expression != null) { return new StaticMethodCallExpression(importNode.getType(), importNode.getFieldName(), args); } } // look for one of these: // import static SomeClass.someProp [as otherName] // when resolving getProp() or setProp() if (validPropName(name)) { String propName = getPropNameForAccessor(name); if (importNodes.containsKey(propName)) { ImportNode importNode = importNodes.get(propName); expression = findStaticMethod(importNode.getType(), prefix(name) + capitalize(importNode.getFieldName()), args); if (expression != null) return expression; expression = findStaticPropertyAccessorGivenArgs(importNode.getType(), importNode.getFieldName(), args); if (expression != null) { return new StaticMethodCallExpression(importNode.getType(), prefix(name) + capitalize(importNode.getFieldName()), args); } } } Map starImports = module.getStaticStarImports(); ClassNode starImportType; if (currentClass.isEnum() && starImports.containsKey(currentClass.getName())) { ImportNode importNode = starImports.get(currentClass.getName()); starImportType = importNode == null ? null : importNode.getType(); expression = findStaticMethod(starImportType, name, args); if (expression != null) return expression; } else { for (ImportNode importNode : starImports.values()) { starImportType = importNode == null ? null : importNode.getType(); expression = findStaticMethod(starImportType, name, args); if (expression != null) return expression; expression = findStaticPropertyAccessorGivenArgs(starImportType, getPropNameForAccessor(name), args); if (expression != null) { return new StaticMethodCallExpression(starImportType, name, args); } } } return null; } private String prefix(String name) { return name.startsWith("is") ? "is" : name.substring(0, 3); } private String getPropNameForAccessor(String fieldName) { int prefixLength = fieldName.startsWith("is") ? 2 : 3; if (fieldName.length() < prefixLength + 1) return fieldName; if (!validPropName(fieldName)) return fieldName; return String.valueOf(fieldName.charAt(prefixLength)).toLowerCase() + fieldName.substring(prefixLength + 1); } private boolean validPropName(String propName) { return propName.startsWith("get") || propName.startsWith("is") || propName.startsWith("set"); } private String getAccessorName(String name) { return (inLeftExpression ? "set" : "get") + capitalize(name); } private Expression findStaticPropertyAccessorGivenArgs(ClassNode staticImportType, String propName, Expression args) { // TODO validate args? return findStaticPropertyAccessor(staticImportType, propName); } private Expression findStaticPropertyAccessor(ClassNode staticImportType, String propName) { String accessorName = getAccessorName(propName); Expression accessor = findStaticPropertyAccessorByFullName(staticImportType, accessorName); if (accessor == null && accessorName.startsWith("get")) { accessor = findStaticPropertyAccessorByFullName(staticImportType, "is" + accessorName.substring(3)); } if (accessor == null && hasStaticProperty(staticImportType, propName)) { // args will be replaced if (inLeftExpression) accessor = new StaticMethodCallExpression(staticImportType, accessorName, ArgumentListExpression.EMPTY_ARGUMENTS); else accessor = new PropertyExpression(new ClassExpression(staticImportType), propName); } return accessor; } private boolean hasStaticProperty(ClassNode staticImportType, String propName) { ClassNode classNode = staticImportType; while (classNode != null) { for (PropertyNode pn : classNode.getProperties()) { if (pn.getName().equals(propName) && pn.isStatic()) return true; } classNode = classNode.getSuperClass(); } return false; } private Expression findStaticPropertyAccessorByFullName(ClassNode staticImportType, String accessorMethodName) { // anything will do as we only check size == 1 ArgumentListExpression dummyArgs = new ArgumentListExpression(); dummyArgs.addExpression(new EmptyExpression()); return findStaticMethod(staticImportType, accessorMethodName, (inLeftExpression ? dummyArgs : ArgumentListExpression.EMPTY_ARGUMENTS)); } private Expression findStaticField(ClassNode staticImportType, String fieldName) { if (staticImportType.isPrimaryClassNode() || staticImportType.isResolved()) { FieldNode field = staticImportType.getField(fieldName); if (field != null && field.isStatic()) return new PropertyExpression(new ClassExpression(staticImportType), fieldName); } return null; } private Expression findStaticMethod(ClassNode staticImportType, String methodName, Expression args) { if (staticImportType.isPrimaryClassNode() || staticImportType.isResolved()) { if (staticImportType.hasPossibleStaticMethod(methodName, args)) { return new StaticMethodCallExpression(staticImportType, methodName, args); } } return null; } protected SourceUnit getSourceUnit() { return source; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/MultipleCompilationErrorsException.java0000644001501200150120000000340211627206700031404 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Jochen Theodorou */ public class MultipleCompilationErrorsException extends CompilationFailedException { protected ErrorCollector collector; public MultipleCompilationErrorsException(ErrorCollector ec) { super(0, null); if (ec == null) { CompilerConfiguration config = super.getUnit() != null ? super.getUnit().getConfiguration() : new CompilerConfiguration(); collector = new ErrorCollector(config); } else { collector = ec; } } public ErrorCollector getErrorCollector() { return collector; } public String getMessage() { StringWriter data = new StringWriter(); PrintWriter writer = new PrintWriter(data); Janitor janitor = new Janitor(); writer.write(super.getMessage()); writer.println(":"); try { collector.write(writer, janitor); } finally { janitor.cleanup(); } return data.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/CompilationUnit.java0000644001501200150120000011356511715031256025470 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.classgen.*; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.control.io.InputStreamReaderSource; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.Message; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.tools.GroovyClass; import org.codehaus.groovy.transform.ASTTransformationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.CodeSource; import java.util.*; /** * The CompilationUnit collects all compilation data as it is generated by the compiler system. * You can use this object to add additional source units to the compilation, or force the * compilation to be run again (to affect only the deltas).

    * * You can also add PhaseOperations to this compilation using the addPhaseOperation method. * This is commonly used when you want to wire a new AST Transformation into the compilation. * * @author Chris Poirier * @author Jochen Theodorou * @author Roshan Dawrani * @version $Id$ */ public class CompilationUnit extends ProcessingUnit { //--------------------------------------------------------------------------- // CONSTRUCTION AND SUCH private GroovyClassLoader transformLoader; // Classloader for global and local transforms protected Map sources; // The SourceUnits from which this unit is built protected Map summariesBySourceName; // Summary of each SourceUnit protected Map summariesByPublicClassName; // Summary of each SourceUnit protected Map classSourcesByPublicClassName; // Summary of each Class protected List names; // Names for each SourceUnit in sources. protected LinkedList queuedSources; protected CompileUnit ast; // The overall AST for this CompilationUnit. protected List generatedClasses; // The classes generated during classgen. protected Verifier verifier; // For use by verify(). protected boolean debug; // Controls behavior of classgen() and other routines. protected boolean configured; // Set true after the first configure() operation protected ClassgenCallback classgenCallback; // A callback for use during classgen() protected ProgressCallback progressCallback; // A callback for use during compile() protected ResolveVisitor resolveVisitor; protected StaticImportVisitor staticImportVisitor; protected OptimizerVisitor optimizer; LinkedList[] phaseOperations; LinkedList[] newPhaseOperations; /** * Initializes the CompilationUnit with defaults. */ public CompilationUnit() { this(null, null, null); } /** * Initializes the CompilationUnit with defaults except for class loader. */ public CompilationUnit(GroovyClassLoader loader) { this(null, null, loader); } /** * Initializes the CompilationUnit with no security considerations. */ public CompilationUnit(CompilerConfiguration configuration) { this(configuration, null, null); } /** * Initializes the CompilationUnit with a CodeSource for controlling * security stuff and a class loader for loading classes. */ public CompilationUnit(CompilerConfiguration configuration, CodeSource security, GroovyClassLoader loader) { this(configuration, security, loader, null); } /** * Initializes the CompilationUnit with a CodeSource for controlling * security stuff, a class loader for loading classes, and a class * loader for loading AST transformations. * Note The transform loader must be * able to load compiler classes. That means CompilationUnit.class.classLoader * must be at last a parent to transformLoader. The other loader has no such constraint. * * @param transformLoader - the loader for transforms * @param loader - loader used to resolve classes against during compilation * @param security - security setting for the compilation * @param configuration - compilation configuration */ public CompilationUnit(CompilerConfiguration configuration, CodeSource security, GroovyClassLoader loader, GroovyClassLoader transformLoader) { super(configuration, loader, null); this.transformLoader = transformLoader; this.names = new ArrayList(); this.queuedSources = new LinkedList(); this.sources = new HashMap(); this.summariesBySourceName = new HashMap(); this.summariesByPublicClassName = new HashMap(); this.classSourcesByPublicClassName = new HashMap(); this.ast = new CompileUnit(this.classLoader, security, this.configuration); this.generatedClasses = new ArrayList(); this.verifier = new Verifier(); this.resolveVisitor = new ResolveVisitor(this); this.staticImportVisitor = new StaticImportVisitor(); this.optimizer = new OptimizerVisitor(this); phaseOperations = new LinkedList[Phases.ALL + 1]; newPhaseOperations = new LinkedList[Phases.ALL + 1]; for (int i = 0; i < phaseOperations.length; i++) { phaseOperations[i] = new LinkedList(); newPhaseOperations[i] = new LinkedList(); } addPhaseOperation(new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { source.parse(); } }, Phases.PARSING); addPhaseOperation(convert, Phases.CONVERSION); addPhaseOperation(new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { EnumVisitor ev = new EnumVisitor(CompilationUnit.this, source); ev.visitClass(classNode); } }, Phases.CONVERSION); addPhaseOperation(resolve, Phases.SEMANTIC_ANALYSIS); addPhaseOperation(staticImport, Phases.SEMANTIC_ANALYSIS); addPhaseOperation(new PrimaryClassNodeOperation() { @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { InnerClassVisitor iv = new InnerClassVisitor(CompilationUnit.this, source); iv.visitClass(classNode); } }, Phases.SEMANTIC_ANALYSIS); addPhaseOperation(compileCompleteCheck, Phases.CANONICALIZATION); addPhaseOperation(classgen, Phases.CLASS_GENERATION); addPhaseOperation(output); ASTTransformationVisitor.addPhaseOperations(this); addPhaseOperation(new PrimaryClassNodeOperation() { @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { StaticVerifier sv = new StaticVerifier(); sv.visitClass(classNode, source); } }, Phases.SEMANTIC_ANALYSIS); addPhaseOperation(new PrimaryClassNodeOperation() { @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { InnerClassCompletionVisitor iv = new InnerClassCompletionVisitor(); iv.visitClass(classNode); } }, Phases.CANONICALIZATION); addPhaseOperation(new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { EnumCompletionVisitor ecv = new EnumCompletionVisitor(CompilationUnit.this, source); ecv.visitClass(classNode); } }, Phases.CANONICALIZATION); // apply configuration customizers if any if (configuration != null) { final List customizers = configuration.getCompilationCustomizers(); for (CompilationCustomizer customizer : customizers) { addPhaseOperation(customizer, customizer.getPhase().getPhaseNumber()); } } this.classgenCallback = null; } /** * Returns the class loader for loading AST transformations. * @return - the transform class loader */ public GroovyClassLoader getTransformLoader() { return transformLoader == null ? getClassLoader() : transformLoader; } public void addPhaseOperation(SourceUnitOperation op, int phase) { if (phase < 0 || phase > Phases.ALL) throw new IllegalArgumentException("phase " + phase + " is unknown"); phaseOperations[phase].add(op); } public void addPhaseOperation(PrimaryClassNodeOperation op, int phase) { if (phase < 0 || phase > Phases.ALL) throw new IllegalArgumentException("phase " + phase + " is unknown"); phaseOperations[phase].add(op); } public void addPhaseOperation(GroovyClassOperation op) { phaseOperations[Phases.OUTPUT].addFirst(op); } public void addNewPhaseOperation(SourceUnitOperation op, int phase) { if (phase < 0 || phase > Phases.ALL) throw new IllegalArgumentException("phase " + phase + " is unknown"); newPhaseOperations[phase].add(op); } /** * Configures its debugging mode and classloader classpath from a given compiler configuration. * This cannot be done more than once due to limitations in {@link java.net.URLClassLoader URLClassLoader}. */ public void configure(CompilerConfiguration configuration) { super.configure(configuration); this.debug = configuration.getDebug(); if (!this.configured && this.classLoader instanceof GroovyClassLoader) { appendCompilerConfigurationClasspathToClassLoader(configuration, (GroovyClassLoader) this.classLoader); } this.configured = true; } private void appendCompilerConfigurationClasspathToClassLoader(CompilerConfiguration configuration, GroovyClassLoader classLoader) { /*for (Iterator iterator = configuration.getClasspath().iterator(); iterator.hasNext(); ) { classLoader.addClasspath((String) iterator.next()); }*/ } /** * Returns the CompileUnit that roots our AST. */ public CompileUnit getAST() { return this.ast; } /** * Get the source summaries */ public Map getSummariesBySourceName() { return summariesBySourceName; } public Map getSummariesByPublicClassName() { return summariesByPublicClassName; } public Map getClassSourcesByPublicClassName() { return classSourcesByPublicClassName; } public boolean isPublicClass(String className) { return summariesByPublicClassName.containsKey(className); } /** * Get the GroovyClasses generated by compile(). */ public List getClasses() { return generatedClasses; } /** * Convenience routine to get the first ClassNode, for * when you are sure there is only one. */ public ClassNode getFirstClassNode() { return this.ast.getModules().get(0).getClasses().get(0); } /** * Convenience routine to get the named ClassNode. */ public ClassNode getClassNode(final String name) { final ClassNode[] result = new ClassNode[]{null}; PrimaryClassNodeOperation handler = new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { if (classNode.getName().equals(name)) { result[0] = classNode; } } }; try { applyToPrimaryClassNodes(handler); } catch (CompilationFailedException e) { if (debug) e.printStackTrace(); } return result[0]; } //--------------------------------------------------------------------------- // SOURCE CREATION /** * Adds a set of file paths to the unit. */ public void addSources(String[] paths) { for (String path : paths) { addSource(new File(path)); } } /** * Adds a set of source files to the unit. */ public void addSources(File[] files) { for (File file : files) { addSource(file); } } /** * Adds a source file to the unit. */ public SourceUnit addSource(File file) { return addSource(new SourceUnit(file, configuration, classLoader, getErrorCollector())); } /** * Adds a source file to the unit. */ public SourceUnit addSource(URL url) { return addSource(new SourceUnit(url, configuration, classLoader, getErrorCollector())); } /** * Adds a InputStream source to the unit. */ public SourceUnit addSource(String name, InputStream stream) { ReaderSource source = new InputStreamReaderSource(stream, configuration); return addSource(new SourceUnit(name, source, configuration, classLoader, getErrorCollector())); } public SourceUnit addSource(String name, String scriptText) { return addSource(new SourceUnit(name, scriptText, configuration, classLoader, getErrorCollector())); } /** * Adds a SourceUnit to the unit. */ public SourceUnit addSource(SourceUnit source) { String name = source.getName(); source.setClassLoader(this.classLoader); for (SourceUnit su : queuedSources) { if (name.equals(su.getName())) return su; } queuedSources.add(source); return source; } /** * Returns an iterator on the unit's SourceUnits. */ public Iterator iterator() { return new Iterator() { Iterator nameIterator = names.iterator(); public boolean hasNext() { return nameIterator.hasNext(); } public SourceUnit next() { String name = nameIterator.next(); return sources.get(name); } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Adds a ClassNode directly to the unit (ie. without source). * WARNING: the source is needed for error reporting, using * this method without setting a SourceUnit will cause * NullPinterExceptions */ public void addClassNode(ClassNode node) { ModuleNode module = new ModuleNode(this.ast); this.ast.addModule(module); module.addClass(node); } //--------------------------------------------------------------------------- // EXTERNAL CALLBACKS /** * A callback interface you can use to "accompany" the classgen() * code as it traverses the ClassNode tree. You will be called-back * for each primary and inner class. Use setClassgenCallback() before * running compile() to set your callback. */ public abstract static class ClassgenCallback { public abstract void call(ClassVisitor writer, ClassNode node) throws CompilationFailedException; } /** * Sets a ClassgenCallback. You can have only one, and setting * it to null removes any existing setting. */ public void setClassgenCallback(ClassgenCallback visitor) { this.classgenCallback = visitor; } /** * A callback interface you can use to get a callback after every * unit of the compile process. You will be called-back with a * ProcessingUnit and a phase indicator. Use setProgressCallback() * before running compile() to set your callback. */ public abstract static class ProgressCallback { public abstract void call(ProcessingUnit context, int phase) throws CompilationFailedException; } /** * Sets a ProgressCallback. You can have only one, and setting * it to null removes any existing setting. */ public void setProgressCallback(ProgressCallback callback) { this.progressCallback = callback; } //--------------------------------------------------------------------------- // ACTIONS /** * Synonym for compile(Phases.ALL). */ public void compile() throws CompilationFailedException { compile(Phases.ALL); } /** * Compiles the compilation unit from sources. */ public void compile(int throughPhase) throws CompilationFailedException { // // To support delta compilations, we always restart // the compiler. The individual passes are responsible // for not reprocessing old code. gotoPhase(Phases.INITIALIZATION); throughPhase = Math.min(throughPhase, Phases.ALL); while (throughPhase >= phase && phase <= Phases.ALL) { if (phase == Phases.SEMANTIC_ANALYSIS) { doPhaseOperation(resolve); if (dequeued()) continue; } processPhaseOperations(phase); // Grab processing may have brought in new AST transforms into various phases, process them as well processNewPhaseOperations(phase); if (progressCallback != null) progressCallback.call(this, phase); completePhase(); applyToSourceUnits(mark); if (dequeued()) continue; gotoPhase(phase + 1); if (phase == Phases.CLASS_GENERATION) { sortClasses(); } } errorCollector.failIfErrors(); } private void processPhaseOperations(int ph) { LinkedList ops = phaseOperations[ph]; for (Object next : ops) { doPhaseOperation(next); } } private void processNewPhaseOperations(int currPhase) { recordPhaseOpsInAllOtherPhases(currPhase); LinkedList currentPhaseNewOps = newPhaseOperations[currPhase]; while (!currentPhaseNewOps.isEmpty()) { Object operation = currentPhaseNewOps.removeFirst(); // push this operation to master list and then process it. phaseOperations[currPhase].add(operation); doPhaseOperation(operation); // if this operation has brought in more phase ops for ast transforms, keep recording them // in master list of other phases and keep processing them for this phase. recordPhaseOpsInAllOtherPhases(currPhase); currentPhaseNewOps = newPhaseOperations[currPhase]; } } private void doPhaseOperation(Object operation) { if (operation instanceof PrimaryClassNodeOperation) { applyToPrimaryClassNodes((PrimaryClassNodeOperation) operation); } else if (operation instanceof SourceUnitOperation) { applyToSourceUnits((SourceUnitOperation) operation); } else { applyToGeneratedGroovyClasses((GroovyClassOperation) operation); } } private void recordPhaseOpsInAllOtherPhases(int currPhase) { // apart from current phase, push new operations for every other phase in the master phase ops list for (int ph = Phases.INITIALIZATION; ph <= Phases.ALL; ph++) { if (ph != currPhase && !newPhaseOperations[ph].isEmpty()) { phaseOperations[ph].addAll(newPhaseOperations[ph]); newPhaseOperations[ph].clear(); } } } private void sortClasses() throws CompilationFailedException { for (ModuleNode module : this.ast.getModules()) { module.sortClasses(); } } /** * Dequeues any source units add through addSource and resets the compiler phase * to initialization. *

    * Note: this does not mean a file is recompiled. If a SourceUnit has already passed * a phase it is skipped until a higher phase is reached. * * @return true if there was a queued source * @throws CompilationFailedException */ protected boolean dequeued() throws CompilationFailedException { boolean dequeue = !queuedSources.isEmpty(); while (!queuedSources.isEmpty()) { SourceUnit su = queuedSources.removeFirst(); String name = su.getName(); names.add(name); sources.put(name, su); } if (dequeue) { gotoPhase(Phases.INITIALIZATION); } return dequeue; } /** * Resolves all types */ private final SourceUnitOperation resolve = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { List classes = source.ast.getClasses(); for (ClassNode node : classes) { VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(node); resolveVisitor.startResolving(node, source); } } }; private PrimaryClassNodeOperation staticImport = new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { staticImportVisitor.visitClass(classNode, source); } }; /** * Runs convert() on a single SourceUnit. */ private SourceUnitOperation convert = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { source.convert(); CompilationUnit.this.ast.addModule(source.getAST()); if (CompilationUnit.this.progressCallback != null) { CompilationUnit.this.progressCallback.call(source, CompilationUnit.this.phase); } } }; private GroovyClassOperation output = new GroovyClassOperation() { public void call(GroovyClass gclass) throws CompilationFailedException { String name = gclass.getName().replace('.', File.separatorChar) + ".class"; File path = new File(configuration.getTargetDirectory(), name); // // Ensure the path is ready for the file // File directory = path.getParentFile(); if (directory != null && !directory.exists()) { directory.mkdirs(); } // // Create the file and write out the data // byte[] bytes = gclass.getBytes(); FileOutputStream stream = null; try { stream = new FileOutputStream(path); stream.write(bytes, 0, bytes.length); } catch (IOException e) { getErrorCollector().addError(Message.create(e.getMessage(), CompilationUnit.this)); } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { // Ignore } } } } }; /* checks if all needed classes are compiled before generating the bytecode */ private SourceUnitOperation compileCompleteCheck = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { List classes = source.ast.getClasses(); for (ClassNode node : classes) { CompileUnit cu = node.getCompileUnit(); for (Iterator iter = cu.iterateClassNodeToCompile(); iter.hasNext();) { String name = (String) iter.next(); SourceUnit su = ast.getScriptSourceLocation(name); List classesInSourceUnit = su.ast.getClasses(); StringBuffer message = new StringBuffer(); message .append("Compilation incomplete: expected to find the class ") .append(name) .append(" in ") .append(su.getName()); if (classesInSourceUnit.isEmpty()) { message.append(", but the file seems not to contain any classes"); } else { message.append(", but the file contains the classes: "); boolean first = true; for (ClassNode cn : classesInSourceUnit) { if (!first) { message.append(", "); } else { first = false; } message.append(cn.getName()); } } getErrorCollector().addErrorAndContinue( new SimpleMessage(message.toString(), CompilationUnit.this) ); iter.remove(); } } } }; /** * Runs classgen() on a single ClassNode. */ private PrimaryClassNodeOperation classgen = new PrimaryClassNodeOperation() { public boolean needSortedInput() { return true; } public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { optimizer.visitClass(classNode, source); // GROOVY-4272: repositioned it here from staticImport if(!classNode.isSynthetic()) { GenericsVisitor genericsVisitor = new GenericsVisitor(source); genericsVisitor.visitClass(classNode); } // // Run the Verifier on the outer class // try { verifier.visitClass(classNode); } catch (GroovyRuntimeException rpe) { ASTNode node = rpe.getNode(); getErrorCollector().addError( new SyntaxException(rpe.getMessage(), null, node.getLineNumber(), node.getColumnNumber()), source ); } LabelVerifier lv = new LabelVerifier(source); lv.visitClass(classNode); ClassCompletionVerifier completionVerifier = new ClassCompletionVerifier(source); completionVerifier.visitClass(classNode); ExtendedVerifier xverifier = new ExtendedVerifier(source); xverifier.visitClass(classNode); // because the class may be generated even if a error was found // and that class may have an invalid format we fail here if needed getErrorCollector().failIfErrors(); // // Prep the generator machinery // ClassVisitor visitor = createClassVisitor(); String sourceName = (source == null ? classNode.getModule().getDescription() : source.getName()); // only show the file name and its extension like javac does in its stacktraces rather than the full path // also takes care of both \ and / depending on the host compiling environment if (sourceName != null) sourceName = sourceName.substring(Math.max(sourceName.lastIndexOf('\\'), sourceName.lastIndexOf('/')) + 1); ClassGenerator generator = new AsmClassGenerator(source, context, visitor, sourceName); // // Run the generation and create the class (if required) // generator.visitClass(classNode); byte[] bytes = ((ClassWriter) visitor).toByteArray(); generatedClasses.add(new GroovyClass(classNode.getName(), bytes)); // // Handle any callback that's been set // if (CompilationUnit.this.classgenCallback != null) { classgenCallback.call(visitor, classNode); } // // Recurse for inner classes // LinkedList innerClasses = generator.getInnerClasses(); while (!innerClasses.isEmpty()) { classgen.call(source, context, (ClassNode) innerClasses.removeFirst()); } } }; protected ClassVisitor createClassVisitor() { return new ClassWriter(ClassWriter.COMPUTE_MAXS); } //--------------------------------------------------------------------------- // PHASE HANDLING /** * Updates the phase marker on all sources. */ protected void mark() throws CompilationFailedException { applyToSourceUnits(mark); } /** * Marks a single SourceUnit with the current phase, * if it isn't already there yet. */ private SourceUnitOperation mark = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { if (source.phase < phase) { source.gotoPhase(phase); } if (source.phase == phase && phaseComplete && !source.phaseComplete) { source.completePhase(); } } }; //--------------------------------------------------------------------------- // LOOP SIMPLIFICATION FOR SourceUnit OPERATIONS /** * An callback interface for use in the applyToSourceUnits loop driver. */ public abstract static class SourceUnitOperation { public abstract void call(SourceUnit source) throws CompilationFailedException; } /** * A loop driver for applying operations to all SourceUnits. * Automatically skips units that have already been processed * through the current phase. */ public void applyToSourceUnits(SourceUnitOperation body) throws CompilationFailedException { for (String name : names) { SourceUnit source = sources.get(name); if ((source.phase < phase) || (source.phase == phase && !source.phaseComplete)) { try { body.call(source); } catch (CompilationFailedException e) { throw e; } catch (Exception e) { GroovyBugError gbe = new GroovyBugError(e); changeBugText(gbe, source); throw gbe; } catch (GroovyBugError e) { changeBugText(e, source); throw e; } } } getErrorCollector().failIfErrors(); } //--------------------------------------------------------------------------- // LOOP SIMPLIFICATION FOR PRIMARY ClassNode OPERATIONS /** * An callback interface for use in the applyToSourceUnits loop driver. */ public abstract static class PrimaryClassNodeOperation { public abstract void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException; public boolean needSortedInput() { return false; } } public abstract static class GroovyClassOperation { public abstract void call(GroovyClass gclass) throws CompilationFailedException; } private int getSuperClassCount(ClassNode element) { int count = 0; while (element != null) { count++; element = element.getSuperClass(); } return count; } private int getSuperInterfaceCount(ClassNode element) { int count = 1; ClassNode[] interfaces = element.getInterfaces(); for (ClassNode anInterface : interfaces) { count = Math.max(count, getSuperInterfaceCount(anInterface) + 1); } return count; } private List getPrimaryClassNodes(boolean sort) { List unsorted = new ArrayList(); for (ModuleNode module : this.ast.getModules()) { for (ClassNode classNode : module.getClasses()) { unsorted.add(classNode); } } if (!sort) return unsorted; int[] indexClass = new int[unsorted.size()]; int[] indexInterface = new int[unsorted.size()]; { int i = 0; for (Iterator iter = unsorted.iterator(); iter.hasNext(); i++) { ClassNode element = iter.next(); if (element.isInterface()) { indexInterface[i] = getSuperInterfaceCount(element); indexClass[i] = -1; } else { indexClass[i] = getSuperClassCount(element); indexInterface[i] = -1; } } } List sorted = getSorted(indexInterface, unsorted); sorted.addAll(getSorted(indexClass, unsorted)); return sorted; } private List getSorted(int[] index, List unsorted) { List sorted = new ArrayList(unsorted.size()); for (int i = 0; i < unsorted.size(); i++) { int min = -1; for (int j = 0; j < unsorted.size(); j++) { if (index[j] == -1) continue; if (min == -1) { min = j; } else if (index[j] < index[min]) { min = j; } } if (min == -1) break; sorted.add(unsorted.get(min)); index[min] = -1; } return sorted; } /** * A loop driver for applying operations to all primary ClassNodes in * our AST. Automatically skips units that have already been processed * through the current phase. */ public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException { Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator(); while (classNodes.hasNext()) { SourceUnit context = null; try { ClassNode classNode = (ClassNode) classNodes.next(); context = classNode.getModule().getContext(); if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) { int offset = 1; Iterator iterator = classNode.getInnerClasses(); while (iterator.hasNext()) { iterator.next(); offset++; } body.call(context, new GeneratorContext(this.ast, offset), classNode); } } catch (CompilationFailedException e) { // fall through, getErrorReporter().failIfErrors() will trigger } catch (NullPointerException npe) { throw npe; } catch (GroovyBugError e) { changeBugText(e, context); throw e; } catch (Exception e) { // check the exception for a nested compilation exception ErrorCollector nestedCollector = null; for (Throwable next = e.getCause(); next != e && next != null; next = next.getCause()) { if (!(next instanceof MultipleCompilationErrorsException)) continue; MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) next; nestedCollector = mcee.collector; break; } if (nestedCollector != null) { getErrorCollector().addCollectorContents(nestedCollector); } else { getErrorCollector().addError(new ExceptionMessage(e, configuration.getDebug(), this)); } } } getErrorCollector().failIfErrors(); } public void applyToGeneratedGroovyClasses(GroovyClassOperation body) throws CompilationFailedException { if (this.phase != Phases.OUTPUT && !(this.phase == Phases.CLASS_GENERATION && this.phaseComplete)) { throw new GroovyBugError("CompilationUnit not ready for output(). Current phase=" + getPhaseDescription()); } for (GroovyClass gclass : this.generatedClasses) { // // Get the class and calculate its filesystem name // try { body.call(gclass); } catch (CompilationFailedException e) { // fall through, getErrorReporter().failIfErrors() will trigger } catch (NullPointerException npe) { throw npe; } catch (GroovyBugError e) { changeBugText(e, null); throw e; } catch (Exception e) { throw new GroovyBugError(e); } } getErrorCollector().failIfErrors(); } private void changeBugText(GroovyBugError e, SourceUnit context) { e.setBugText("exception in phase '" + getPhaseDescription() + "' in source unit '" + ((context != null) ? context.getName() : "?") + "' " + e.getBugText()); } } groovy-1.8.6/src/main/org/codehaus/groovy/control/CompilePhase.java0000644001501200150120000000603511707612046024717 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; /** * The phases of the GroovyCompiler. This is an enum facade on top of the * Phases object. In general, prefer using this object over Phases. * * @author Hamlet D'Arcy */ public enum CompilePhase { /** * source files are opened and environment configured */ INITIALIZATION(Phases.INITIALIZATION), /** * the grammar is used to to produce tree of tokens representing the source code */ PARSING(Phases.PARSING), /** * An abstract syntax tree (AST) is created from token trees */ CONVERSION(Phases.CONVERSION), /** * Performs consistency and validity checks that the grammar can't check for, and resolves classes */ SEMANTIC_ANALYSIS(Phases.SEMANTIC_ANALYSIS), /** * Complete building the AST */ CANONICALIZATION(Phases.CANONICALIZATION), /** * instruction set is chosen, for example java5 or pre java5 */ INSTRUCTION_SELECTION(Phases.INSTRUCTION_SELECTION), /** * creates the binary output in memory */ CLASS_GENERATION(Phases.CLASS_GENERATION), /** * write the binary output to the file system */ OUTPUT(Phases.OUTPUT), /** * Perform any last cleanup */ FINALIZATION(Phases.FINALIZATION), ; /** * The phases as an array, with a null entry. */ public static CompilePhase[] phases = { null, INITIALIZATION, PARSING, CONVERSION, SEMANTIC_ANALYSIS, CANONICALIZATION, INSTRUCTION_SELECTION, CLASS_GENERATION, OUTPUT, FINALIZATION, }; int phaseNumber; CompilePhase(int phaseNumber) { this.phaseNumber = phaseNumber; } /** * Returns the underlieng integer Phase number. */ public int getPhaseNumber() { return phaseNumber; } /** * Returns the CompilePhase for the given integer phase number. * @param phaseNumber * the phase number * @return * the CompilePhase or null if not found */ public static CompilePhase fromPhaseNumber(int phaseNumber) { for (CompilePhase phase : values()) { if (phase.phaseNumber == phaseNumber) { return phase; } } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/control/Janitor.java0000644001501200150120000000301011627206700023737 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.control; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * An agent that can be used to defer cleanup operations to * a later time. Users much implement the HasCleanup interface. * * @author Chris Poirier * * @version $Id$ */ public class Janitor implements HasCleanup { private final Set pending = new HashSet(); // All objects pending cleanup public void register( HasCleanup object ) { pending.add( object ); } public void cleanup() { Iterator iterator = pending.iterator(); while( iterator.hasNext() ) { HasCleanup object = (HasCleanup)iterator.next(); try { object.cleanup(); } catch( Exception e ) { // Ignore } } pending.clear(); } } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/0000755001501200150120000000000011707612046022032 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyExecutableMemberDoc.java0000644001501200150120000000216311627206700027741 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyExecutableMemberDoc extends GroovyMemberDoc { String flatSignature(); boolean isNative(); boolean isSynchronized(); boolean isVarArgs(); GroovyParameter[] parameters(); // GroovyParamTag[] paramTags(); String signature(); GroovyClassDoc[] thrownExceptions(); GroovyType[] thrownExceptionTypes(); // GroovyThrowsTag[] throwsTags(); // GroovyTypeVariable[] typeParameters(); // GroovyParamTag[] typeParamTags(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyAnnotationRef.java0000644001501200150120000000251611707612046026656 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyAnnotationRef { /** * The annotation being referenced. * * @return the annotation being referenced */ GroovyClassDoc type(); /** * Name of the annotation being referenced. Once resolved, * equates to type().typeName(). * * @return the name of the annotation reference */ String name(); /** * The string representation of the annotation reference. * Initially implemented as a temporary hack stored from the source. * To be replaced with strong-typed finer grained information. * * @return the text representation of the annotation ref */ String description(); }groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyConstructorDoc.java0000644001501200150120000000134111627206700027052 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyConstructorDoc extends GroovyExecutableMemberDoc { } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyProgramElementDoc.java0000644001501200150120000000210411627206700027444 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyProgramElementDoc extends GroovyDoc { GroovyAnnotationRef[] annotations(); GroovyClassDoc containingClass(); GroovyPackageDoc containingPackage(); boolean isFinal(); boolean isPackagePrivate(); boolean isPrivate(); boolean isProtected(); boolean isPublic(); boolean isStatic(); String modifiers(); int modifierSpecifier(); String qualifiedName(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyDocErrorReporter.java0000644001501200150120000000175111627206700027346 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyDocErrorReporter{ void printError(String arg0); // void printError(GroovySourcePosition arg0, String arg1); void printNotice(String arg0); // void printNotice(GroovySourcePosition arg0, String arg1); void printWarning(String arg0); // void printWarning(GroovySourcePosition arg0, String arg1); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyParameter.java0000644001501200150120000000150211627206700026016 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyParameter { GroovyAnnotationRef[] annotations(); String name(); GroovyType type(); String typeName(); String defaultValue(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/package.html0000644001501200150120000000022711627206700024311 0ustar miguelmiguel package org.codehaus.groovy.groovydoc.*

    GroovyDoc internal classes.

    groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyRootDoc.java0000644001501200150120000000212511627206700025451 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; import java.util.List; import java.util.Map; public interface GroovyRootDoc extends GroovyDoc, GroovyDocErrorReporter { GroovyClassDoc classNamed(String arg0); GroovyClassDoc[] classes(); String[][] options(); GroovyPackageDoc packageNamed(String arg0); GroovyClassDoc[] specifiedClasses(); GroovyPackageDoc[] specifiedPackages(); Map getVisibleClasses(List importedClassesAndPackages); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyMemberDoc.java0000644001501200150120000000136411627206700025741 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyMemberDoc extends GroovyProgramElementDoc { boolean isSynthetic(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyPackageDoc.java0000644001501200150120000000572111627206700026066 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyPackageDoc extends GroovyDoc { /** * All included classes and interfaces in this package. * * @return array of classes and interfaces found or empty array if none found */ GroovyClassDoc[] allClasses(); /** * All classes and interfaces in this package optionally * limited to just the included ones. * * @param filter Specifying true filters according to the specified access modifier option. * Specifying false includes all classes and interfaces regardless of access modifier option. * @return array of classes and interfaces found or empty array if none found */ GroovyClassDoc[] allClasses(boolean filter); // GroovyAnnotationTypeDoc[] annotationTypes(); // GroovyAnnotationDesc[] annotations(); /** * Included enum types in this package. * * @return array of enum types found or empty array if none found */ GroovyClassDoc[] enums(); /** * Included errors in this package. * * @return array of errors found or empty array if none found */ GroovyClassDoc[] errors(); /** * Included exceptions in this package. * * @return array of exceptions found or empty array if none found */ GroovyClassDoc[] exceptions(); /** * Find a class or interface within this package. * * @param className the name of the class to find * @return ClassDoc of found class or interface, or null if not found */ GroovyClassDoc findClass(String className); /** * Included interfaces in this package. * * @return array of interfaces found or empty array if none found */ GroovyClassDoc[] interfaces(); /** * Included ordinary classes in this package. * * @return array of ordinary classes (non-interface, non-enum, non-throwable classes) found or empty array if none found */ GroovyClassDoc[] ordinaryClasses(); /** * The one-sentence summary for the package derived from the beginning of the description. * * @return the summary */ String summary(); /** * Description of the package. * * @return the description */ String description(); String nameWithDots(); // not in JavaDoc API String getRelativeRootPath(); // not in JavaDoc API } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyTag.java0000644001501200150120000000171611627206700024620 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyTag { /** * The tag name, e.g. "deprecated", "param", "see" or "author". */ String name(); /** * The optional parameter for tags like "throws" and "param". */ String param(); /** * The text associated with the tag. */ String text(); }groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyFieldDoc.java0000644001501200150120000000161711627206700025556 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyFieldDoc extends GroovyMemberDoc { Object constantValue(); String constantValueExpression(); boolean isTransient(); boolean isVolatile(); // GroovySerialFieldTag[] serialFieldTags(); GroovyType type(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyType.java0000644001501200150120000000366311627206700025031 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyType { // GroovyAnnotationTypeDoc asAnnotationTypeDoc(); // // GroovyClassDoc asClassDoc(); // // GroovyParameterizedType asParameterizedType(); // // GroovyTypeVariable asTypeVariable(); // // GroovyWildcardType asWildcardType(); // // String dimension(); boolean isPrimitive(); /** * The qualified name of this type excluding any dimension information. * For example, a two dimensional array of String returns "java.lang.String". */ String qualifiedTypeName(); /** * The unqualified name of this type excluding any dimension or nesting information. * For example, the class Outer.Inner returns "Inner". */ String simpleTypeName(); /** * The unqualified name of this type excluding any dimension information. * For example, a two dimensional array of String returns "String". */ String typeName(); /** * The qualified name including any dimension information. * For example, a two dimensional array of String returns * "java.lang.String[][]", and the parameterized type * List<Integer> returns "java.util.List<java.lang.Integer>". */ String toString(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyClassDoc.java0000644001501200150120000000365711627206700025606 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyClassDoc extends GroovyType, GroovyProgramElementDoc { GroovyConstructorDoc[] constructors(); GroovyConstructorDoc[] constructors(boolean filter); boolean definesSerializableFields(); GroovyFieldDoc[] enumConstants(); GroovyFieldDoc[] fields(); GroovyFieldDoc[] properties(); GroovyFieldDoc[] fields(boolean filter); GroovyClassDoc findClass(String className); GroovyClassDoc[] importedClasses(); GroovyPackageDoc[] importedPackages(); GroovyClassDoc[] innerClasses(); GroovyClassDoc[] innerClasses(boolean filter); GroovyClassDoc[] interfaces(); GroovyType[] interfaceTypes(); boolean isAbstract(); boolean isExternalizable(); boolean isSerializable(); GroovyMethodDoc[] methods(); GroovyMethodDoc[] methods(boolean filter); GroovyFieldDoc[] serializableFields(); GroovyMethodDoc[] serializationMethods(); boolean subclassOf(GroovyClassDoc gcd); GroovyClassDoc superclass(); GroovyType superclassType(); // GroovyTypeVariable[] typeParameters(); // not supported in groovy // GroovyParamTag[] typeParamTags(); // not supported in groovy String getFullPathName(); // not in Java Doclet API String getRelativeRootPath(); // not in Java Doclet API } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyDoc.java0000644001501200150120000000271711627206700024614 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyDoc extends Comparable { String commentText(); // GroovyTag[] firstSentenceTags(); String getRawCommentText(); // GroovyTag[] inlineTags(); boolean isAnnotationType(); boolean isAnnotationTypeElement(); boolean isClass(); boolean isConstructor(); boolean isDeprecated(); boolean isEnum(); boolean isEnumConstant(); boolean isError(); boolean isException(); boolean isField(); boolean isIncluded(); boolean isInterface(); boolean isMethod(); boolean isOrdinaryClass(); String name(); // GroovySourcePosition position(); // GroovySeeTag[] seeTags(); void setRawCommentText(String arg0); // GroovyTag[] tags(); // GroovyTag[] tags(String arg0); String firstSentenceCommentText(); } groovy-1.8.6/src/main/org/codehaus/groovy/groovydoc/GroovyMethodDoc.java0000644001501200150120000000175411627206700025755 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.groovydoc; public interface GroovyMethodDoc extends GroovyExecutableMemberDoc { boolean isAbstract(); GroovyClassDoc overriddenClass(); GroovyMethodDoc overriddenMethod(); GroovyType overriddenType(); boolean overrides(GroovyMethodDoc arg0); GroovyType returnType(); //---- additional void setReturnType(GroovyType o); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/0000755001501200150120000000000011715031256020603 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java0000644001501200150120000001756511707612044026302 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.List; import java.util.Map; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; public abstract class ClassCodeVisitorSupport extends CodeVisitorSupport implements GroovyClassVisitor { public void visitClass(ClassNode node) { visitAnnotations(node); visitPackage(node.getPackage()); visitImports(node.getModule()); node.visitContents(this); visitObjectInitializerStatements(node); } protected void visitObjectInitializerStatements(ClassNode node) { for (Statement element : node.getObjectInitializerStatements()) { element.visit(this); } } public void visitPackage(PackageNode node) { if (node != null) { visitAnnotations(node); node.visit(this); } } public void visitImports(ModuleNode node) { if (node != null) { for (ImportNode importNode : node.getImports()) { visitAnnotations(importNode); importNode.visit(this); } for (ImportNode importStarNode : node.getStarImports()) { visitAnnotations(importStarNode); importStarNode.visit(this); } for (ImportNode importStaticNode : node.getStaticImports().values()) { visitAnnotations(importStaticNode); importStaticNode.visit(this); } for (ImportNode importStaticStarNode : node.getStaticStarImports().values()) { visitAnnotations(importStaticStarNode); importStaticStarNode.visit(this); } } } public void visitAnnotations(AnnotatedNode node) { List annotations = node.getAnnotations(); if (annotations.isEmpty()) return; for (AnnotationNode an : annotations) { // skip built-in properties if (an.isBuiltIn()) continue; for (Map.Entry member : an.getMembers().entrySet()) { member.getValue().visit(this); } } } protected void visitClassCodeContainer(Statement code) { if (code != null) code.visit(this); } @Override public void visitDeclarationExpression(DeclarationExpression expression) { visitAnnotations(expression); super.visitDeclarationExpression(expression); } protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { visitAnnotations(node); visitClassCodeContainer(node.getCode()); for (Parameter param : node.getParameters()) { visitAnnotations(param); } } public void visitConstructor(ConstructorNode node) { visitConstructorOrMethod(node, true); } public void visitMethod(MethodNode node) { visitConstructorOrMethod(node, false); } public void visitField(FieldNode node) { visitAnnotations(node); Expression init = node.getInitialExpression(); if (init != null) init.visit(this); } public void visitProperty(PropertyNode node) { visitAnnotations(node); Statement statement = node.getGetterBlock(); visitClassCodeContainer(statement); statement = node.getSetterBlock(); visitClassCodeContainer(statement); Expression init = node.getInitialExpression(); if (init != null) init.visit(this); } protected void addError(String msg, ASTNode expr) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); SourceUnit source = getSourceUnit(); source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source) ); } protected abstract SourceUnit getSourceUnit(); protected void visitStatement(Statement statement) { } public void visitAssertStatement(AssertStatement statement) { visitStatement(statement); super.visitAssertStatement(statement); } public void visitBlockStatement(BlockStatement block) { visitStatement(block); super.visitBlockStatement(block); } public void visitBreakStatement(BreakStatement statement) { visitStatement(statement); super.visitBreakStatement(statement); } public void visitCaseStatement(CaseStatement statement) { visitStatement(statement); super.visitCaseStatement(statement); } public void visitCatchStatement(CatchStatement statement) { visitStatement(statement); super.visitCatchStatement(statement); } public void visitContinueStatement(ContinueStatement statement) { visitStatement(statement); super.visitContinueStatement(statement); } public void visitDoWhileLoop(DoWhileStatement loop) { visitStatement(loop); super.visitDoWhileLoop(loop); } public void visitExpressionStatement(ExpressionStatement statement) { visitStatement(statement); super.visitExpressionStatement(statement); } public void visitForLoop(ForStatement forLoop) { visitStatement(forLoop); super.visitForLoop(forLoop); } public void visitIfElse(IfStatement ifElse) { visitStatement(ifElse); super.visitIfElse(ifElse); } public void visitReturnStatement(ReturnStatement statement) { visitStatement(statement); super.visitReturnStatement(statement); } public void visitSwitch(SwitchStatement statement) { visitStatement(statement); super.visitSwitch(statement); } public void visitSynchronizedStatement(SynchronizedStatement statement) { visitStatement(statement); super.visitSynchronizedStatement(statement); } public void visitThrowStatement(ThrowStatement statement) { visitStatement(statement); super.visitThrowStatement(statement); } public void visitTryCatchFinally(TryCatchStatement statement) { visitStatement(statement); super.visitTryCatchFinally(statement); } public void visitWhileLoop(WhileStatement loop) { visitStatement(loop); super.visitWhileLoop(loop); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/MixinNode.java0000644001501200150120000000330511627206700023341 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; /** * Represents a mixin which can be applied to any ClassNode to implement mixins * * @author James Strachan * @version $Revision$ */ public class MixinNode extends ClassNode { public static final MixinNode[] EMPTY_ARRAY = {}; /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superType the base class name - use "java.lang.Object" if no direct base class */ public MixinNode(String name, int modifiers, ClassNode superType) { this(name, modifiers, superType, ClassHelper.EMPTY_TYPE_ARRAY); } /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superType the base class name - use "java.lang.Object" if no direct base class */ public MixinNode(String name, int modifiers, ClassNode superType, ClassNode[] interfaces) { super(name, modifiers, superType, interfaces, MixinNode.EMPTY_ARRAY); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/MixinASTTransformation.java0000644001501200150120000000667611707612044026051 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import groovy.lang.Mixin; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.objectweb.asm.Opcodes; import java.util.Arrays; @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class MixinASTTransformation implements ASTTransformation { private static final ClassNode MY_TYPE = ClassHelper.make(Mixin.class); // TODO would it be better to actually statically mixin the methods? public void visit(ASTNode nodes[], SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotationNode node = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (!MY_TYPE.equals(node.getClassNode())) return; final Expression expr = node.getMember("value"); if (expr == null) { return; } Expression useClasses = null; if (expr instanceof ClassExpression) { useClasses = expr; } else if (expr instanceof ListExpression) { ListExpression listExpression = (ListExpression) expr; for (Expression ex : listExpression.getExpressions()) { if (!(ex instanceof ClassExpression)) return; } useClasses = expr; } if (useClasses == null) return; if (parent instanceof ClassNode) { ClassNode annotatedClass = (ClassNode) parent; final Parameter[] noparams = new Parameter[0]; MethodNode clinit = annotatedClass.getDeclaredMethod("", noparams); if (clinit == null) { clinit = annotatedClass.addMethod("", Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC, ClassHelper.VOID_TYPE, noparams, null, new BlockStatement()); clinit.setSynthetic(true); } final BlockStatement code = (BlockStatement) clinit.getCode(); code.addStatement( new ExpressionStatement( new MethodCallExpression( new PropertyExpression(new ClassExpression(annotatedClass), "metaClass"), "mixin", useClasses ) ) ); } } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/EnumConstantClassNode.java0000644001501200150120000000271311627206700025663 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; /** * Represents the anonymous inner class for an enum constant * This subtype is needed so that EnumVisitor can differentiate between the scenarios when a InnerClassNode * represents anonymous inner class for an enu constant and when it represents an enum class defined inside * another class * * @author Roshan Dawrani */ public class EnumConstantClassNode extends InnerClassNode { /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superClass the base class name - use "java.lang.Object" if no direct base class */ public EnumConstantClassNode(ClassNode outerClass, String name, int modifiers, ClassNode superClass) { super(outerClass, name, modifiers, superClass); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/AnnotationNode.java0000644001501200150120000001311411627206700024366 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.HashMap; import java.util.Map; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.GroovyBugError; /** * Represents an annotation which can be attached to interfaces, classes, methods and fields. * * @author James Strachan * @author Alex Popescu * @version $Revision$ */ public class AnnotationNode extends ASTNode { public static final int TYPE_TARGET = 1; public static final int CONSTRUCTOR_TARGET = 1 << 1; public static final int METHOD_TARGET = 1 << 2; public static final int FIELD_TARGET = 1 << 3; public static final int PARAMETER_TARGET = 1 << 4; public static final int LOCAL_VARIABLE_TARGET = 1 << 5; public static final int ANNOTATION_TARGET = 1 << 6; public static final int PACKAGE_TARGET = 1 << 7; private static final int ALL_TARGETS = TYPE_TARGET | CONSTRUCTOR_TARGET | METHOD_TARGET | FIELD_TARGET | PARAMETER_TARGET | LOCAL_VARIABLE_TARGET | ANNOTATION_TARGET | PACKAGE_TARGET; private final ClassNode classNode; private Map members = new HashMap(); private boolean runtimeRetention= false, sourceRetention= false, classRetention = false; private int allowedTargets = ALL_TARGETS; public AnnotationNode(ClassNode classNode) { this.classNode = classNode; } public ClassNode getClassNode() { return classNode; } public Map getMembers() { return members; } public Expression getMember(String name) { return members.get(name); } public void addMember(String name, Expression value) { Expression oldValue = members.get(name); if (oldValue == null) { members.put(name, value); } else { throw new GroovyBugError(String.format("Annotation member %s has already been added", name)); } } public void setMember(String name, Expression value) { members.put(name, value); } public boolean isBuiltIn(){ return false; } /** * Flag corresponding to RetentionPolicy. * @return true if the annotation should be visible at runtime, * false otherwise */ public boolean hasRuntimeRetention() { return this.runtimeRetention; } /** * Sets the internal flag of this annotation runtime retention policy. * If the current annotation has * RetentionPolicy.RUNTIME or if false * if the RetentionPolicy.CLASS. * @param flag if true then current annotation is marked as having * RetentionPolicy.RUNTIME. If false then * the annotation has RetentionPolicy.CLASS. */ public void setRuntimeRetention(boolean flag) { this.runtimeRetention = flag; } /** * Flag corresponding to RetentionPolicy.SOURCE. * @return true if the annotation is only allowed in sources * false otherwise */ public boolean hasSourceRetention() { if (!runtimeRetention && !classRetention) return true; return this.sourceRetention; } /** Sets the internal flag if the current annotation has * RetentionPolicy.SOURCE. */ public void setSourceRetention(boolean flag) { this.sourceRetention = flag; } /** * Flag corresponding to RetentionPolicy.CLASS. * @return true if the annotation is recorded by the compiler, * but not visible at runtime * * false otherwise */ public boolean hasClassRetention() { return this.classRetention; } /** Sets the internal flag if the current annotation has * RetentionPolicy.CLASS. */ public void setClassRetention(boolean flag) { this.classRetention = flag; } public void setAllowedTargets(int bitmap) { this.allowedTargets = bitmap; } public boolean isTargetAllowed(int target) { return (this.allowedTargets & target) == target; } public static String targetToName(int target) { switch(target) { case TYPE_TARGET: return "TYPE"; case CONSTRUCTOR_TARGET: return "CONSTRUCTOR"; case METHOD_TARGET: return "METHOD"; case FIELD_TARGET: return "FIELD"; case PARAMETER_TARGET: return "PARAMETER"; case LOCAL_VARIABLE_TARGET: return "LOCAL_VARIABLE"; case ANNOTATION_TARGET: return "ANNOTATION"; case PACKAGE_TARGET: return "PACKAGE"; default: return "unknown target"; } } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/0000755001501200150120000000000011715031256022231 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java0000644001501200150120000003442311707612044030070 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.builder; import groovy.lang.MissingPropertyException; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import java.util.ArrayList; import java.util.List; /** * Transformation to capture ASTBuilder from code statements. *

    * The AstBuilder "from code" approach is used with a single Closure * parameter. This transformation converts the ClosureExpression back * into source code and rewrites the AST so that the "from string" * builder is invoked on the source. In order for this to work, the * closure source must be given a goto label. It is the "from string" * approach's responsibility to remove the BlockStatement created * by the label. * * @author Hamlet D'Arcy */ @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) public class AstBuilderTransformation implements ASTTransformation { public void visit(ASTNode[] nodes, SourceUnit sourceUnit) { // todo : are there other import types that can be specified? AstBuilderInvocationTrap transformer = new AstBuilderInvocationTrap( sourceUnit.getAST().getImports(), sourceUnit.getAST().getStarImports(), sourceUnit.getSource(), sourceUnit ); if (nodes != null) { for (ASTNode it : nodes) { if (!(it instanceof AnnotationNode) && !(it instanceof ClassNode)) { it.visit(transformer); } } } if (sourceUnit.getAST() != null) { sourceUnit.getAST().visit(transformer); if (sourceUnit.getAST().getStatementBlock() != null) { sourceUnit.getAST().getStatementBlock().visit(transformer); } if (sourceUnit.getAST().getClasses() != null) { for (ClassNode classNode : sourceUnit.getAST().getClasses()) { if (classNode.getMethods() != null) { for (MethodNode node : classNode.getMethods()) { if (node != null && node.getCode() != null) { node.getCode().visit(transformer); } } } try { if (classNode.getDeclaredConstructors() != null) { for (MethodNode node : classNode.getDeclaredConstructors()) { if (node != null && node.getCode() != null) { node.getCode().visit(transformer); } } } } catch (MissingPropertyException ignored) { // todo: inner class nodes don't have a constructors field available } // all properties are also always fields if (classNode.getFields() != null) { for (FieldNode node : classNode.getFields()) { if (node.getInitialValueExpression() != null) { node.getInitialValueExpression().visit(transformer); } } } try { if (classNode.getObjectInitializerStatements() != null) { for (Statement node : classNode.getObjectInitializerStatements()) { if (node != null) { node.visit(transformer); } } } } catch (MissingPropertyException ignored) { // todo: inner class nodes don't have a objectInitializers field available } // todo: is there anything to do with the module ??? } } if (sourceUnit.getAST().getMethods() != null) { for (MethodNode node : sourceUnit.getAST().getMethods()) { if (node != null) { if (node.getParameters() != null) { for (Parameter parameter : node.getParameters()) { if (parameter != null && parameter.getInitialExpression() != null) { parameter.getInitialExpression().visit(transformer); } } } if (node.getCode() != null) { node.getCode().visit(transformer); } } } } } } /** * This class traps invocations of AstBuilder.build(CompilePhase, boolean, Closure) and converts * the contents of the closure into expressions by reading the source of the Closure and sending * that as a String to AstBuilder.build(String, CompilePhase, boolean) at runtime. */ private static class AstBuilderInvocationTrap extends CodeVisitorSupport { private final List factoryTargets = new ArrayList(); private final ReaderSource source; private final SourceUnit sourceUnit; /** * Creates the trap and captures all the ways in which a class may be referenced via imports. * * @param imports all the imports from the source * @param importPackages all the imported packages from the source * @param source the reader source that contains source for the SourceUnit * @param sourceUnit the source unit being compiled. Used for error messages. */ AstBuilderInvocationTrap(List imports, List importPackages, ReaderSource source, SourceUnit sourceUnit) { if (source == null) throw new IllegalArgumentException("Null: source"); if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit"); this.source = source; this.sourceUnit = sourceUnit; // factory type may be references as fully qualified, an import, or an alias factoryTargets.add("org.codehaus.groovy.ast.builder.AstBuilder");//default package if (imports != null) { for (ImportNode importStatement : imports) { if ("org.codehaus.groovy.ast.builder.AstBuilder".equals(importStatement.getType().getName())) { factoryTargets.add(importStatement.getAlias()); } } } if (importPackages != null) { for (ImportNode importPackage : importPackages) { if ("org.codehaus.groovy.ast.builder.".equals(importPackage.getPackageName())) { factoryTargets.add("AstBuilder"); break; } } } } /** * Reports an error back to the source unit. * * @param msg the error message * @param expr the expression that caused the error message. */ private void addError(String msg, ASTNode expr) { int line = expr.getLineNumber(); int col = expr.getColumnNumber(); sourceUnit.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), sourceUnit) ); } /** * Attempts to find AstBuilder 'from code' invocations. When found, converts them into calls * to the 'from string' approach. * * @param call the method call expression that may or may not be an AstBuilder 'from code' invocation. */ public void visitMethodCallExpression(MethodCallExpression call) { if (isBuildInvocation(call)) { ClosureExpression closureExpression = getClosureArgument(call); List otherArgs = getNonClosureArguments(call); String source = convertClosureToSource(closureExpression); // parameter order is build(CompilePhase, boolean, String) otherArgs.add(new ConstantExpression(source)); call.setArguments(new ArgumentListExpression(otherArgs)); call.setMethod(new ConstantExpression("buildFromBlock")); call.setSpreadSafe(false); call.setSafe(false); call.setImplicitThis(false); } else { // continue normal tree walking call.getObjectExpression().visit(this); call.getMethod().visit(this); call.getArguments().visit(this); } } private List getNonClosureArguments(MethodCallExpression call) { List result = new ArrayList(); if (call.getArguments() instanceof TupleExpression) { for (ASTNode node : ((TupleExpression) call.getArguments()).getExpressions()) { if (!(node instanceof ClosureExpression)) { result.add((Expression) node); } } } return result; } private ClosureExpression getClosureArgument(MethodCallExpression call) { if (call.getArguments() instanceof TupleExpression) { for (ASTNode node : ((TupleExpression) call.getArguments()).getExpressions()) { if (node instanceof ClosureExpression) { return (ClosureExpression) node; } } } return null; } /** * Looks for method calls on the AstBuilder class called build that take * a Closure as parameter. This is all needed b/c build is overloaded. * * @param call the method call expression, may not be null */ private boolean isBuildInvocation(MethodCallExpression call) { if (call == null) throw new IllegalArgumentException("Null: call"); // is method name correct? if (call.getMethod() instanceof ConstantExpression && "buildFromCode".equals(((ConstantExpression) call.getMethod()).getValue())) { // is method object correct type? if (call.getObjectExpression() != null && call.getObjectExpression().getType() != null) { String name = call.getObjectExpression().getType().getName(); if (name != null && !"".equals(name) && factoryTargets.contains(name)) { // is one of the arguments a closure? if (call.getArguments() != null && call.getArguments() instanceof TupleExpression) { if (((TupleExpression) call.getArguments()).getExpressions() != null) { for (ASTNode node : ((TupleExpression) call.getArguments()).getExpressions()) { if (node instanceof ClosureExpression) { return true; } } } } } } } return false; } /** * Converts a ClosureExpression into the String source. * * @param expression a closure * @return the source the closure was created from */ private String convertClosureToSource(ClosureExpression expression) { if (expression == null) throw new IllegalArgumentException("Null: expression"); StringBuilder result = new StringBuilder(); for (int x = expression.getLineNumber(); x <= expression.getLastLineNumber(); x++) { String line = source.getLine(x, null); if (line == null) { addError( "Error calculating source code for expression. Trying to read line " + x + " from " + source.getClass(), expression ); } if (x == expression.getLastLineNumber()) { line = line.substring(0, expression.getLastColumnNumber() - 1); } if (x == expression.getLineNumber()) { line = line.substring(expression.getColumnNumber() - 1); } //restoring line breaks is important b/c of lack of semicolons result.append(line).append('\n'); } String source = result.toString().trim(); if (!source.startsWith("{")) { addError( "Error converting ClosureExpression into source code. Closures must start with {. Found: " + source, expression ); } return source; } } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.groovy0000644001501200150120000000000011715031256030453 0ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/AstSpecificationCompiler.groovy0000644001501200150120000010165011715031256030426 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.builder import groovy.transform.PackageScope import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.ast.AnnotationNode import org.codehaus.groovy.ast.ClassNode import org.codehaus.groovy.ast.ConstructorNode import org.codehaus.groovy.ast.DynamicVariable import org.codehaus.groovy.ast.FieldNode import org.codehaus.groovy.ast.GenericsType import org.codehaus.groovy.ast.ImportNode import org.codehaus.groovy.ast.InnerClassNode import org.codehaus.groovy.ast.MethodNode import org.codehaus.groovy.ast.MixinNode import org.codehaus.groovy.ast.Parameter import org.codehaus.groovy.ast.PropertyNode import org.codehaus.groovy.ast.VariableScope import org.codehaus.groovy.ast.expr.AnnotationConstantExpression import org.codehaus.groovy.ast.expr.ArgumentListExpression import org.codehaus.groovy.ast.expr.ArrayExpression import org.codehaus.groovy.ast.expr.AttributeExpression import org.codehaus.groovy.ast.expr.BinaryExpression import org.codehaus.groovy.ast.expr.BitwiseNegationExpression import org.codehaus.groovy.ast.expr.BooleanExpression import org.codehaus.groovy.ast.expr.CastExpression import org.codehaus.groovy.ast.expr.ClassExpression import org.codehaus.groovy.ast.expr.ClosureExpression import org.codehaus.groovy.ast.expr.ClosureListExpression import org.codehaus.groovy.ast.expr.ConstantExpression import org.codehaus.groovy.ast.expr.ConstructorCallExpression import org.codehaus.groovy.ast.expr.DeclarationExpression import org.codehaus.groovy.ast.expr.ElvisOperatorExpression import org.codehaus.groovy.ast.expr.Expression import org.codehaus.groovy.ast.expr.FieldExpression import org.codehaus.groovy.ast.expr.GStringExpression import org.codehaus.groovy.ast.expr.ListExpression import org.codehaus.groovy.ast.expr.MapEntryExpression import org.codehaus.groovy.ast.expr.MapExpression import org.codehaus.groovy.ast.expr.MethodCallExpression import org.codehaus.groovy.ast.expr.MethodPointerExpression import org.codehaus.groovy.ast.expr.NamedArgumentListExpression import org.codehaus.groovy.ast.expr.NotExpression import org.codehaus.groovy.ast.expr.PostfixExpression import org.codehaus.groovy.ast.expr.PrefixExpression import org.codehaus.groovy.ast.expr.PropertyExpression import org.codehaus.groovy.ast.expr.RangeExpression import org.codehaus.groovy.ast.expr.SpreadExpression import org.codehaus.groovy.ast.expr.SpreadMapExpression import org.codehaus.groovy.ast.expr.StaticMethodCallExpression import org.codehaus.groovy.ast.expr.TernaryExpression import org.codehaus.groovy.ast.expr.TupleExpression import org.codehaus.groovy.ast.expr.UnaryMinusExpression import org.codehaus.groovy.ast.expr.UnaryPlusExpression import org.codehaus.groovy.ast.expr.VariableExpression import org.codehaus.groovy.ast.stmt.AssertStatement import org.codehaus.groovy.ast.stmt.BlockStatement import org.codehaus.groovy.ast.stmt.BreakStatement import org.codehaus.groovy.ast.stmt.CaseStatement import org.codehaus.groovy.ast.stmt.CatchStatement import org.codehaus.groovy.ast.stmt.ContinueStatement import org.codehaus.groovy.ast.stmt.EmptyStatement import org.codehaus.groovy.ast.stmt.ExpressionStatement import org.codehaus.groovy.ast.stmt.ForStatement import org.codehaus.groovy.ast.stmt.IfStatement import org.codehaus.groovy.ast.stmt.ReturnStatement import org.codehaus.groovy.ast.stmt.SwitchStatement import org.codehaus.groovy.ast.stmt.SynchronizedStatement import org.codehaus.groovy.ast.stmt.ThrowStatement import org.codehaus.groovy.ast.stmt.TryCatchStatement import org.codehaus.groovy.ast.stmt.WhileStatement import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.runtime.MethodClosure import org.codehaus.groovy.syntax.Token import org.codehaus.groovy.syntax.Types import org.codehaus.groovy.ast.stmt.Statement import org.codehaus.groovy.ast.ClassHelper /** * Handles parsing the properties from the closure into values that can be referenced. * * This object is very stateful and not threadsafe. It accumulates expressions in the * 'expression' field as they are found and executed within the DSL. * * Note: this class consists of many one-line method calls. A better implementation * might be to take a declarative approach and replace the one-liners with map entries. * * @author Hamlet D'Arcy */ @PackageScope class AstSpecificationCompiler implements GroovyInterceptable { private boolean returnScriptBodyOnly = false private CompilePhase phase private String source private final List expression = [] /** * Creates the DSL compiler. */ AstSpecificationCompiler(Closure spec) { spec.delegate = this spec() } /** * Gets the current generated expression. */ List getExpression() { return expression } /** * This method takes a List of Classes (a "spec"), and makes sure that the expression field * contains those classes. It is a safety mechanism to enforce that the DSL is being called * properly. * * @param methodName * the name of the method within the DSL that is being invoked. Used in creating error messages. * @param spec * the list of Class objects that the method expects to have in the expression field when invoked. * @return * the portions of the expression field that adhere to the spec. */ private List enforceConstraints(String methodName, List spec) { // enforce that the correct # arguments was passed if (spec.size() != expression.size()) { throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression?.collect { it.class }}") } // enforce types and collect result (0..(spec.size() - 1)).collect { int it -> def actualClass = expression[it].class def expectedClass = spec[it] if (!expectedClass.isAssignableFrom(actualClass)) { throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression?.collect { it.class }}") } expression[it] } } /** * This method helps you take Closure parameters to a method and bundle them into * constructor calls to a specific ASTNode subtype. * @param name * name of object being constructed, used to create helpful error message. * @param argBlock * the actual parameters being specified for the node * @param constructorStatement * the type specific construction code that will be run */ private void captureAndCreateNode(String name, Closure argBlock, Closure constructorStatement) { if (!argBlock) throw new IllegalArgumentException("nodes of type $name require arguments to be specified") def oldProps = new ArrayList(expression) expression.clear() new AstSpecificationCompiler(argBlock) def result = constructorStatement(expression) // invoke custom constructor for node expression.clear() expression.addAll(oldProps) expression.add(result) } /** * Helper method to convert a DSL invocation into an ASTNode instance. * * @param target * the class you are going to create * @param typeAlias * the DSL keyword that was used to invoke this type * @param ctorArgs * a specification of what arguments the constructor expects * @param argBlock * the single closure argument used during invocation */ private void makeNode(Class target, String typeAlias, List> ctorArgs, Closure argBlock) { captureAndCreateNode(target.class.simpleName, argBlock) { target.newInstance( * enforceConstraints(typeAlias, ctorArgs) ) } } /** * Helper method to convert a DSL invocation with a list of parameters specified * in a Closure into an ASTNode instance. * * @param target * the class you are going to create * @param argBlock * the single closure argument used during invocation */ private void makeNodeFromList(Class target, Closure argBlock) { //todo: add better error handling? captureAndCreateNode(target.simpleName, argBlock) { target.newInstance(new ArrayList(expression)) } } /** * Helper method to convert a DSL invocation with a String parameter into a List of ASTNode instances. * * @param argBlock * the single closure argument used during invocation * @param input * the single String argument used during invocation */ private void makeListOfNodes(Closure argBlock, String input) { captureAndCreateNode(input, argBlock) { new ArrayList(expression) } } /** * Helper method to convert a DSL invocation with a String parameter into an Array of ASTNode instances. * * @param argBlock * the single closure argument used during invocation * @param target * the target type */ private void makeArrayOfNodes(Object target, Closure argBlock) { captureAndCreateNode(target.class.simpleName, argBlock) { expression.toArray(target) } } /** * Helper method to convert a DSL invocation into an ASTNode instance when a Class parameter is specified. * * @param target * the class you are going to create * @param alias * the DSL keyword that was used to invoke this type * @param spec * the list of Classes that you expect to be present as parameters * @param argBlock * the single closure argument used during invocation * @param type * a type parameter */ private void makeNodeWithClassParameter(Class target, String alias, List spec, Closure argBlock, Class type) { captureAndCreateNode(target.class.simpleName, argBlock) { expression.add(0, ClassHelper.make(type)) target.newInstance( * enforceConstraints(alias, spec) ) } } private void makeNodeWithStringParameter(Class target, String alias, List spec, Closure argBlock, String text) { captureAndCreateNode(target.class.simpleName, argBlock) { expression.add(0, text) target.newInstance( * enforceConstraints(alias, spec) ) } } /** * Creates a CastExpression. */ private void cast(Class type, Closure argBlock) { makeNodeWithClassParameter(CastExpression, 'cast', [ClassNode, Expression], argBlock, type) } /** * Creates an ConstructorCallExpression. */ private void constructorCall(Class type, Closure argBlock) { makeNodeWithClassParameter(ConstructorCallExpression, 'constructorCall', [ClassNode, Expression], argBlock, type) } /** * Creates a MethodCallExpression. */ private void methodCall(Closure argBlock) { makeNode(MethodCallExpression, 'methodCall', [Expression, Expression, Expression], argBlock) } /** * Creates an AnnotationConstantExpression. */ private void annotationConstant(Closure argBlock) { makeNode(AnnotationConstantExpression, 'annotationConstant', [AnnotationNode], argBlock) } /** * Creates a PostfixExpression. */ private void postfix(Closure argBlock) { makeNode(PostfixExpression, 'postfix', [Expression, Token], argBlock) } /** * Creates a FieldExpression. */ private void field(Closure argBlock) { makeNode(FieldExpression, 'field', [FieldNode], argBlock) } /** * Creates a MapExpression. */ private void map(Closure argBlock) { makeNodeFromList(MapExpression, argBlock) } /** * Creates a TupleExpression. */ private void tuple(Closure argBlock) { makeNodeFromList(TupleExpression, argBlock) } /** * Creates a MapEntryExpression. */ private void mapEntry(Closure argBlock) { makeNode(MapEntryExpression, 'mapEntry', [Expression, Expression], argBlock) } /** * Creates a gString. */ private void gString(String verbatimText, Closure argBlock) { makeNodeWithStringParameter(GStringExpression, 'gString', [String, List, List], argBlock, verbatimText) } /** * Creates a methodPointer. */ private void methodPointer(Closure argBlock) { makeNode(MethodPointerExpression, 'methodPointer', [Expression, Expression], argBlock) } /** * Creates a property. */ private void property(Closure argBlock) { makeNode(PropertyExpression, 'property', [Expression, Expression], argBlock) } /** * Creates a RangeExpression. */ private void range(Closure argBlock) { makeNode(RangeExpression, 'range', [Expression, Expression, Boolean], argBlock) } /** * Creates EmptyStatement. */ private void empty() { expression << new EmptyStatement() } /** * Creates a label. */ private void label(String label) { expression << label } /** * Creates an ImportNode. */ private void importNode(Class target, String alias = null) { expression << new ImportNode(ClassHelper.make(target), alias) } /** * Creates a CatchStatement. */ private void catchStatement(Closure argBlock) { makeNode(CatchStatement, 'catchStatement', [Parameter, Statement], argBlock) } /** * Creates a ThrowStatement. */ private void throwStatement(Closure argBlock) { makeNode(ThrowStatement, 'throwStatement', [Expression], argBlock) } /** * Creates a SynchronizedStatement. */ private void synchronizedStatement(Closure argBlock) { makeNode(SynchronizedStatement, 'synchronizedStatement', [Expression, Statement], argBlock) } /** * Creates a ReturnStatement. */ private void returnStatement(Closure argBlock) { makeNode(ReturnStatement, 'returnStatement', [Expression], argBlock) } /** * Creates a TernaryExpression. */ private void ternary(Closure argBlock) { makeNode(TernaryExpression, 'ternary', [BooleanExpression, Expression, Expression], argBlock) } /** * Creates an ElvisOperatorExpression. */ private void elvisOperator(Closure argBlock) { makeNode(ElvisOperatorExpression, 'elvisOperator', [Expression, Expression], argBlock) } /** * Creates a BreakStatement. */ private void breakStatement(String label = null) { if (label) { expression << new BreakStatement(label) } else { expression << new BreakStatement() } } /** * Creates a ContinueStatement. */ private void continueStatement(Closure argBlock = null) { if (!argBlock) { expression << new ContinueStatement() } else { makeNode(ContinueStatement, 'continueStatement', [String], argBlock) } } /** * Create a CaseStatement. */ private void caseStatement(Closure argBlock) { makeNode(CaseStatement, 'caseStatement', [Expression, Statement], argBlock) } /** * Creates a BlockStatement. */ private void defaultCase(Closure argBlock) { block(argBlock) // same as arg block } /** * Creates a PrefixExpression. */ private void prefix(Closure argBlock) { makeNode(PrefixExpression, 'prefix', [Token, Expression], argBlock) } /** * Creates a NotExpression. */ private void not(Closure argBlock) { makeNode(NotExpression, 'not', [Expression], argBlock) } /** * Creates a DynamicVariable. */ private void dynamicVariable(String variable, boolean isStatic = false) { expression << new DynamicVariable(variable, isStatic) } /** * Creates a ClassNode[]. */ private void exceptions(Closure argBlock) { makeArrayOfNodes([] as ClassNode[], argBlock) } /** * Designates a list of AnnotationNodes. */ private void annotations(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Designates a list of ConstantExpressions. */ private void strings(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Designates a list of Expressions. */ private void values(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Creates a boolean value. */ private void inclusive(boolean value) { expression << value } /** * Creates a ConstantExpression. */ private void constant(Object value) { expression << new ConstantExpression(value) } /** * Creates an IfStatement. */ private void ifStatement(Closure argBlock) { makeNode(IfStatement, 'ifStatement', [BooleanExpression, Statement, Statement], argBlock) } /** * Creates a SpreadExpression. */ private void spread(Closure argBlock) { makeNode(SpreadExpression, 'spread', [Expression], argBlock) } /** * Creates a SpreadMapExpression. */ private void spreadMap(Closure argBlock) { makeNode(SpreadMapExpression, 'spreadMap', [Expression], argBlock) } /** * Creates a WhileStatement. */ private void whileStatement(Closure argBlock) { makeNode(WhileStatement, 'whileStatement', [BooleanExpression, Statement], argBlock) } /** * Create a ForStatement. */ private void forStatement(Closure argBlock) { makeNode(ForStatement, 'forStatement', [Parameter, Expression, Statement], argBlock) } /** * Creates a ClosureListExpression. */ private void closureList(Closure argBlock) { makeNodeFromList(ClosureListExpression, argBlock) } /** * Creates a DeclarationExpression. */ private void declaration(Closure argBlock) { makeNode(DeclarationExpression, 'declaration', [Expression, Token, Expression], argBlock) } /** * Creates a ListExpression. */ private void list(Closure argBlock) { makeNodeFromList(ListExpression, argBlock) } /** * Creates a BitwiseNegationExpression. */ private void bitwiseNegation(Closure argBlock) { makeNode(BitwiseNegationExpression, 'bitwiseNegation', [Expression], argBlock) } /** * Creates a ClosureExpression. */ private void closure(Closure argBlock) { makeNode(ClosureExpression, 'closure', [Parameter[], Statement], argBlock) } /** * Creates a BooleanExpression. */ private void booleanExpression(Closure argBlock) { makeNode(BooleanExpression, 'booleanExpression', [Expression], argBlock) } /** * Creates a BinaryExpression. */ private void binary(Closure argBlock) { makeNode(BinaryExpression, 'binary', [Expression, Token, Expression], argBlock) } /** * Creates a UnaryPlusExpression. */ private void unaryPlus(Closure argBlock) { makeNode(UnaryPlusExpression, 'unaryPlus', [Expression], argBlock) } /** * Creates a ClassExpression. */ private void classExpression(Class type) { expression << new ClassExpression(ClassHelper.make(type)) } /** * Creates a UnaryMinusExpression */ private void unaryMinus(Closure argBlock) { makeNode(UnaryMinusExpression, 'unaryMinus', [Expression], argBlock) } /** * Creates an AttributeExpression. */ private void attribute(Closure argBlock) { makeNode(AttributeExpression, 'attribute', [Expression, Expression], argBlock) } /** * Creates an ExpressionStatement. */ private void expression(Closure argBlock) { makeNode(ExpressionStatement, 'expression', [Expression], argBlock) } /** * Creates a NamedArgumentListExpression. */ private void namedArgumentList(Closure argBlock) { makeNodeFromList(NamedArgumentListExpression, argBlock) } /** * Creates a ClassNode[]. */ private void interfaces(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Creates a MixinNode[]. */ private void mixins(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Creates a GenericsTypes[]. */ private void genericsTypes(Closure argBlock) { makeListOfNodes(argBlock, "List") } /** * Creates a ClassNode. */ private void classNode(Class target) { expression << ClassHelper.make(target, false) } /** * Creates a Parameter[]. */ private void parameters(Closure argBlock) { makeArrayOfNodes([] as Parameter[], argBlock) } /** * Creates a BlockStatement. */ private void block(Closure argBlock) { captureAndCreateNode("BlockStatement", argBlock) { return new BlockStatement(new ArrayList(expression), new VariableScope()) } } /** * Creates a Parameter. */ private void parameter(Map args, Closure argBlock = null) { if (!args) throw new IllegalArgumentException() if (args.size() > 1) throw new IllegalArgumentException() //todo: add better error handling? if (argBlock) { args.each {name, type -> captureAndCreateNode("Parameter", argBlock) { new Parameter(ClassHelper.make(type), name, expression[0]) } } } else { args.each {name, type -> expression << (new Parameter(ClassHelper.make(type), name)) } } } /** * Creates an ArrayExpression. */ private void array(Class type, Closure argBlock) { captureAndCreateNode("ArrayExpression", argBlock) { new ArrayExpression(ClassHelper.make(type), new ArrayList(expression)) } } /** * Creates a GenericsType. */ private void genericsType(Class type, Closure argBlock = null) { if (argBlock) { captureAndCreateNode("GenericsType", argBlock) { new GenericsType(ClassHelper.make(type), expression[0] as ClassNode[], expression[1]) } } else { expression << new GenericsType(ClassHelper.make(type)) } } /** * Creates a list of ClassNodes. */ private void upperBound(Closure argBlock) { makeListOfNodes(argBlock, 'List') } /** * Creates a list of ClassNodes. */ private void lowerBound(Class target) { expression << ClassHelper.make(target) } /** * Creates a 2 element list of name and Annotation. Used with Annotation Members. */ private void member(String name, Closure argBlock) { captureAndCreateNode("Annotation Member", argBlock) { [name, expression[0]] } } /** * Creates an ArgumentListExpression. */ private void argumentList(Closure argBlock) { if (!argBlock) { expression << new ArgumentListExpression() } else { makeNodeFromList(ArgumentListExpression, argBlock) } } /** * Creates an AnnotationNode. */ private void annotation(Class target, Closure argBlock = null) { if (argBlock) { //todo: add better error handling captureAndCreateNode("ArgumentListExpression", argBlock) { def node = new AnnotationNode(ClassHelper.make(target)) expression?.each { node.addMember(it[0], it[1]) } node } } else { expression << new AnnotationNode(ClassHelper.make(target)) } } /** * Creates a MixinNode. */ private void mixin(String name, int modifiers, Closure argBlock) { captureAndCreateNode("AttributeExpression", argBlock) { if (expression.size() > 1) { new MixinNode(name, modifiers, expression[0], new ArrayList(expression[1]) as ClassNode[]) } else { new MixinNode(name, modifiers, expression[0]) } } } /** * Creates a ClassNode */ private void classNode(String name, int modifiers, Closure argBlock) { captureAndCreateNode("ClassNode", argBlock) { def result = new ClassNode(name, modifiers, expression[0], new ArrayList(expression[1]) as ClassNode[], new ArrayList(expression[2]) as MixinNode[] ) if (expression[3]) { result.setGenericsTypes(new ArrayList(expression[3]) as GenericsType[]) } result } } /** * Creates an AssertStatement. */ private void assertStatement(Closure argBlock) { captureAndCreateNode("AssertStatement", argBlock) { if (expression.size() < 2) { new AssertStatement( * enforceConstraints('assertStatement', [BooleanExpression]) ) } else { new AssertStatement( * enforceConstraints('assertStatement', [BooleanExpression, Expression]) ) } } } /** * Creates a TryCatchStatement. */ private void tryCatch(Closure argBlock) { captureAndCreateNode("TryCatchStatement", argBlock) { def result = new TryCatchStatement(expression[0], expression[1]) def catchStatements = expression.tail().tail() catchStatements.each {statement -> result.addCatch(statement) } return result } } /** * Creates a VariableExpression. */ private void variable(String variable) { expression << new VariableExpression(variable) } /** * Creates a MethodNode. */ private void method(String name, int modifiers, Class returnType, Closure argBlock) { captureAndCreateNode("MethodNode", argBlock) { //todo: enforce contract def result = new MethodNode( name, modifiers, ClassHelper.make(returnType), expression[0], expression[1], expression[2] ) if (expression[3]) { def annotations = expression[3] result.addAnnotations(new ArrayList(annotations)) } result } } /** * Creates a token. */ private void token(String value) { if (value == null) throw new IllegalArgumentException("Null: value") def tokenID = Types.lookupKeyword(value) if (tokenID == Types.UNKNOWN) { tokenID = Types.lookupSymbol(value) } if (tokenID == Types.UNKNOWN) throw new IllegalArgumentException("could not find token for $value") expression << new Token(tokenID, value, -1, -1) } /** * Creates a RangeExpression. */ private void range(Range range) { if (range == null) throw new IllegalArgumentException('Null: range') expression << new RangeExpression( new ConstantExpression(range.getFrom()), new ConstantExpression(range.getTo()), true) //default is inclusive } /** * Creates a SwitchStatement. */ private void switchStatement(Closure argBlock) { captureAndCreateNode("SwitchStatement", argBlock) { def switchExpression = expression.head() def caseStatements = expression.tail().tail() def defaultExpression = expression.tail().head() new SwitchStatement(switchExpression, caseStatements, defaultExpression) } } /** * Creates a mapEntry. */ private void mapEntry(Map map) { map.entrySet().each { expression << new MapEntryExpression( new ConstantExpression(it.key), new ConstantExpression(it.value)) } } // // todo: these methods can still be reduced smaller // /** * Creates a FieldNode. */ private void fieldNode(String name, int modifiers, Class type, Class owner, Closure argBlock) { captureAndCreateNode("FieldNode", argBlock) { expression.add(0, ClassHelper.make(owner)) expression.add(0, ClassHelper.make(type)) expression.add(0, modifiers) expression.add(0, name) new FieldNode( * enforceConstraints('fieldNode', [String, Integer, ClassNode, ClassNode, Expression])) } } /** * Creates a property. */ private void innerClass(String name, int modifiers, Closure argBlock) { captureAndCreateNode("InnerClassNode", argBlock) { //todo: enforce contract new InnerClassNode( expression[0], name, modifiers, expression[1], new ArrayList(expression[2]) as ClassNode[], new ArrayList(expression[3]) as MixinNode[]) } } /** * Creates a PropertyNode. */ private void propertyNode(String name, int modifiers, Class type, Class owner, Closure argBlock) { //todo: improve error handling? captureAndCreateNode("PropertyNode", argBlock) { new PropertyNode(name, modifiers, ClassHelper.make(type), ClassHelper.make(owner), expression[0], // initial value expression[1], // getter block expression[2]) // setter block } } /** * Creates a StaticMethodCallExpression. */ private void staticMethodCall(Class target, String name, Closure argBlock) { captureAndCreateNode("StaticMethodCallExpression", argBlock) { expression.add(0, name) expression.add(0, ClassHelper.make(target)) new StaticMethodCallExpression( * enforceConstraints('staticMethodCall', [ClassNode, String, Expression]) ) } } /** * Creates a StaticMethodCallExpression. */ private void staticMethodCall(MethodClosure target, Closure argBlock) { captureAndCreateNode("StaticMethodCallExpression", argBlock) { expression.add(0, target.method) expression.add(0, ClassHelper.makeWithoutCaching(target.owner.class, false)) new StaticMethodCallExpression( * enforceConstraints('staticMethodCall', [ClassNode, String, Expression]) ) } } /** * Creates a ConstructorNode. */ private void constructor(int modifiers, Closure argBlock) { captureAndCreateNode("ConstructorNode", argBlock) { expression.add(0, modifiers) new ConstructorNode( * enforceConstraints('constructor', [Integer, Parameter[], ClassNode[], Statement]) ) } } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/AstBuilder.groovy0000644001501200150120000001556711707612044025555 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.builder import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.ast.stmt.BlockStatement /** * The AstBuilder provides several ways to build an abstract syntax tree (AST) of Groovy code. * * You can convert a String into AST using the buildFromString method. * You can convert code into AST using the buildFromCode method. * You can use the AST DSL with the buildFromSpec method. * * For more information, see the resources on the Groovy wiki pages. * * @author Hamlet D'Arcy */ public class AstBuilder { /** * Builds AST based on the code within the {@link Closure} parameter. * * This method must be invoked at compile time and never at runtime, because * an ASTTransformation must be run to support it. If you receive an IllegalStateException then * you most likely need to add stronger typing. For instance, this will not work: * * def builder = new AstBuilder() * builder.buildFromCode { * // some code * } * * While this code will: * * new AstBuilder().buildFromCode { * // some code * } * * * The compiler rewrites buildFromCode invocations into {@link AstBuilder#buildFromString(CompilePhase, boolean, String)} * invocations. An exception raised during AST generation will show a stack trace from {@link AstBuilder#buildFromString(CompilePhase, boolean, String)} * and not from {@link AstBuilder#buildFromCode(CompilePhase, boolean, Closure)} . * * The compiler saves the source code of the closure as a String within the Java class file. The String source * of the closure will be visible and un-obfuscated within the class file. If your Closure parameter contains * sensitive data such as a hard-coded password then that data is free to be seen by anyone with the class file. * Do not store sensitive data within the closure parameter. * * @param phase * the {@link CompilePhase} the AST will be targeted towards. Default is {@link CompilePhase#CLASS_GENERATION} * @param statementsOnly * when true, only the script statements are returned. WHen false, you will * receive back a Script class node also. Default is true. * @param block * the code that will be converted * @returns a List of {@link ASTNode} . * @throws IllegalStateException * this method may not be invoked at runtime. It works via a compile-time transformation * of the closure source code into a String, which is sent to the {@link AstBuilder#buildFromString(CompilePhase, boolean, String)} * method. The buildFromCode() method must be invoked against a strongly typed AstBuilder. */ List buildFromCode(CompilePhase phase = CompilePhase.CLASS_GENERATION, boolean statementsOnly = true, Closure block) { throw new IllegalStateException("""AstBuilder.build(CompilePhase, boolean, Closure):List should never be called at runtime. Are you sure you are using it correctly? """) } /** * Builds AST based on the code within the String parameter. * * @param phase * the {@link CompilePhase} the AST will be targeted towards. Default is {@link CompilePhase#CLASS_GENERATION} * @param statementsOnly * when true, only the script statements are returned. WHen false, you will * receive back a Script class node also. Default is true. * @param source * The source code String that will be compiled. * @returns a List of {@link ASTNode} . * @throws IllegalArgumentException * if source is null or empty */ List buildFromString(CompilePhase phase = CompilePhase.CLASS_GENERATION, boolean statementsOnly = true, String source) { if (!source || "" == source.trim()) throw new IllegalArgumentException("A source must be specified") return new AstStringCompiler().compile(source, phase, statementsOnly); } /** * Builds AST based on the code within the String parameter. The parameter is assumed to be * a code block which is not legal Groovy code. A goto label is affixed to the block, compiled, * and the resulting BlockStatement wrapper is removed before returning a result. * @param phase * the {@link CompilePhase} the AST will be targeted towards. Default is {@link CompilePhase#CLASS_GENERATION} * @param statementsOnly * when true, only the script statements are returned. WHen false, you will * receive back a Script class node also. Default is true. * @param source * The source code String that will be compiled. The string must be a block wrapped in curly braces. * @returns a List of {@link ASTNode} . * @throws IllegalArgumentException * if source is null or empty */ private List buildFromBlock(CompilePhase phase = CompilePhase.CLASS_GENERATION, boolean statementsOnly = true, String source) { if (!source || "" == source.trim()) throw new IllegalArgumentException("A source must be specified") def labelledSource = "__synthesized__label__${System.currentTimeMillis()}__:" + source List result = new AstStringCompiler().compile(labelledSource, phase, statementsOnly) // find the block statement from the result, and unwrap it from one level. result.collect { node -> if (node instanceof BlockStatement) { ((BlockStatement)node).statements[0] //unwrap the artifact of pre-pending the goto label } else { node } } } /** * Builds AST based on the DSL data within the Closure parameter. * @param specification * the contents to create */ List buildFromSpec(Closure specification) { if (specification == null) throw new IllegalArgumentException('Null: specification') def properties = new AstSpecificationCompiler(specification) return properties.expression } }groovy-1.8.6/src/main/org/codehaus/groovy/ast/builder/AstStringCompiler.groovy0000644001501200150120000000453611707612044027122 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.builder import groovy.transform.PackageScope import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.ast.ModuleNode import org.codehaus.groovy.control.CompilerConfiguration /** * This class handles converting Strings to ASTNode lists. * * @author Hamlet D'Arcy */ @PackageScope class AstStringCompiler { /** * Performs the String source to {@link List} of {@link ASTNode}. * * @param script * a Groovy script in String form * @param compilePhase * the int based CompilePhase to compile it to. * @param statementsOnly */ List compile(String script, CompilePhase compilePhase, boolean statementsOnly) { def scriptClassName = "script" + System.currentTimeMillis() GroovyClassLoader classLoader = new GroovyClassLoader() GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptClassName + ".groovy", "/groovy/script") CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.codeSource, classLoader) cu.addSource(codeSource.getName(), script); cu.compile(compilePhase.getPhaseNumber()) // collect all the ASTNodes into the result, possibly ignoring the script body if desired return cu.ast.modules.inject([]) {List acc, ModuleNode node -> if (node.statementBlock) acc.add(node.statementBlock) node.classes?.each { if (!(it.name == scriptClassName && statementsOnly)) { acc << it } } acc } } }groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/0000755001501200150120000000000011707612044021573 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/BlockStatement.java0000644001501200150120000000660111707612044025360 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.VariableScope; /** * A list of statements and a scope. * * @author James Strachan * @version $Revision$ */ public class BlockStatement extends Statement { private List statements = new ArrayList(); private VariableScope scope; public BlockStatement() { this(new ArrayList(), new VariableScope()); } /** * Creates a BlockStatement with a scope and children statements. * @param statements * the statements. Do not pass null. If you do, no exception will occur, * but a NullPointerException will eventually occur later. Also, a reference * to the list is kept, so modifying the List later does effect this class. * @param scope * the scope */ public BlockStatement(List statements, VariableScope scope) { this.statements = statements; this.scope = scope; } /** * Creates a BlockStatement with a scope and children statements. * @param statements * the statements, which cannot be null or an exception occurs. No reference * to the array is held, so modifying the array later has no effect on this * class. * @param scope * the scope */ public BlockStatement(Statement[] statements, VariableScope scope) { this.statements.addAll(Arrays.asList(statements)); this.scope = scope; } public void visit(GroovyCodeVisitor visitor) { visitor.visitBlockStatement(this); } public List getStatements() { return statements; } public void addStatement(Statement statement) { statements.add(statement); } public void addStatements(List listOfStatements) { statements.addAll(listOfStatements); } public String toString() { return super.toString() + statements; } public String getText() { StringBuffer buffer = new StringBuffer("{ "); boolean first = true; for (Statement statement : statements) { if (first) { first = false; } else { buffer.append("; "); } buffer.append(statement.getText()); } buffer.append(" }"); return buffer.toString(); } public boolean isEmpty() { return statements.isEmpty(); } public void setVariableScope(VariableScope scope) { this.scope = scope; } public VariableScope getVariableScope() { return scope; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/Statement.java0000644001501200150120000000227711627206700024411 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.ASTNode; /** * Base class for any statement * * @author James Strachan * @version $Revision$ */ public class Statement extends ASTNode { private String statementLabel; public Statement() { statementLabel = null; } public String getStatementLabel() { return statementLabel; } public void setStatementLabel( String label ) { statementLabel = label; } public boolean isEmpty() { return false; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/ContinueStatement.java0000644001501200150120000000236511627206700026114 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a continue statement in a loop statement * * @author James Strachan * @version $Revision$ */ public class ContinueStatement extends Statement { private String label; public ContinueStatement() { this(null); } public ContinueStatement(String label) { this.label = label; } public String getLabel() { return label; } public void visit(GroovyCodeVisitor visitor) { visitor.visitContinueStatement(this); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/ReturnStatement.java0000644001501200150120000000406511627206700025606 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; /** * A return statement * * @author James Strachan * @version $Revision$ */ public class ReturnStatement extends Statement { /** * Only used for synthetic return statements emitted by the compiler. * For comparisons use isReturningNullOrVoid() instead. */ public static final ReturnStatement RETURN_NULL_OR_VOID = new ReturnStatement(ConstantExpression.NULL); private Expression expression; public ReturnStatement(ExpressionStatement statement) { this(statement.getExpression()); setStatementLabel(statement.getStatementLabel()); } public ReturnStatement(Expression expression) { this.expression = expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitReturnStatement(this); } public Expression getExpression() { return expression; } public String getText() { return "return " + expression.getText(); } public void setExpression(Expression expression) { this.expression = expression; } public boolean isReturningNullOrVoid() { return expression instanceof ConstantExpression && ((ConstantExpression)expression).isNullExpression(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/package.html0000644001501200150120000000023211627206700024050 0ustar miguelmiguel package org.codehaus.groovy.ast.stmt.*

    AST nodes for Groovy statements

    groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/CaseStatement.java0000644001501200150120000000324211627206700025176 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; /** * Represents a case statement in a switch statement * * @author James Strachan * @version $Revision$ */ public class CaseStatement extends Statement { private Statement code; private Expression expression; public CaseStatement(Expression expression, Statement code) { this.expression = expression; this.code = code; } public Statement getCode() { return code; } public void setCode(Statement code) { this.code = code; } public Expression getExpression() { return expression; } public void setExpression(Expression e) { expression=e; } public void visit(GroovyCodeVisitor visitor) { visitor.visitCaseStatement(this); } public String toString() { return super.toString() + "[expression: " + expression + "; code: " + code + "]"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/AssertStatement.java0000644001501200150120000000411211627206700025561 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; /** * Represents an assert statement such as * * assert i != 0 : "should never be zero"; * * * @author James Strachan * @version $Revision$ */ public class AssertStatement extends Statement { private BooleanExpression booleanExpression; private Expression messageExpression; public AssertStatement(BooleanExpression booleanExpression) { this(booleanExpression, ConstantExpression.NULL); } public AssertStatement(BooleanExpression booleanExpression, Expression messageExpression) { this.booleanExpression = booleanExpression; this.messageExpression = messageExpression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitAssertStatement(this); } public Expression getMessageExpression() { return messageExpression; } public BooleanExpression getBooleanExpression() { return booleanExpression; } public void setBooleanExpression(BooleanExpression booleanExpression) { this.booleanExpression = booleanExpression; } public void setMessageExpression(Expression messageExpression) { this.messageExpression = messageExpression; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/SynchronizedStatement.java0000644001501200150120000000310511627206700027000 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; /** * Represents a synchronized statement * * @author James Strachan * @version $Revision$ */ public class SynchronizedStatement extends Statement { private Statement code; private Expression expression; public SynchronizedStatement(Expression expression, Statement code) { this.expression = expression; this.code = code; } public Statement getCode() { return code; } public void setCode(Statement statement) { code = statement; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitSynchronizedStatement(this); } public void setExpression(Expression expression) { this.expression = expression; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/SwitchStatement.java0000644001501200150120000000521411627206700025565 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; /** * Represents a switch (object) { case value: ... case [1, 2, 3]: ... default: ... } statement in Groovy. * * @author James Strachan * @version $Revision$ */ public class SwitchStatement extends Statement { private Expression expression; private List caseStatements = new ArrayList(); private Statement defaultStatement; public SwitchStatement(Expression expression) { this(expression, EmptyStatement.INSTANCE); } public SwitchStatement(Expression expression, Statement defaultStatement) { this.expression = expression; this.defaultStatement = defaultStatement; } public SwitchStatement(Expression expression, List caseStatements, Statement defaultStatement) { this.expression = expression; this.caseStatements = caseStatements; this.defaultStatement = defaultStatement; } public void visit(GroovyCodeVisitor visitor) { visitor.visitSwitch(this); } public List getCaseStatements() { return caseStatements; } public Expression getExpression() { return expression; } public void setExpression(Expression e) { expression=e; } public Statement getDefaultStatement() { return defaultStatement; } public void setDefaultStatement(Statement defaultStatement) { this.defaultStatement = defaultStatement; } public void addCase(CaseStatement caseStatement) { caseStatements.add(caseStatement); } /** * @return the case statement of the given index or null */ public CaseStatement getCaseStatement(int idx) { if (idx >= 0 && idx < caseStatements.size()) { return caseStatements.get(idx); } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/ExpressionStatement.java0000644001501200150120000000326111627206700026463 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; /** * A simple statement such as a method call where the return value is ignored * * @author James Strachan * @version $Revision$ */ public class ExpressionStatement extends Statement { private Expression expression; public ExpressionStatement(Expression expression) { if (expression == null) { throw new IllegalArgumentException("expression cannot be null"); } this.expression = expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitExpressionStatement(this); } public Expression getExpression() { return expression; } public void setExpression(Expression expression) { this.expression = expression; } public String getText() { return this.toString(); } public String toString() { return super.toString() + "[expression:" + expression + "]"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/WhileStatement.java0000644001501200150120000000334311707612044025376 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.BooleanExpression; /** * Represents a while (condition) { ... } loop in Groovy * * @author James Strachan * @version $Revision$ */ public class WhileStatement extends Statement implements LoopingStatement { private BooleanExpression booleanExpression; private Statement loopBlock; public WhileStatement(BooleanExpression booleanExpression, Statement loopBlock) { this.booleanExpression = booleanExpression; this.loopBlock = loopBlock; } public void visit(GroovyCodeVisitor visitor) { visitor.visitWhileLoop(this); } public BooleanExpression getBooleanExpression() { return booleanExpression; } public Statement getLoopBlock() { return loopBlock; } public void setBooleanExpression(BooleanExpression booleanExpression) { this.booleanExpression = booleanExpression; } public void setLoopBlock(Statement loopBlock) { this.loopBlock = loopBlock; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/LoopingStatement.java0000644001501200150120000000217611707612044025740 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; /** * This is an AST Node that provides some sort of looping mechanism. Typically * in the form of a block that will be executed repeatedly. * DoWhileStatements, WhileStatements, and ForStatements are all examples of LoopingStatements. * * @author Hamlet D'Arcy */ public interface LoopingStatement { /** * Gets the loop block. */ public Statement getLoopBlock(); /** * Sets the loop block. */ public void setLoopBlock(Statement loopBlock); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/DoWhileStatement.java0000644001501200150120000000337011707612044025661 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.BooleanExpression; /** * Represents a do { ... } while (condition) loop in Groovy * * @author James Strachan * @version $Revision$ */ public class DoWhileStatement extends Statement implements LoopingStatement { private BooleanExpression booleanExpression; private Statement loopBlock; public DoWhileStatement(BooleanExpression booleanExpression, Statement loopBlock) { this.booleanExpression = booleanExpression; this.loopBlock = loopBlock; } public void visit(GroovyCodeVisitor visitor) { visitor.visitDoWhileLoop(this); } public BooleanExpression getBooleanExpression() { return booleanExpression; } public Statement getLoopBlock() { return loopBlock; } public void setBooleanExpression(BooleanExpression booleanExpression) { this.booleanExpression = booleanExpression; } public void setLoopBlock(Statement loopBlock) { this.loopBlock = loopBlock; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/TryCatchStatement.java0000644001501200150120000000462111627206700026046 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a try { ... } catch () finally {} statement in Groovy * * @author James Strachan * @version $Revision$ */ public class TryCatchStatement extends Statement { private Statement tryStatement; private List catchStatements = new ArrayList(); private Statement finallyStatement; public TryCatchStatement(Statement tryStatement, Statement finallyStatement) { this.tryStatement = tryStatement; this.finallyStatement = finallyStatement; } public void visit(GroovyCodeVisitor visitor) { visitor.visitTryCatchFinally(this); } public List getCatchStatements() { return catchStatements; } public Statement getFinallyStatement() { return finallyStatement; } public Statement getTryStatement() { return tryStatement; } public void addCatch(CatchStatement catchStatement) { catchStatements.add(catchStatement); } /** * @return the catch statement of the given index or null */ public CatchStatement getCatchStatement(int idx) { if (idx >= 0 && idx < catchStatements.size()) { return catchStatements.get(idx); } return null; } public void setTryStatement(Statement tryStatement) { this.tryStatement = tryStatement; } public void setCatchStatement(int idx, CatchStatement catchStatement) { catchStatements.set(idx, catchStatement); } public void setFinallyStatement(Statement finallyStatement) { this.finallyStatement = finallyStatement; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/ThrowStatement.java0000644001501200150120000000252211627206700025426 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; /** * Represents a throw statement * * @author James Strachan * @version $Revision$ */ public class ThrowStatement extends Statement { private Expression expression; public ThrowStatement(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitThrowStatement(this); } public void setExpression(Expression expression) { this.expression = expression; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/CatchStatement.java0000644001501200150120000000307711627206700025353 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Parameter; /** * Represents a catch (Exception var) { } statement * * @author James Strachan * @version $Revision$ */ public class CatchStatement extends Statement { private Parameter variable; private Statement code; public CatchStatement(Parameter variable, Statement code) { this.variable = variable; this.code = code; } public void visit(GroovyCodeVisitor visitor) { visitor.visitCatchStatement(this); } public Statement getCode() { return code; } public ClassNode getExceptionType() { return variable.getType(); } public Parameter getVariable() { return variable; } public void setCode(Statement code) { this.code = code; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/IfStatement.java0000644001501200150120000000370511627206700024665 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.BooleanExpression; /** * Represents an if (condition) { ... } else { ... } statement in Groovy * * @author James Strachan * @version $Revision$ */ public class IfStatement extends Statement { private BooleanExpression booleanExpression; private Statement ifBlock; private Statement elseBlock; public IfStatement(BooleanExpression booleanExpression, Statement ifBlock, Statement elseBlock) { this.booleanExpression = booleanExpression; this.ifBlock = ifBlock; this.elseBlock = elseBlock; } public void visit(GroovyCodeVisitor visitor) { visitor.visitIfElse(this); } public BooleanExpression getBooleanExpression() { return booleanExpression; } public Statement getIfBlock() { return ifBlock; } public Statement getElseBlock() { return elseBlock; } public void setBooleanExpression(BooleanExpression booleanExpression) { this.booleanExpression = booleanExpression; } public void setIfBlock(Statement statement) { ifBlock = statement; } public void setElseBlock(Statement statement) { elseBlock = statement; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/ForStatement.java0000644001501200150120000000471111707612044025054 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.VariableScope; import org.codehaus.groovy.ast.expr.Expression; /** * Represents a standard for loop in Groovy * * @author James Strachan * @version $Revision$ */ public class ForStatement extends Statement implements LoopingStatement { public static final Parameter FOR_LOOP_DUMMY = new Parameter(ClassHelper.OBJECT_TYPE,"forLoopDummyParameter"); private Parameter variable; private Expression collectionExpression; private Statement loopBlock; private VariableScope scope; public ForStatement(Parameter variable, Expression collectionExpression, Statement loopBlock) { this.variable = variable; this.collectionExpression = collectionExpression; this.loopBlock = loopBlock; } public void visit(GroovyCodeVisitor visitor) { visitor.visitForLoop(this); } public Expression getCollectionExpression() { return collectionExpression; } public Statement getLoopBlock() { return loopBlock; } public Parameter getVariable() { return variable; } public ClassNode getVariableType() { return variable.getType(); } public void setCollectionExpression(Expression collectionExpression) { this.collectionExpression = collectionExpression; } public void setVariableScope(VariableScope variableScope) { scope = variableScope; } public VariableScope getVariableScope() { return scope; } public void setLoopBlock(Statement loopBlock) { this.loopBlock = loopBlock; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/BreakStatement.java0000644001501200150120000000236011627206700025347 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a break statement in a switch or loop statement * * @author James Strachan * @version $Revision$ */ public class BreakStatement extends Statement { private String label; public BreakStatement() { this(null); } public BreakStatement(String label) { this.label = label; } public String getLabel() { return label; } public void visit(GroovyCodeVisitor visitor) { visitor.visitBreakStatement(this); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/stmt/EmptyStatement.java0000644001501200150120000000210711627206700025420 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents an empty statement * * @author James Strachan * @version $Revision$ */ public class EmptyStatement extends Statement { public static final EmptyStatement INSTANCE = new EmptyStatement(); public void visit(GroovyCodeVisitor visitor) { } public boolean isEmpty() { return true; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/InterfaceHelperClassNode.java0000644001501200150120000000332611707612044026307 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.ArrayList; import java.util.List; /** * Represents an inner class defined as helper for an interface * * @author Roshan Dawrani */ public class InterfaceHelperClassNode extends InnerClassNode { private List callSites = new ArrayList(); /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superClass the base class name - use "java.lang.Object" if no direct base class * @param callSites list of callsites used in the interface */ public InterfaceHelperClassNode(ClassNode outerClass, String name, int modifiers, ClassNode superClass, List callSites) { super(outerClass, name, modifiers, superClass, ClassHelper.EMPTY_TYPE_ARRAY, MixinNode.EMPTY_ARRAY); setCallSites(callSites); } public void setCallSites(List cs) { callSites = (cs != null) ? cs : new ArrayList(); } public List getCallSites() { return callSites; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ConstructorNode.java0000644001501200150120000000425111627206700024603 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; /** * Represents a constructor declaration * * @author James Strachan * @version $Revision$ */ public class ConstructorNode extends MethodNode { public ConstructorNode(int modifiers, Statement code) { this(modifiers, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code); } public ConstructorNode(int modifiers, Parameter[] parameters, ClassNode[] exceptions, Statement code) { super("",modifiers,ClassHelper.VOID_TYPE,parameters,exceptions,code); // This variable scope is thrown out and replaced with a different one during semantic analysis. VariableScope scope = new VariableScope(); for (int i = 0; i < parameters.length; i++) { scope.putDeclaredVariable(parameters[i]); } this.setVariableScope(scope); } public boolean firstStatementIsSpecialConstructorCall() { Statement code = getFirstStatement(); if (code == null || !(code instanceof ExpressionStatement)) return false; Expression expression = ((ExpressionStatement) code).getExpression(); if (!(expression instanceof ConstructorCallExpression)) return false; ConstructorCallExpression cce = (ConstructorCallExpression) expression; return cce.isSpecialCall(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/package.html0000644001501200150120000000024511627206700023065 0ustar miguelmiguel package org.codehaus.groovy.ast.*

    Groovy AST nodes for the syntax of the language

    groovy-1.8.6/src/main/org/codehaus/groovy/ast/ClassHelper.java0000644001501200150120000003374211707612044023665 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import groovy.lang.*; import org.codehaus.groovy.runtime.GeneratedClosure; import org.codehaus.groovy.vmplugin.VMPluginFactory; import org.objectweb.asm.Opcodes; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.regex.Pattern; import java.lang.ref.SoftReference; /** * This class is a Helper for ClassNode and classes handling ClassNodes. * It does contain a set of predefined ClassNodes for the most used * types and some code for cached ClassNode creation and basic * ClassNode handling * * @author Jochen Theodorou */ public class ClassHelper { private static final Class[] classes = new Class[] { Object.class, Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Double.TYPE, Float.TYPE, Void.TYPE, Closure.class, GString.class, List.class, Map.class, Range.class, Pattern.class, Script.class, String.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Double.class, Float.class, BigDecimal.class, BigInteger.class, Number.class, Void.class, Reference.class, Class.class, MetaClass.class, Iterator.class, GeneratedClosure.class, GroovyObjectSupport.class }; private static final String[] primitiveClassNames = new String[] { "", "boolean", "char", "byte", "short", "int", "long", "double", "float", "void" }; public static final ClassNode DYNAMIC_TYPE = makeCached(Object.class), OBJECT_TYPE = DYNAMIC_TYPE, VOID_TYPE = makeCached(Void.TYPE), CLOSURE_TYPE = makeCached(Closure.class), GSTRING_TYPE = makeCached(GString.class), LIST_TYPE = makeWithoutCaching(List.class), MAP_TYPE = makeWithoutCaching(Map.class), RANGE_TYPE = makeCached(Range.class), PATTERN_TYPE = makeCached(Pattern.class), STRING_TYPE = makeCached(String.class), SCRIPT_TYPE = makeCached(Script.class), REFERENCE_TYPE = makeWithoutCaching(Reference.class), boolean_TYPE = makeCached(boolean.class), char_TYPE = makeCached(char.class), byte_TYPE = makeCached(byte.class), int_TYPE = makeCached(int.class), long_TYPE = makeCached(long.class), short_TYPE = makeCached(short.class), double_TYPE = makeCached(double.class), float_TYPE = makeCached(float.class), Byte_TYPE = makeCached(Byte.class), Short_TYPE = makeCached(Short.class), Integer_TYPE = makeCached(Integer.class), Long_TYPE = makeCached(Long.class), Character_TYPE = makeCached(Character.class), Float_TYPE = makeCached(Float.class), Double_TYPE = makeCached(Double.class), Boolean_TYPE = makeCached(Boolean.class), BigInteger_TYPE = makeCached(java.math.BigInteger.class), BigDecimal_TYPE = makeCached(java.math.BigDecimal.class), Number_TYPE = makeCached(Number.class), void_WRAPPER_TYPE = makeCached(Void.class), METACLASS_TYPE = makeCached(MetaClass.class), Iterator_TYPE = makeCached(Iterator.class), // uncached constants. CLASS_Type = makeWithoutCaching(Class.class), COMPARABLE_TYPE = makeWithoutCaching(Comparable.class), GENERATED_CLOSURE_Type = makeWithoutCaching(GeneratedClosure.class), GROOVY_OBJECT_SUPPORT_TYPE = makeWithoutCaching(GroovyObjectSupport.class), GROOVY_OBJECT_TYPE = makeWithoutCaching(GroovyObject.class), GROOVY_INTERCEPTABLE_TYPE = makeWithoutCaching(GroovyInterceptable.class), Enum_Type = new ClassNode("java.lang.Enum",0,OBJECT_TYPE), Annotation_TYPE = new ClassNode("java.lang.annotation.Annotation",0,OBJECT_TYPE), ELEMENT_TYPE_TYPE = new ClassNode("java.lang.annotation.ElementType",0,Enum_Type) ; static { Enum_Type.isPrimaryNode = false; Annotation_TYPE.isPrimaryNode = false; } private static ClassNode[] types = new ClassNode[] { OBJECT_TYPE, boolean_TYPE, char_TYPE, byte_TYPE, short_TYPE, int_TYPE, long_TYPE, double_TYPE, float_TYPE, VOID_TYPE, CLOSURE_TYPE, GSTRING_TYPE, LIST_TYPE, MAP_TYPE, RANGE_TYPE, PATTERN_TYPE, SCRIPT_TYPE, STRING_TYPE, Boolean_TYPE, Character_TYPE, Byte_TYPE, Short_TYPE, Integer_TYPE, Long_TYPE, Double_TYPE, Float_TYPE, BigDecimal_TYPE, BigInteger_TYPE, Number_TYPE, void_WRAPPER_TYPE, REFERENCE_TYPE, CLASS_Type, METACLASS_TYPE, Iterator_TYPE, GENERATED_CLOSURE_Type, GROOVY_OBJECT_SUPPORT_TYPE, GROOVY_OBJECT_TYPE, GROOVY_INTERCEPTABLE_TYPE, Enum_Type, Annotation_TYPE }; protected static final ClassNode[] EMPTY_TYPE_ARRAY = {}; public static final String OBJECT = "java.lang.Object"; public static ClassNode makeCached(Class c){ final SoftReference classNodeSoftReference = ClassHelperCache.classCache.get(c); ClassNode classNode; if (classNodeSoftReference == null || (classNode = classNodeSoftReference.get()) == null) { classNode = new ClassNode(c); ClassHelperCache.classCache.put(c, new SoftReference(classNode)); VMPluginFactory.getPlugin().setAdditionalClassInformation(classNode); } return classNode; } /** * Creates an array of ClassNodes using an array of classes. * For each of the given classes a new ClassNode will be * created * @see #make(Class) * @param classes an array of classes used to create the ClassNodes * @return an array of ClassNodes */ public static ClassNode[] make(Class[] classes) { ClassNode[] cns = new ClassNode[classes.length]; for (int i=0; i> classCache = new WeakHashMap>(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/CodeVisitorSupport.java0000644001501200150120000002274411707612044025307 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.classgen.BytecodeExpression; import java.util.List; /** * Abstract base class for any GroovyCodeVisitor which by default * just walks the code and expression tree * * @author James Strachan * @version $Revision$ */ public abstract class CodeVisitorSupport implements GroovyCodeVisitor { public void visitBlockStatement(BlockStatement block) { for (Statement statement : block.getStatements()) { statement.visit(this); } } public void visitForLoop(ForStatement forLoop) { forLoop.getCollectionExpression().visit(this); forLoop.getLoopBlock().visit(this); } public void visitWhileLoop(WhileStatement loop) { loop.getBooleanExpression().visit(this); loop.getLoopBlock().visit(this); } public void visitDoWhileLoop(DoWhileStatement loop) { loop.getLoopBlock().visit(this); loop.getBooleanExpression().visit(this); } public void visitIfElse(IfStatement ifElse) { ifElse.getBooleanExpression().visit(this); ifElse.getIfBlock().visit(this); Statement elseBlock = ifElse.getElseBlock(); if (elseBlock instanceof EmptyStatement) { // dispatching to EmptyStatement will not call back visitor, // must call our visitEmptyStatement explicitly visitEmptyStatement((EmptyStatement) elseBlock); } else { elseBlock.visit(this); } } public void visitExpressionStatement(ExpressionStatement statement) { statement.getExpression().visit(this); } public void visitReturnStatement(ReturnStatement statement) { statement.getExpression().visit(this); } public void visitAssertStatement(AssertStatement statement) { statement.getBooleanExpression().visit(this); statement.getMessageExpression().visit(this); } public void visitTryCatchFinally(TryCatchStatement statement) { statement.getTryStatement().visit(this); for (CatchStatement catchStatement : statement.getCatchStatements()) { catchStatement.visit(this); } Statement finallyStatement = statement.getFinallyStatement(); if (finallyStatement instanceof EmptyStatement) { // dispatching to EmptyStatement will not call back visitor, // must call our visitEmptyStatement explicitly visitEmptyStatement((EmptyStatement) finallyStatement); } else { finallyStatement.visit(this); } } protected void visitEmptyStatement(EmptyStatement statement) { // noop } public void visitSwitch(SwitchStatement statement) { statement.getExpression().visit(this); for (CaseStatement caseStatement : statement.getCaseStatements()) { caseStatement.visit(this); } statement.getDefaultStatement().visit(this); } public void visitCaseStatement(CaseStatement statement) { statement.getExpression().visit(this); statement.getCode().visit(this); } public void visitBreakStatement(BreakStatement statement) { } public void visitContinueStatement(ContinueStatement statement) { } public void visitSynchronizedStatement(SynchronizedStatement statement) { statement.getExpression().visit(this); statement.getCode().visit(this); } public void visitThrowStatement(ThrowStatement statement) { statement.getExpression().visit(this); } public void visitMethodCallExpression(MethodCallExpression call) { call.getObjectExpression().visit(this); call.getMethod().visit(this); call.getArguments().visit(this); } public void visitStaticMethodCallExpression(StaticMethodCallExpression call) { call.getArguments().visit(this); } public void visitConstructorCallExpression(ConstructorCallExpression call) { call.getArguments().visit(this); } public void visitBinaryExpression(BinaryExpression expression) { expression.getLeftExpression().visit(this); expression.getRightExpression().visit(this); } public void visitTernaryExpression(TernaryExpression expression) { expression.getBooleanExpression().visit(this); expression.getTrueExpression().visit(this); expression.getFalseExpression().visit(this); } public void visitShortTernaryExpression(ElvisOperatorExpression expression) { visitTernaryExpression(expression); } public void visitPostfixExpression(PostfixExpression expression) { expression.getExpression().visit(this); } public void visitPrefixExpression(PrefixExpression expression) { expression.getExpression().visit(this); } public void visitBooleanExpression(BooleanExpression expression) { expression.getExpression().visit(this); } public void visitNotExpression(NotExpression expression) { expression.getExpression().visit(this); } public void visitClosureExpression(ClosureExpression expression) { expression.getCode().visit(this); } public void visitTupleExpression(TupleExpression expression) { visitListOfExpressions(expression.getExpressions()); } public void visitListExpression(ListExpression expression) { visitListOfExpressions(expression.getExpressions()); } public void visitArrayExpression(ArrayExpression expression) { visitListOfExpressions(expression.getExpressions()); visitListOfExpressions(expression.getSizeExpression()); } public void visitMapExpression(MapExpression expression) { visitListOfExpressions(expression.getMapEntryExpressions()); } public void visitMapEntryExpression(MapEntryExpression expression) { expression.getKeyExpression().visit(this); expression.getValueExpression().visit(this); } public void visitRangeExpression(RangeExpression expression) { expression.getFrom().visit(this); expression.getTo().visit(this); } public void visitSpreadExpression(SpreadExpression expression) { expression.getExpression().visit(this); } public void visitSpreadMapExpression(SpreadMapExpression expression) { expression.getExpression().visit(this); } public void visitMethodPointerExpression(MethodPointerExpression expression) { expression.getExpression().visit(this); expression.getMethodName().visit(this); } public void visitUnaryMinusExpression(UnaryMinusExpression expression) { expression.getExpression().visit(this); } public void visitUnaryPlusExpression(UnaryPlusExpression expression) { expression.getExpression().visit(this); } public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) { expression.getExpression().visit(this); } public void visitCastExpression(CastExpression expression) { expression.getExpression().visit(this); } public void visitConstantExpression(ConstantExpression expression) { } public void visitClassExpression(ClassExpression expression) { } public void visitVariableExpression(VariableExpression expression) { } public void visitDeclarationExpression(DeclarationExpression expression) { visitBinaryExpression(expression); } public void visitPropertyExpression(PropertyExpression expression) { expression.getObjectExpression().visit(this); expression.getProperty().visit(this); } public void visitAttributeExpression(AttributeExpression expression) { expression.getObjectExpression().visit(this); expression.getProperty().visit(this); } public void visitFieldExpression(FieldExpression expression) { } public void visitGStringExpression(GStringExpression expression) { visitListOfExpressions(expression.getStrings()); visitListOfExpressions(expression.getValues()); } protected void visitListOfExpressions(List list) { if (list == null) return; for (Expression expression : list) { if (expression instanceof SpreadExpression) { Expression spread = ((SpreadExpression) expression).getExpression(); spread.visit(this); } else { expression.visit(this); } } } public void visitCatchStatement(CatchStatement statement) { statement.getCode().visit(this); } public void visitArgumentlistExpression(ArgumentListExpression ale) { visitTupleExpression(ale); } public void visitClosureListExpression(ClosureListExpression cle) { visitListOfExpressions(cle.getExpressions()); } public void visitBytecodeExpression(BytecodeExpression cle) { } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ASTNode.java0000644001501200150120000001313211715031256022703 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.util.ListHashMap; /** * Base class for any AST node. This class supports basic information used in all * nodes of the AST
      *
    • line and column number information. Usually a node represents a certain * area in a text file determined by a starting position and an ending position. * For nodes that do not represent this, this information will be -1. A node can * also be configured in its line/col information using another node through * setSourcePosition(otherNode).
    • *
    • every node can store meta data. A phase operation or transform can use * this to transport arbitrary information to another phase operation or * transform. The only requirement is that the other phase operation or transform * runs after the part storing the information. If the information transport is * done it is strongly recommended to remove that meta data.
    • *
    *
  • a text representation of this node trough getText(). This was in the * past used for assertion messages. Since the usage of power asserts this * method will not be called for this purpose anymore and might be removed in * future versions of Groovy
  • * @author James Strachan * @author * @version $Revision$ */ public class ASTNode { private int lineNumber = -1; private int columnNumber = -1; private int lastLineNumber = -1; private int lastColumnNumber = -1; private ListHashMap metaDataMap = new ListHashMap(); public void visit(GroovyCodeVisitor visitor) { throw new RuntimeException("No visit() method implemented for class: " + getClass().getName()); } public String getText() { return ""; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public int getColumnNumber() { return columnNumber; } public void setColumnNumber(int columnNumber) { this.columnNumber = columnNumber; } public int getLastLineNumber() { return lastLineNumber; } public void setLastLineNumber(int lastLineNumber) { this.lastLineNumber = lastLineNumber; } public int getLastColumnNumber() { return lastColumnNumber; } public void setLastColumnNumber(int lastColumnNumber) { this.lastColumnNumber = lastColumnNumber; } /** * Sets the source position using another ASTNode. * The sourcePosition consists of a line/column pair for * the start and a line/column pair for the end of the * expression or statement * * @param node - the node used to configure the position information */ public void setSourcePosition(ASTNode node) { this.columnNumber = node.getColumnNumber(); this.lastLineNumber = node.getLastLineNumber(); this.lastColumnNumber = node.getLastColumnNumber(); this.lineNumber = node.getLineNumber(); } /** * Gets the node meta data. * * @param key - the meta data key * @return the node meta data value for this key */ public Object getNodeMetaData(Object key) { return metaDataMap.get(key); } /** * Copies all node meta data from one node to the other * @param other - the other node */ public void copyNodeMetaData(ASTNode other) { metaDataMap.putAll(other.metaDataMap); } /** * Sets the node meta data. * * @param key - the meta data key * @param value - the meta data value * @throws GroovyBugError if key is null or there is already meta * data under that key */ public void setNodeMetaData(Object key, Object value) { if (key==null) throw new GroovyBugError("Tried to set meta data with null key on "+this+"."); Object old = metaDataMap.put(key,value); if (old!=null) throw new GroovyBugError("Tried to overwrite existing meta data "+this+"."); } /** * Sets the node meta data but allows overwriting values. * * @param key - the meta data key * @param value - the meta data value * @return the old node meta data value for this key * @throws GroovyBugError if key is null */ public Object putNodeMetaData(Object key, Object value) { if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + "."); return metaDataMap.put(key, value); } /** * Removes a node meta data entry. * * @param key - the meta data key * @throws GroovyBugError if the key is null */ public void removeNodeMetaData(Object key) { if (key==null) throw new GroovyBugError("Tried to remove meta data with null key "+this+"."); metaDataMap.remove(key); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/AnnotatedNode.java0000644001501200150120000000632211627206700024174 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.*; /** * Base class for any AST node which is capable of being annotated * * @author James Strachan * @version $Revision$ */ public class AnnotatedNode extends ASTNode { private List annotations = Collections.emptyList(); private boolean synthetic; ClassNode declaringClass; private boolean hasNoRealSourcePositionFlag; public AnnotatedNode() { } public List getAnnotations() { return annotations; } public List getAnnotations(ClassNode type) { List ret = new ArrayList(annotations.size()); for (AnnotationNode node: annotations) { if (type.equals(node.getClassNode())) ret.add(node); } return ret; } public void addAnnotation(AnnotationNode value) { checkInit(); annotations.add(value); } private void checkInit() { if (annotations == Collections.EMPTY_LIST) annotations = new ArrayList(3); } public void addAnnotations(List annotations) { for (AnnotationNode node : annotations) { addAnnotation(node); } } /** * returns true if this node is added by the compiler. * NOTE: * This method has nothing to do with the synthetic flag * for fields, methods or classes. * @return true if this node is added by the compiler */ public boolean isSynthetic() { return synthetic; } /** * sets this node as a node added by the compiler. * NOTE: * This method has nothing to do with the synthetic flag * for fields, methods or classes. * @param synthetic - if true this node is marked as * added by the compiler */ public void setSynthetic(boolean synthetic) { this.synthetic = synthetic; } public ClassNode getDeclaringClass() { return declaringClass; } /** * @param declaringClass - The declaringClass to set. */ public void setDeclaringClass(ClassNode declaringClass) { this.declaringClass = declaringClass; } /** * Currently only ever returns true for default constructors * added by the compiler. See GROOVY-4161. */ public boolean hasNoRealSourcePosition() { return hasNoRealSourcePositionFlag; } public void setHasNoRealSourcePosition(boolean value) { this.hasNoRealSourcePositionFlag = value; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/Variable.java0000644001501200150120000000351211707612044023175 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.Expression; /** * interface to mark a AstNode as Variable. Typically these are * VariableExpression, FieldNode, PropertyNode and Parameter * * @author Jochen Theodorou */ public interface Variable { /** * the type of the variable */ ClassNode getType(); /** * the type before wrapping primitives type of the variable */ ClassNode getOriginType(); /** * the name of the variable */ String getName(); /** * expression used to initialize the variable or null of there * is no initialization. */ Expression getInitialExpression(); /** * returns true if there is an initialization expression */ boolean hasInitialExpression(); /** * returns true if this variable is used in a static context. * A static context is any static initializer block, when this variable * is declared as static or when this variable is used in a static method */ boolean isInStaticContext(); boolean isDynamicTyped(); boolean isClosureSharedVariable(); void setClosureSharedVariable(boolean inClosure); int getModifiers(); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/InnerClassNode.java0000644001501200150120000000520711627206700024321 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.LinkedList; /** * Represents an inner class declaration * * @author James Strachan * @version $Revision$ */ public class InnerClassNode extends ClassNode { private ClassNode outerClass; private VariableScope scope; private boolean anonymous; /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superClass the base class name - use "java.lang.Object" if no direct base class */ public InnerClassNode(ClassNode outerClass, String name, int modifiers, ClassNode superClass) { this(outerClass, name, modifiers, superClass, ClassHelper.EMPTY_TYPE_ARRAY, MixinNode.EMPTY_ARRAY); } /** * @param name is the full name of the class * @param modifiers the modifiers, @see org.objectweb.asm.Opcodes * @param superClass the base class name - use "java.lang.Object" if no direct base class */ public InnerClassNode(ClassNode outerClass, String name, int modifiers, ClassNode superClass, ClassNode[] interfaces, MixinNode[] mixins) { super(name, modifiers, superClass, interfaces, mixins); this.outerClass = outerClass; if (outerClass.innerClasses == null) outerClass.innerClasses = new LinkedList (); outerClass.innerClasses.add(this); } public ClassNode getOuterClass() { return outerClass; } /** * @return the field node on the outer class or null if this is not an inner class */ public FieldNode getOuterField(String name) { return outerClass.getDeclaredField(name); } public VariableScope getVariableScope() { return scope; } public void setVariableScope(VariableScope scope) { this.scope = scope; } public boolean isAnonymous() { return anonymous; } public void setAnonymous(boolean anonymous) { this.anonymous = anonymous; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ImportNode.java0000644001501200150120000001014111627206700023523 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.objectweb.asm.Opcodes; /** * Represents an import statement of a single class *

    * @author Jochen Theodorou * @author Paul King * @author James Strachan */ public class ImportNode extends AnnotatedNode implements Opcodes { private final ClassNode type; private final String alias; private final String fieldName; // TODO use PackageNode instead here? private final String packageName; private final boolean isStar; private final boolean isStatic; /** * Represent an import of an entire package, i.e. import package.Classname * * @param type the referenced class * @param alias optional alias */ public ImportNode(ClassNode type, String alias) { this.type = type; this.alias = alias; this.isStar = false; this.isStatic = false; this.packageName = null; this.fieldName = null; } /** * Represent an import of an entire package, i.e. import package.* * * @param packageName the name of the package */ public ImportNode(String packageName) { this.type = null; this.alias = null; this.isStar = true; this.isStatic = false; this.packageName = packageName; this.fieldName = null; } /** * Represent a static import of a Class, i.e. import static package.Classname.* * * @param type the referenced class */ public ImportNode(ClassNode type) { this.type = type; this.alias = null; this.isStar = true; this.isStatic = true; this.packageName = null; this.fieldName = null; } /** * Represent a static import of a field or method, i.e. import static package.Classname.name * * @param type the referenced class * @param fieldName the field name * @param alias optional alias */ public ImportNode(ClassNode type, String fieldName, String alias) { this.type = type; this.alias = alias; this.isStar = false; this.isStatic = true; this.packageName = null; this.fieldName = fieldName; } /** * @return the text display of this import */ public String getText() { String typeName = getClassName(); if (isStar && !isStatic) { return "import " + packageName + "*"; } if (isStar) { return "import static " + typeName + ".*"; } if (isStatic) { if (alias != null && alias.length() != 0 && !alias.equals(fieldName)) { return "import static " + typeName + "." + fieldName + " as " + alias; } return "import static " + typeName + "." + fieldName; } if (alias == null || alias.length() == 0) { return "import " + typeName; } return "import " + typeName + " as " + alias; } public String getPackageName() { return packageName; } public String getFieldName() { return fieldName; } public boolean isStar() { return isStar; } public boolean isStatic() { return isStatic; } public String getAlias() { return alias; } public ClassNode getType() { return type; } public String getClassName() { return type == null ? null : type.getName(); } public void visit(GroovyCodeVisitor visitor) { } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/AstToTextHelper.java0000644001501200150120000000702511707612044024512 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.lang.reflect.Modifier; /** * Helper class for converting AST into text. * @author Hamlet D'Arcy */ public class AstToTextHelper { public static String getClassText(ClassNode node) { if (node == null) return ""; if (node.getName() == null) return ""; return node.getName(); } public static String getParameterText(Parameter node) { if (node == null) return ""; String name = node.getName() == null ? "" : node.getName(); String type = getClassText(node.getType()); if (node.getInitialExpression() != null) { return type + " " + name + " = " + node.getInitialExpression().getText(); } return type + " " + name; } public static String getParametersText(Parameter[] parameters) { if (parameters == null) return ""; if (parameters.length == 0) return ""; StringBuilder result = new StringBuilder(); int max = parameters.length; for (int x = 0; x < max; x++) { result.append(getParameterText(parameters[x])); if (x < (max - 1)) { result.append(", "); } } return result.toString(); } public static String getThrowsClauseText(ClassNode[] exceptions) { if (exceptions == null) return ""; if (exceptions.length == 0) return ""; StringBuilder result = new StringBuilder("throws "); int max = exceptions.length; for (int x = 0; x < max; x++) { result.append(getClassText(exceptions[x])); if (x < (max - 1)) { result.append(", "); } } return result.toString(); } public static String getModifiersText(int modifiers) { StringBuilder result = new StringBuilder(); if (Modifier.isPrivate(modifiers)) { result.append("private "); } if (Modifier.isProtected(modifiers)) { result.append("protected "); } if (Modifier.isPublic(modifiers)) { result.append("public "); } if (Modifier.isStatic(modifiers)) { result.append("static "); } if (Modifier.isAbstract(modifiers)) { result.append("abstract "); } if (Modifier.isFinal(modifiers)) { result.append("final "); } if (Modifier.isInterface(modifiers)) { result.append("interface "); } if (Modifier.isNative(modifiers)) { result.append("native "); } if (Modifier.isSynchronized(modifiers)) { result.append("synchronized "); } if (Modifier.isTransient(modifiers)) { result.append("transient "); } if (Modifier.isVolatile(modifiers)) { result.append("volatile "); } return result.toString().trim(); } }groovy-1.8.6/src/main/org/codehaus/groovy/ast/CompileUnit.java0000644001501200150120000001476611707612044023715 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import groovy.lang.GroovyClassLoader; import java.security.CodeSource; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; /** * Represents the entire contents of a compilation step which consists of one or more * {@link ModuleNode} instances. There's one instance of this that's shared by all modules and * classes compiled during a single invocation of the compiler. *

    * It's attached to MethodNodes and ClassNodes and is used to find fully qualified names of classes, * resolve imports, and that sort of thing. * * @author James Strachan * @version $Revision$ */ public class CompileUnit { private final List modules = new ArrayList(); private Map classes = new HashMap(); private CompilerConfiguration config; private GroovyClassLoader classLoader; private CodeSource codeSource; private Map classesToCompile = new HashMap(); private Map classNameToSource = new HashMap(); public CompileUnit(GroovyClassLoader classLoader, CompilerConfiguration config) { this(classLoader, null, config); } public CompileUnit(GroovyClassLoader classLoader, CodeSource codeSource, CompilerConfiguration config) { this.classLoader = classLoader; this.config = config; this.codeSource = codeSource; } public List getModules() { return modules; } public void addModule(ModuleNode node) { // node==null means a compilation error prevented // groovy from building an ast if (node == null) return; modules.add(node); node.setUnit(this); addClasses(node.getClasses()); } /** * @return the ClassNode for the given qualified name or returns null if * the name does not exist in the current compilation unit * (ignoring the .class files on the classpath) */ public ClassNode getClass(String name) { ClassNode cn = classes.get(name); if (cn != null) return cn; return classesToCompile.get(name); } /** * @return a list of all the classes in each module in the compilation unit */ public List getClasses() { List answer = new ArrayList(); for (ModuleNode module : modules) { answer.addAll(module.getClasses()); } return answer; } public CompilerConfiguration getConfig() { return config; } public GroovyClassLoader getClassLoader() { return classLoader; } public CodeSource getCodeSource() { return codeSource; } /** * Appends all of the fully qualified class names in this * module into the given map */ void addClasses(List classList) { for (ClassNode node : classList) { addClass(node); } } /** * Adds a class to the unit. */ public void addClass(ClassNode node) { node = node.redirect(); String name = node.getName(); ClassNode stored = classes.get(name); if (stored != null && stored != node) { // we have a duplicate class! // One possibility for this is, that we declared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node.getModule().getContext(); SourceUnit storedSource = stored.getModule().getContext(); String txt = "Invalid duplicate class definition of class " + node.getName() + " : "; if (nodeSource == storedSource) { // same class in same source txt += "The source " + nodeSource.getName() + " contains at least two definitions of the class " + node.getName() + ".\n"; if (node.isScriptBody() || stored.isScriptBody()) { txt += "One of the classes is an explicit generated class using the class statement, the other is a class generated from" + " the script body based on the file name. Solutions are to change the file name or to change the class name.\n"; } } else { txt += "The sources " + nodeSource.getName() + " and " + storedSource.getName() + " are containing both a class of the name " + node.getName() + ".\n"; } nodeSource.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber()), nodeSource) ); } classes.put(name, node); if (classesToCompile.containsKey(name)) { ClassNode cn = classesToCompile.get(name); cn.setRedirect(node); classesToCompile.remove(name); } } /** * this method actually does not compile a class. It's only * a marker that this type has to be compiled by the CompilationUnit * at the end of a parse step no node should be be left. */ public void addClassNodeToCompile(ClassNode node, SourceUnit location) { classesToCompile.put(node.getName(), node); classNameToSource.put(node.getName(), location); } public SourceUnit getScriptSourceLocation(String className) { return classNameToSource.get(className); } public boolean hasClassNodeToCompile() { return !classesToCompile.isEmpty(); } public Iterator iterateClassNodeToCompile() { return classesToCompile.keySet().iterator(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ClassNode.java0000644001501200150120000014411511715031256023327 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.codehaus.groovy.vmplugin.VMPluginFactory; import org.objectweb.asm.Opcodes; import java.lang.reflect.Array; import java.util.*; /** * Represents a class in the AST.
    * A ClassNode should be created using the methods in ClassHelper. * This ClassNode may be used to represent a class declaration or * any other type. This class uses a proxy mechanism allowing to * create a class for a plain name at AST creation time. In another * phase of the compiler the real ClassNode for the plain name may be * found. To avoid the need of exchanging this ClassNode with an * instance of the correct ClassNode the correct ClassNode is set as * redirect. Most method calls are then redirected to that ClassNode. *
    * There are three types of ClassNodes: *
    *

      *
    1. Primary ClassNodes:
      * A primary ClassNode is one where we have a source representation * which is to be compiled by Groovy and which we have an AST for. * The groovy compiler will output one class for each such ClassNode * that passes through AsmBytecodeGenerator... not more, not less. * That means for example Closures become such ClassNodes too at * some point. * *
    2. ClassNodes create through different sources (typically created * from a java.lang.reflect.Class object):
      * The compiler will not output classes from these, the methods * usually do not contain bodies. These kind of ClassNodes will be * used in different checks, but not checks that work on the method * bodies. For example if such a ClassNode is a super class to a primary * ClassNode, then the abstract method test and others will be done * with data based on these. Theoretically it is also possible to mix both * (1 and 2) kind of classes in a hierarchy, but this probably works only * in the newest Groovy versions. Such ClassNodes normally have to * isResolved() returning true without having a redirect.In the Groovy * compiler the only version of this, that exists, is a ClassNode created * through a Class instance * *
    3. Labels:
      * ClassNodes created through ClassHelper.makeWithoutCaching. They * are place holders, its redirect points to the real structure, which can * be a label too, but following all redirects it should end with a ClassNode * from one of the other two categories. If ResolveVisitor finds such a * node, it tries to set the redirects. Any such label created after * ResolveVisitor has done its work needs to have a redirect pointing to * case 1 or 2. If not the compiler may react strange... this can be considered * as a kind of dangling pointer. *
      * Note: the redirect mechanism is only allowed for classes * that are not primary ClassNodes. Typically this is done for classes * created by name only. The redirect itself can be any type of ClassNode. *
      * To describe generic type signature see {@link #getGenericsTypes()} and * {@link #setGenericsTypes(GenericsType[])}. These methods are not proxied, * they describe the type signature used at the point of declaration or the * type signatures provided by the class. If the type signatures provided * by the class are needed, then a call to {@link #redirect()} will help. * * @see org.codehaus.groovy.ast.ClassHelper * * @author James Strachan * @author Jochen Theodorou * @version $Revision$ */ public class ClassNode extends AnnotatedNode implements Opcodes { private static class MapOfLists { private Map> map = new HashMap>(); public List get(Object key) { return map.get(key); } public List getNotNull(Object key) { List ret = get(key); if (ret==null) ret = Collections.emptyList(); return ret; } public void put(Object key, MethodNode value) { if (map.containsKey(key)) { get(key).add(value); } else { ArrayList list = new ArrayList(2); list.add(value); map.put(key, list); } } } public static final ClassNode[] EMPTY_ARRAY = new ClassNode[0]; public static final ClassNode THIS = new ClassNode(Object.class); public static final ClassNode SUPER = new ClassNode(Object.class); private String name; private int modifiers; private boolean syntheticPublic; private ClassNode[] interfaces; private MixinNode[] mixins; private List constructors; private List objectInitializers; private MapOfLists methods; private List methodsList; private LinkedList fields; private List properties; private Map fieldIndex; private ModuleNode module; private CompileUnit compileUnit; private boolean staticClass = false; private boolean scriptBody = false; private boolean script; private ClassNode superClass; protected boolean isPrimaryNode; protected List innerClasses; /** * The ASTTransformations to be applied to the Class */ private Map, Set>> transformInstances; // use this to synchronize access for the lazy init protected Object lazyInitLock = new Object(); // clazz!=null when resolved protected Class clazz; // only false when this classNode is constructed from a class private boolean lazyInitDone=true; // not null if if the ClassNode is an array private ClassNode componentType = null; // if not null this instance is handled as proxy // for the redirect private ClassNode redirect=null; // flag if the classes or its members are annotated private boolean annotated; // type spec for generics private GenericsType[] genericsTypes=null; private boolean usesGenerics=false; // if set to true the name getGenericsTypes consists // of 1 element describing the name of the placeholder private boolean placeholder; /** * Returns the ClassNode this ClassNode is redirecting to. */ public ClassNode redirect(){ if (redirect==null) return this; return redirect.redirect(); } /** * Sets this instance as proxy for the given ClassNode. * @param cn the class to redirect to. If set to null the redirect will be removed */ public void setRedirect(ClassNode cn) { if (isPrimaryNode) throw new GroovyBugError("tried to set a redirect for a primary ClassNode ("+getName()+"->"+cn.getName()+")."); if (cn!=null) cn = cn.redirect(); if (cn==this) return; redirect = cn; } /** * Returns a ClassNode representing an array of the class * represented by this ClassNode */ public ClassNode makeArray() { if (redirect!=null) { ClassNode res = redirect().makeArray(); res.componentType = this; return res; } ClassNode cn; if (clazz!=null) { Class ret = Array.newInstance(clazz,0).getClass(); // don't use the ClassHelper here! cn = new ClassNode(ret,this); } else { cn = new ClassNode(this); } return cn; } /** * @return true if this instance is a primary ClassNode */ public boolean isPrimaryClassNode() { return redirect().isPrimaryNode || (componentType != null && componentType.isPrimaryClassNode()); } /* * Constructor used by makeArray() if no real class is available */ private ClassNode(ClassNode componentType) { this(componentType.getName()+"[]", ACC_PUBLIC, ClassHelper.OBJECT_TYPE); this.componentType = componentType.redirect(); isPrimaryNode=false; } /* * Constructor used by makeArray() if a real class is available */ private ClassNode(Class c, ClassNode componentType) { this(c); this.componentType = componentType; isPrimaryNode=false; } /** * Creates a ClassNode from a real class. The resulting * ClassNode will not be a primary ClassNode. */ public ClassNode(Class c) { this(c.getName(), c.getModifiers(), null, null ,MixinNode.EMPTY_ARRAY); clazz=c; lazyInitDone=false; CompileUnit cu = getCompileUnit(); if (cu!=null) cu.addClass(this); isPrimaryNode=false; } /** * The complete class structure will be initialized only when really * needed to avoid having too many objects during compilation */ private void lazyClassInit() { synchronized (lazyInitLock) { if (redirect!=null) { throw new GroovyBugError("lazyClassInit called on a proxy ClassNode, that must not happen."+ "A redirect() call is missing somewhere!"); } if (lazyInitDone) return; VMPluginFactory.getPlugin().configureClassNode(compileUnit,this); lazyInitDone = true; } } // added to track the enclosing method for local inner classes private MethodNode enclosingMethod = null; public MethodNode getEnclosingMethod() { return redirect().enclosingMethod; } public void setEnclosingMethod(MethodNode enclosingMethod) { redirect().enclosingMethod = enclosingMethod; } /** * Indicates that this class has been "promoted" to public by * Groovy when in fact there was no public modifier explicitly * in the source code. I.e. it remembers that it has applied * Groovy's "public classes by default" rule.This property is * typically only of interest to AST transform writers. * * @return true if this class is public but had no explicit public modifier */ public boolean isSyntheticPublic() { return syntheticPublic; } public void setSyntheticPublic(boolean syntheticPublic) { this.syntheticPublic = syntheticPublic; } /** * @param name is the full name of the class * @param modifiers the modifiers, * @param superClass the base class name - use "java.lang.Object" if no direct * base class * @see org.objectweb.asm.Opcodes */ public ClassNode(String name, int modifiers, ClassNode superClass) { this(name, modifiers, superClass, EMPTY_ARRAY, MixinNode.EMPTY_ARRAY); } /** * @param name is the full name of the class * @param modifiers the modifiers, * @param superClass the base class name - use "java.lang.Object" if no direct * base class * @param interfaces the interfaces for this class * @param mixins the mixins for this class * @see org.objectweb.asm.Opcodes */ public ClassNode(String name, int modifiers, ClassNode superClass, ClassNode[] interfaces, MixinNode[] mixins) { this.name = name; this.modifiers = modifiers; this.superClass = superClass; this.interfaces = interfaces; this.mixins = mixins; isPrimaryNode = true; if (superClass!=null) { usesGenerics = superClass.isUsingGenerics(); } if (!usesGenerics && interfaces!=null) { for (ClassNode anInterface : interfaces) { usesGenerics = usesGenerics || anInterface.isUsingGenerics(); } } this.methods = new MapOfLists(); this.methodsList = new ArrayList(); } /** * Sets the superclass of this ClassNode */ public void setSuperClass(ClassNode superClass) { redirect().superClass = superClass; } /** * @return the list of FieldNode's associated with this ClassNode */ public List getFields() { if (!redirect().lazyInitDone) redirect().lazyClassInit(); if (redirect!=null) return redirect().getFields(); if (fields == null) fields = new LinkedList (); return fields; } /** * @return the array of interfaces which this ClassNode implements */ public ClassNode[] getInterfaces() { if (!redirect().lazyInitDone) redirect().lazyClassInit(); if (redirect!=null) return redirect().getInterfaces(); return interfaces; } public void setInterfaces(ClassNode[] interfaces) { if (redirect!=null) { redirect().setInterfaces(interfaces); } else { this.interfaces = interfaces; } } /** * @return the array of mixins associated with this ClassNode */ public MixinNode[] getMixins() { return redirect().mixins; } /** * @return the list of methods associated with this ClassNode */ public List getMethods() { if (!redirect().lazyInitDone) redirect().lazyClassInit(); if (redirect!=null) return redirect().getMethods(); return methodsList; } /** * @return the list of abstract methods associated with this * ClassNode or null if there are no such methods */ public List getAbstractMethods() { List result = new ArrayList(3); for (MethodNode method : getDeclaredMethodsMap().values()) { if (method.isAbstract()) { result.add(method); } } if (result.isEmpty()) { return null; } else { return result; } } public List getAllDeclaredMethods() { return new ArrayList(getDeclaredMethodsMap().values()); } public Set getAllInterfaces () { Set res = new HashSet(); getAllInterfaces(res); return res; } private void getAllInterfaces(Set res) { if (isInterface()) res.add(this); for (ClassNode anInterface : getInterfaces()) { res.add(anInterface); anInterface.getAllInterfaces(res); } } public Map getDeclaredMethodsMap() { // Start off with the methods from the superclass. ClassNode parent = getSuperClass(); Map result = null; if (parent != null) { result = parent.getDeclaredMethodsMap(); } else { result = new HashMap(); } // add in unimplemented abstract methods from the interfaces for (ClassNode iface : getInterfaces()) { Map ifaceMethodsMap = iface.getDeclaredMethodsMap(); for (String methSig : ifaceMethodsMap.keySet()) { if (!result.containsKey(methSig)) { MethodNode methNode = ifaceMethodsMap.get(methSig); result.put(methSig, methNode); } } } // And add in the methods implemented in this class. for (MethodNode method : getMethods()) { String sig = method.getTypeDescriptor(); result.put(sig, method); } return result; } public String getName() { return redirect().name; } public String getUnresolvedName() { return name; } public String setName(String name) { return redirect().name=name; } public int getModifiers() { return redirect().modifiers; } public void setModifiers(int modifiers) { redirect().modifiers = modifiers; } public List getProperties() { final ClassNode r = redirect(); if (r.properties == null) r.properties = new ArrayList (); return r.properties; } public List getDeclaredConstructors() { if (!redirect().lazyInitDone) redirect().lazyClassInit(); final ClassNode r = redirect(); if (r.constructors == null) r.constructors = new ArrayList (); return r.constructors; } public ModuleNode getModule() { return redirect().module; } public PackageNode getPackage() { return getModule() == null ? null : getModule().getPackage(); } public void setModule(ModuleNode module) { redirect().module = module; if (module != null) { redirect().compileUnit = module.getUnit(); } } public void addField(FieldNode node) { final ClassNode r = redirect(); node.setDeclaringClass(r); node.setOwner(r); if (r.fields == null) r.fields = new LinkedList (); if (r.fieldIndex == null) r.fieldIndex = new HashMap (); r.fields.add(node); r.fieldIndex.put(node.getName(), node); } public void addFieldFirst(FieldNode node) { final ClassNode r = redirect(); node.setDeclaringClass(r); node.setOwner(r); if (r.fields == null) r.fields = new LinkedList (); if (r.fieldIndex == null) r.fieldIndex = new HashMap (); r.fields.addFirst(node); r.fieldIndex.put(node.getName(), node); } public void addProperty(PropertyNode node) { node.setDeclaringClass(redirect()); FieldNode field = node.getField(); addField(field); final ClassNode r = redirect(); if (r.properties == null) r.properties = new ArrayList (); r.properties.add(node); } public PropertyNode addProperty(String name, int modifiers, ClassNode type, Expression initialValueExpression, Statement getterBlock, Statement setterBlock) { for (PropertyNode pn : getProperties()) { if (pn.getName().equals(name)) { if (pn.getInitialExpression() == null && initialValueExpression != null) pn.getField().setInitialValueExpression(initialValueExpression); if (pn.getGetterBlock() == null && getterBlock != null) pn.setGetterBlock(getterBlock); if (pn.getSetterBlock() == null && setterBlock != null) pn.setSetterBlock(setterBlock); return pn; } } PropertyNode node = new PropertyNode(name, modifiers, type, redirect(), initialValueExpression, getterBlock, setterBlock); addProperty(node); return node; } public boolean hasProperty(String name) { return getProperty(name) != null; } public PropertyNode getProperty(String name) { for (PropertyNode pn : getProperties()) { if (pn.getName().equals(name)) return pn; } return null; } public void addConstructor(ConstructorNode node) { node.setDeclaringClass(this); final ClassNode r = redirect(); if (r.constructors == null) r.constructors = new ArrayList (); r.constructors.add(node); } public ConstructorNode addConstructor(int modifiers, Parameter[] parameters, ClassNode[] exceptions, Statement code) { ConstructorNode node = new ConstructorNode(modifiers, parameters, exceptions, code); addConstructor(node); return node; } public void addMethod(MethodNode node) { node.setDeclaringClass(this); redirect().methodsList.add(node); redirect().methods.put(node.getName(), node); } /** * If a method with the given name and parameters is already defined then it is returned * otherwise the given method is added to this node. This method is useful for * default method adding like getProperty() or invokeMethod() where there may already * be a method defined in a class and so the default implementations should not be added * if already present. */ public MethodNode addMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNode other = getDeclaredMethod(name, parameters); // let's not add duplicate methods if (other != null) { return other; } MethodNode node = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); addMethod(node); return node; } /** * @see #getDeclaredMethod(String, Parameter[]) */ public boolean hasDeclaredMethod(String name, Parameter[] parameters) { MethodNode other = getDeclaredMethod(name, parameters); return other != null; } /** * @see #getMethod(String, Parameter[]) */ public boolean hasMethod(String name, Parameter[] parameters) { MethodNode other = getMethod(name, parameters); return other != null; } /** * Adds a synthetic method as part of the compilation process */ public MethodNode addSyntheticMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNode answer = addMethod(name, modifiers|ACC_SYNTHETIC, returnType, parameters, exceptions, code); answer.setSynthetic(true); return answer; } public FieldNode addField(String name, int modifiers, ClassNode type, Expression initialValue) { FieldNode node = new FieldNode(name, modifiers, type, redirect(), initialValue); addField(node); return node; } public FieldNode addFieldFirst(String name, int modifiers, ClassNode type, Expression initialValue) { FieldNode node = new FieldNode(name, modifiers, type, redirect(), initialValue); addFieldFirst(node); return node; } public void addInterface(ClassNode type) { // let's check if it already implements an interface boolean skip = false; ClassNode[] interfaces = redirect().interfaces; for (ClassNode existing : interfaces) { if (type.equals(existing)) { skip = true; } } if (!skip) { ClassNode[] newInterfaces = new ClassNode[interfaces.length + 1]; System.arraycopy(interfaces, 0, newInterfaces, 0, interfaces.length); newInterfaces[interfaces.length] = type; redirect().interfaces = newInterfaces; } } public boolean equals(Object o) { if (redirect!=null) return redirect().equals(o); if (!(o instanceof ClassNode)) return false; ClassNode cn = (ClassNode) o; return (cn.getName().equals(getName())); } public int hashCode() { if (redirect!=null) return redirect().hashCode(); return getName().hashCode(); } public void addMixin(MixinNode mixin) { // let's check if it already uses a mixin MixinNode[] mixins = redirect().mixins; boolean skip = false; for (MixinNode existing : mixins) { if (mixin.equals(existing)) { skip = true; } } if (!skip) { MixinNode[] newMixins = new MixinNode[mixins.length + 1]; System.arraycopy(mixins, 0, newMixins, 0, mixins.length); newMixins[mixins.length] = mixin; redirect().mixins = newMixins; } } /** * Finds a field matching the given name in this class. * * @param name the name of the field of interest * @return the method matching the given name and parameters or null */ public FieldNode getDeclaredField(String name) { if (!redirect().lazyInitDone) redirect().lazyClassInit(); ClassNode r = redirect (); if (r.fieldIndex == null) r.fieldIndex = new HashMap (); return r.fieldIndex.get(name); } /** * Finds a field matching the given name in this class or a parent class. * * @param name the name of the field of interest * @return the method matching the given name and parameters or null */ public FieldNode getField(String name) { ClassNode node = this; while (node != null) { FieldNode fn = node.getDeclaredField(name); if (fn != null) return fn; node = node.getSuperClass(); } return null; } /** * @return the field node on the outer class or null if this is not an * inner class */ public FieldNode getOuterField(String name) { return null; } /** * Helper method to avoid casting to inner class */ public ClassNode getOuterClass() { return null; } /** * Adds a statement to the object initializer. * * @param statements the statement to be added */ public void addObjectInitializerStatements(Statement statements) { getObjectInitializerStatements().add(statements); } public List getObjectInitializerStatements() { if (objectInitializers == null) objectInitializers = new ArrayList (); return objectInitializers; } private MethodNode getOrAddStaticConstructorNode() { MethodNode method = null; List declaredMethods = getDeclaredMethods(""); if (declaredMethods.isEmpty()) { method = addMethod("", ACC_STATIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new BlockStatement()); method.setSynthetic(true); } else { method = (MethodNode) declaredMethods.get(0); } return method; } public void addStaticInitializerStatements(List staticStatements, boolean fieldInit) { MethodNode method = getOrAddStaticConstructorNode(); BlockStatement block = null; Statement statement = method.getCode(); if (statement == null) { block = new BlockStatement(); } else if (statement instanceof BlockStatement) { block = (BlockStatement) statement; } else { block = new BlockStatement(); block.addStatement(statement); } // while anything inside a static initializer block is appended // we don't want to append in the case we have a initialization // expression of a static field. In that case we want to add // before the other statements if (!fieldInit) { block.addStatements(staticStatements); } else { List blockStatements = block.getStatements(); staticStatements.addAll(blockStatements); blockStatements.clear(); blockStatements.addAll(staticStatements); } } public void positionStmtsAfterEnumInitStmts(List staticFieldStatements) { MethodNode method = getOrAddStaticConstructorNode(); Statement statement = method.getCode(); if (statement instanceof BlockStatement) { BlockStatement block = (BlockStatement) statement; // add given statements for explicitly declared static fields just after enum-special fields // are found - the $VALUES binary expression marks the end of such fields. List blockStatements = block.getStatements(); ListIterator litr = blockStatements.listIterator(); while (litr.hasNext()) { Statement stmt = litr.next(); if (stmt instanceof ExpressionStatement && ((ExpressionStatement) stmt).getExpression() instanceof BinaryExpression) { BinaryExpression bExp = (BinaryExpression) ((ExpressionStatement) stmt).getExpression(); if (bExp.getLeftExpression() instanceof FieldExpression) { FieldExpression fExp = (FieldExpression) bExp.getLeftExpression(); if (fExp.getFieldName().equals("$VALUES")) { for (Statement tmpStmt : staticFieldStatements) { litr.add(tmpStmt); } } } } } } } /** * This methods returns a list of all methods of the given name * defined in the current class * @return the method list * @see #getMethods(String) */ public List getDeclaredMethods(String name) { if (!redirect().lazyInitDone) redirect().lazyClassInit(); if (redirect!=null) return redirect().getDeclaredMethods(name); return methods.getNotNull(name); } /** * This methods creates a list of all methods with this name of the * current class and of all super classes * @return the methods list * @see #getDeclaredMethods(String) */ public List getMethods(String name) { List answer = new ArrayList(); ClassNode node = this; while (node != null) { answer.addAll(node.getDeclaredMethods(name)); node = node.getSuperClass(); } return answer; } /** * Finds a method matching the given name and parameters in this class. * * @return the method matching the given name and parameters or null */ public MethodNode getDeclaredMethod(String name, Parameter[] parameters) { for (MethodNode method : getDeclaredMethods(name)) { if (parametersEqual(method.getParameters(), parameters)) { return method; } } return null; } /** * Finds a method matching the given name and parameters in this class * or any parent class. * * @return the method matching the given name and parameters or null */ public MethodNode getMethod(String name, Parameter[] parameters) { for (MethodNode method : getMethods(name)) { if (parametersEqual(method.getParameters(), parameters)) { return method; } } return null; } /** * @param type the ClassNode of interest * @return true if this node is derived from the given ClassNode */ public boolean isDerivedFrom(ClassNode type) { if (this.equals(ClassHelper.VOID_TYPE)) { return type.equals(ClassHelper.VOID_TYPE); } if (type.equals(ClassHelper.OBJECT_TYPE)) return true; ClassNode node = this; while (node != null) { if (type.equals(node)) { return true; } node = node.getSuperClass(); } return false; } /** * @return true if this class is derived from a groovy object * i.e. it implements GroovyObject */ public boolean isDerivedFromGroovyObject() { return implementsInterface(ClassHelper.GROOVY_OBJECT_TYPE); } /** * @param classNode the class node for the interface * @return true if this class or any base class implements the given interface */ public boolean implementsInterface(ClassNode classNode) { ClassNode node = redirect(); do { if (node.declaresInterface(classNode)) { return true; } node = node.getSuperClass(); } while (node != null); return false; } /** * @param classNode the class node for the interface * @return true if this class declares that it implements the given interface * or if one of its interfaces extends directly or indirectly the interface * * NOTE: Doesn't consider an interface to implement itself. * I think this is intended to be called on ClassNodes representing * classes, not interfaces. * */ public boolean declaresInterface(ClassNode classNode) { ClassNode[] interfaces = redirect().getInterfaces(); for (ClassNode cn : interfaces) { if (cn.equals(classNode)) return true; } for (ClassNode cn : interfaces) { if (cn.declaresInterface(classNode)) return true; } return false; } /** * @return the ClassNode of the super class of this type */ public ClassNode getSuperClass() { if (!lazyInitDone && !isResolved()) { throw new GroovyBugError("ClassNode#getSuperClass for "+getName()+" called before class resolving"); } ClassNode sn = redirect().getUnresolvedSuperClass(); if (sn!=null) sn=sn.redirect(); return sn; } public ClassNode getUnresolvedSuperClass() { return getUnresolvedSuperClass(true); } public ClassNode getUnresolvedSuperClass(boolean useRedirect) { if (!useRedirect) return superClass; if (!redirect().lazyInitDone) redirect().lazyClassInit(); return redirect().superClass; } public void setUnresolvedSuperClass(ClassNode sn) { superClass = sn; } public ClassNode [] getUnresolvedInterfaces() { return getUnresolvedInterfaces(true); } public ClassNode [] getUnresolvedInterfaces(boolean useRedirect) { if (!useRedirect) return interfaces; if (!redirect().lazyInitDone) redirect().lazyClassInit(); return redirect().interfaces; } public CompileUnit getCompileUnit() { if (redirect!=null) return redirect().getCompileUnit(); if (compileUnit == null && module != null) { compileUnit = module.getUnit(); } return compileUnit; } protected void setCompileUnit(CompileUnit cu) { if (redirect!=null) redirect().setCompileUnit(cu); if (compileUnit!= null) compileUnit = cu; } /** * @return true if the two arrays are of the same size and have the same contents */ protected boolean parametersEqual(Parameter[] a, Parameter[] b) { if (a.length == b.length) { boolean answer = true; for (int i = 0; i < a.length; i++) { if (!a[i].getType().equals(b[i].getType())) { answer = false; break; } } return answer; } return false; } /** * @return the package name of this class */ public String getPackageName() { int idx = getName().lastIndexOf('.'); if (idx > 0) { return getName().substring(0, idx); } return null; } public String getNameWithoutPackage() { int idx = getName().lastIndexOf('.'); if (idx > 0) { return getName().substring(idx + 1); } return getName(); } public void visitContents(GroovyClassVisitor visitor) { // now let's visit the contents of the class for (PropertyNode pn : getProperties()) { visitor.visitProperty(pn); } for (FieldNode fn : getFields()) { visitor.visitField(fn); } for (ConstructorNode cn : getDeclaredConstructors()) { visitor.visitConstructor(cn); } for (MethodNode mn : getMethods()) { visitor.visitMethod(mn); } } public MethodNode getGetterMethod(String getterName) { for (MethodNode method : getDeclaredMethods(getterName)) { if (getterName.equals(method.getName()) && ClassHelper.VOID_TYPE!=method.getReturnType() && method.getParameters().length == 0) { return method; } } ClassNode parent = getSuperClass(); if (parent!=null) return parent.getGetterMethod(getterName); return null; } public MethodNode getSetterMethod(String setterName) { return getSetterMethod(setterName, true); } public MethodNode getSetterMethod(String setterName, boolean voidOnly) { for (MethodNode method : getDeclaredMethods(setterName)) { if (setterName.equals(method.getName()) && (!voidOnly || ClassHelper.VOID_TYPE==method.getReturnType()) && method.getParameters().length == 1) { return method; } } ClassNode parent = getSuperClass(); if (parent!=null) return parent.getSetterMethod(setterName, voidOnly); return null; } /** * Is this class declared in a static method (such as a closure / inner class declared in a static method) */ public boolean isStaticClass() { return redirect().staticClass; } public void setStaticClass(boolean staticClass) { redirect().staticClass = staticClass; } /** * @return Returns true if this inner class or closure was declared inside a script body */ public boolean isScriptBody() { return redirect().scriptBody; } public void setScriptBody(boolean scriptBody) { redirect().scriptBody = scriptBody; } public boolean isScript() { return redirect().script || isDerivedFrom(ClassHelper.SCRIPT_TYPE); } public void setScript(boolean script) { redirect().script = script; } public String toString() { String ret = getName(); if (genericsTypes != null) { ret += " <"; for (int i = 0; i < genericsTypes.length; i++) { if (i != 0) ret += ", "; GenericsType genericsType = genericsTypes[i]; ret += genericTypeAsString(genericsType); } ret += ">"; } if (redirect != null) { ret += " -> " + redirect().toString(); } return ret; } /** * This exists to avoid a recursive definition of toString. The default toString * in GenericsType calls ClassNode.toString(), which calls GenericsType.toString(), etc. * @param genericsType * @return */ private String genericTypeAsString(GenericsType genericsType) { String ret = genericsType.getName(); if (genericsType.getUpperBounds() != null) { ret += " extends "; for (int i = 0; i < genericsType.getUpperBounds().length; i++) { ClassNode classNode = genericsType.getUpperBounds()[i]; if (classNode.equals(this)) { ret += classNode.getName(); } else { ret += classNode.toString(); } if (i + 1 < genericsType.getUpperBounds().length) ret += " & "; } } else if (genericsType.getLowerBound() !=null) { ClassNode classNode = genericsType.getLowerBound(); if (classNode.equals(this)) { ret += " super " + classNode.getName(); } else { ret += " super " + classNode; } } return ret; } /** * Returns true if the given method has a possibly matching instance method with the given name and arguments. * * @param name the name of the method of interest * @param arguments the arguments to match against * @return true if a matching method was found */ public boolean hasPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } ClassNode node = this; do { for (MethodNode method : getMethods(name)) { if (method.getParameters().length == count && !method.isStatic()) { return true; } } node = node.getSuperClass(); } while (node != null); return false; } public MethodNode tryFindPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } else return null; MethodNode res = null; ClassNode node = this; TupleExpression args = (TupleExpression) arguments; do { for (MethodNode method : node.getMethods(name)) { if (method.getParameters().length == count) { boolean match = true; for (int i = 0; i != count; ++i) if (!args.getType().isDerivedFrom(method.getParameters()[i].getType())) { match = false; break; } if (match) { if (res == null) res = method; else { if (res.getParameters().length != count) return null; if (node.equals(this)) return null; match = true; for (int i = 0; i != count; ++i) if (!res.getParameters()[i].getType().equals(method.getParameters()[i].getType())) { match = false; break; } if (!match) return null; } } } } node = node.getSuperClass(); } while (node != null); return res; } /** * Returns true if the given method has a possibly matching static method with the given name and arguments. * * @param name the name of the method of interest * @param arguments the arguments to match against * @return true if a matching method was found */ public boolean hasPossibleStaticMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } else if (arguments instanceof MapExpression) { count = 1; } for (MethodNode method : getMethods(name)) { if(method.isStatic()) { Parameter[] parameters = method.getParameters(); if (parameters.length == count) return true; // handle varargs case if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) { if (count >= parameters.length - 1) return true; } // handle parameters with default values int nonDefaultParameters = 0; for (Parameter parameter : parameters) { if (!parameter.hasInitialExpression()) { nonDefaultParameters++; } } if (count < parameters.length && nonDefaultParameters <= count) { return true; } } } return false; } public boolean isInterface(){ return (getModifiers() & Opcodes.ACC_INTERFACE) > 0; } public boolean isResolved(){ return redirect().clazz!=null || (componentType != null && componentType.isResolved()); } public boolean isArray(){ return componentType!=null; } public ClassNode getComponentType() { return componentType; } /** * Returns the concrete class this classnode relates to. However, this method * is inherently unsafe as it may return null depending on the compile phase you are * using. AST transformations should never use this method directly, but rather obtain * a new class node using {@link #getPlainNodeReference()}. * @return the class this classnode relates to. May return null. */ public Class getTypeClass(){ Class c = redirect().clazz; if (c!=null) return c; ClassNode component = redirect().componentType; if (component!=null && component.isResolved()){ ClassNode cn = component.makeArray(); setRedirect(cn); return redirect().clazz; } throw new GroovyBugError("ClassNode#getTypeClass for "+getName()+" is called before the type class is set "); } public boolean hasPackageName(){ return redirect().name.indexOf('.')>0; } /** * Marks if the current class uses annotations or not * @param flag */ public void setAnnotated(boolean flag) { this.annotated = flag; } public boolean isAnnotated() { return this.annotated; } public GenericsType[] getGenericsTypes() { return genericsTypes; } public void setGenericsTypes(GenericsType[] genericsTypes) { usesGenerics = usesGenerics || genericsTypes!=null; this.genericsTypes = genericsTypes; } public void setGenericsPlaceHolder(boolean b) { usesGenerics = usesGenerics || b; placeholder = b; } public boolean isGenericsPlaceHolder() { return placeholder; } public boolean isUsingGenerics() { return usesGenerics; } public void setUsingGenerics(boolean b) { usesGenerics = b; } public ClassNode getPlainNodeReference() { if (ClassHelper.isPrimitiveType(this)) return this; ClassNode n = new ClassNode(getName(),getModifiers(),getSuperClass(),null,null); n.isPrimaryNode = false; n.setRedirect(redirect()); n.componentType = redirect().getComponentType(); return n; } public boolean isAnnotationDefinition() { return redirect().isPrimaryNode && isInterface() && (getModifiers() & Opcodes.ACC_ANNOTATION)!=0; } public List getAnnotations() { if (redirect!=null) return redirect.getAnnotations(); lazyClassInit(); return super.getAnnotations(); } public List getAnnotations(ClassNode type) { if (redirect!=null) return redirect.getAnnotations(type); lazyClassInit(); return super.getAnnotations(type); } public void addTransform(Class transform, ASTNode node) { GroovyASTTransformation annotation = transform.getAnnotation(GroovyASTTransformation.class); Set nodes = getTransformInstances().get(annotation.phase()).get(transform); if (nodes == null) { nodes = new LinkedHashSet(); getTransformInstances().get(annotation.phase()).put(transform, nodes); } nodes.add(node); } public Map, Set> getTransforms(CompilePhase phase) { return getTransformInstances().get(phase); } public void renameField(String oldName, String newName) { ClassNode r = redirect (); if (r.fieldIndex == null) r.fieldIndex = new HashMap (); final Map index = r.fieldIndex; index.put(newName, index.remove(oldName)); } public void removeField(String oldName) { ClassNode r = redirect (); if (r.fieldIndex == null) r.fieldIndex = new HashMap (); final Map index = r.fieldIndex; r.fields.remove(index.get(oldName)); index.remove(oldName); } public boolean isEnum() { return (getModifiers()&Opcodes.ACC_ENUM) != 0; } /** * @return iterator of inner classes defined inside this one */ public Iterator getInnerClasses() { return (innerClasses == null ? Collections.emptyList() : innerClasses).iterator(); } private Map, Set>> getTransformInstances() { if(transformInstances == null){ transformInstances = new EnumMap, Set>>(CompilePhase.class); for (CompilePhase phase : CompilePhase.values()) { transformInstances.put(phase, new HashMap, Set>()); } } return transformInstances; } public boolean isRedirectNode() { return redirect!=null; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ModuleNode.java0000644001501200150120000003621211715031256023505 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import groovy.lang.Binding; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.InvokerHelper; import org.objectweb.asm.Opcodes; import java.io.File; import java.util.*; /** * Represents a module, which consists typically of a class declaration * but could include some imports, some statements and multiple classes * intermixed with statements like scripts in Python or Ruby * * @author Jochen Theodorou * @author Paul King * @author James Strachan */ public class ModuleNode extends ASTNode implements Opcodes { private BlockStatement statementBlock = new BlockStatement(); List classes = new LinkedList(); private List methods = new ArrayList(); private Map imports = new HashMap(); private List starImports = new ArrayList(); private Map staticImports = new LinkedHashMap(); private Map staticStarImports = new LinkedHashMap(); private CompileUnit unit; private PackageNode packageNode; private String description; private boolean createClassForStatements = true; private transient SourceUnit context; private boolean importsResolved = false; private ClassNode scriptDummy; private String mainClassName = null; public ModuleNode (SourceUnit context ) { this.context = context; } public ModuleNode (CompileUnit unit) { this.unit = unit; } public BlockStatement getStatementBlock() { return statementBlock; } public List getMethods() { return methods; } public List getClasses() { if (createClassForStatements && (!statementBlock.isEmpty() || !methods.isEmpty() || isPackageInfo())) { ClassNode mainClass = createStatementsClass(); mainClassName = mainClass.getName(); createClassForStatements = false; classes.add(0, mainClass); mainClass.setModule(this); addToCompileUnit(mainClass); } return classes; } private boolean isPackageInfo() { return context != null && context.getName() != null && context.getName().endsWith("package-info.groovy"); } public List getImports() { return new ArrayList(imports.values()); } public List getStarImports() { return starImports; } /** * @param alias the name of interest * @return the class node for the given alias or null if none is available */ public ClassNode getImportType(String alias) { ImportNode importNode = imports.get(alias); return importNode == null ? null : importNode.getType(); } /** * @param alias the name of interest * @return the import node for the given alias or null if none is available */ public ImportNode getImport(String alias) { return imports.get(alias); } public void addImport(String alias, ClassNode type) { addImport(alias, type, new ArrayList()); } public void addImport(String alias, ClassNode type, List annotations) { ImportNode importNode = new ImportNode(type, alias); imports.put(alias, importNode); importNode.addAnnotations(annotations); } public void addStarImport(String packageName) { addStarImport(packageName, new ArrayList()); } public void addStarImport(String packageName, List annotations) { ImportNode importNode = new ImportNode(packageName); importNode.addAnnotations(annotations); starImports.add(importNode); } public void addStatement(Statement node) { statementBlock.addStatement(node); } public void addClass(ClassNode node) { if(classes.isEmpty()) mainClassName = node.getName(); classes.add(node); node.setModule(this); addToCompileUnit(node); } private void addToCompileUnit(ClassNode node) { // register the new class with the compile unit if (unit != null) { unit.addClass(node); } } public void addMethod(MethodNode node) { methods.add(node); } public void visit(GroovyCodeVisitor visitor) { } public String getPackageName() { return packageNode == null ? null : packageNode.getName(); } public PackageNode getPackage() { return packageNode; } // TODO don't allow override? public void setPackage(PackageNode packageNode) { this.packageNode = packageNode; } // TODO don't allow override? public void setPackageName(String packageName) { this.packageNode = new PackageNode(packageName); } public boolean hasPackageName(){ return packageNode != null && packageNode.getName() != null; } public boolean hasPackage(){ return this.packageNode != null; } public SourceUnit getContext() { return context; } /** * @return the underlying character stream description */ public String getDescription() { if( context != null ) { return context.getName(); } else { return this.description; } } public void setDescription(String description) { // DEPRECATED -- context.getName() is now sufficient // TODO add deprecated annotation or javadoc comment? this.description = description; } public CompileUnit getUnit() { return unit; } void setUnit(CompileUnit unit) { this.unit = unit; } public ClassNode getScriptClassDummy() { if (scriptDummy!=null) { setScriptBaseClassFromConfig(scriptDummy); return scriptDummy; } String name = getPackageName(); if (name == null) { name = ""; } // now let's use the file name to determine the class name if (getDescription() == null) { throw new RuntimeException("Cannot generate main(String[]) class for statements when we have no file description"); } name += extractClassFromFileDescription(); ClassNode classNode; if (isPackageInfo()) { classNode = new ClassNode(name, ACC_ABSTRACT | ACC_INTERFACE, ClassHelper.OBJECT_TYPE); } else { classNode = new ClassNode(name, ACC_PUBLIC, ClassHelper.SCRIPT_TYPE); setScriptBaseClassFromConfig(classNode); classNode.setScript(true); classNode.setScriptBody(true); } scriptDummy = classNode; return classNode; } private void setScriptBaseClassFromConfig(ClassNode cn) { if (unit != null) { String baseClassName = unit.getConfig().getScriptBaseClass(); if(baseClassName != null) { if(!cn.getSuperClass().getName().equals(baseClassName)) { cn.setSuperClass(ClassHelper.make(baseClassName)); } } } } protected ClassNode createStatementsClass() { ClassNode classNode = getScriptClassDummy(); if (classNode.getName().endsWith("package-info")) { return classNode; } handleMainMethodIfPresent(methods); // return new Foo(new ShellContext(args)).run() classNode.addMethod( new MethodNode( "main", ACC_PUBLIC | ACC_STATIC, ClassHelper.VOID_TYPE, new Parameter[] { new Parameter(ClassHelper.STRING_TYPE.makeArray(), "args")}, ClassNode.EMPTY_ARRAY, new ExpressionStatement( new MethodCallExpression( new ClassExpression(ClassHelper.make(InvokerHelper.class)), "runScript", new ArgumentListExpression( new ClassExpression(classNode), new VariableExpression("args")))))); classNode.addMethod( new MethodNode("run", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, statementBlock)); classNode.addConstructor(ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new BlockStatement()); Statement stmt = new ExpressionStatement( new MethodCallExpression( new VariableExpression("super"), "setBinding", new ArgumentListExpression( new VariableExpression("context")))); classNode.addConstructor( ACC_PUBLIC, new Parameter[] { new Parameter(ClassHelper.make(Binding.class), "context")}, ClassNode.EMPTY_ARRAY, stmt); for (MethodNode node : methods) { int modifiers = node.getModifiers(); if ((modifiers & ACC_ABSTRACT) != 0) { throw new RuntimeException( "Cannot use abstract methods in a script, they are only available inside classes. Method: " + node.getName()); } // br: the old logic seems to add static to all def f().... in a script, which makes enclosing // inner classes (including closures) in a def function difficult. Comment it out. node.setModifiers(modifiers /*| ACC_STATIC*/); classNode.addMethod(node); } return classNode; } /* * If a main method is provided by user, account for it under run() as scripts generate their own 'main' so they can run. */ private void handleMainMethodIfPresent(List methods) { boolean found = false; for (Iterator iter = methods.iterator(); iter.hasNext();) { MethodNode node = (MethodNode) iter.next(); if(node.getName().equals("main")) { int modifiers = node.getModifiers(); if (node.isStatic() && node.getParameters().length == 1) { boolean retTypeMatches, argTypeMatches; ClassNode argType = node.getParameters()[0].getType(); ClassNode retType = node.getReturnType(); argTypeMatches = (argType.equals(ClassHelper.OBJECT_TYPE) || argType.getName().contains("String[]")); retTypeMatches = (retType == ClassHelper.VOID_TYPE || retType == ClassHelper.OBJECT_TYPE); if(retTypeMatches && argTypeMatches) { if(found) { throw new RuntimeException("Repetitive main method found."); } else { found = true; } // if script has both loose statements as well as main(), then main() is ignored if(statementBlock.isEmpty()) { addStatement(node.getCode()); } iter.remove(); } } } } } protected String extractClassFromFileDescription() { // let's strip off everything after the last '.' String answer = getDescription(); int slashIdx = answer.lastIndexOf('/'); int separatorIdx = answer.lastIndexOf(File.separatorChar); int dotIdx = answer.lastIndexOf('.'); if (dotIdx > 0 && dotIdx > Math.max(slashIdx, separatorIdx)) { answer = answer.substring(0, dotIdx); } // new let's strip everything up to and including the path separators if (slashIdx >= 0) { answer = answer.substring(slashIdx + 1); } // recalculate in case we have already done some stripping separatorIdx = answer.lastIndexOf(File.separatorChar); if (separatorIdx >= 0) { answer = answer.substring(separatorIdx + 1); } return answer; } public boolean isEmpty() { return classes.isEmpty() && statementBlock.getStatements().isEmpty(); } public void sortClasses(){ if (isEmpty()) return; List classes = getClasses(); LinkedList sorted = new LinkedList(); int level=1; while (!classes.isEmpty()) { for (Iterator cni = classes.iterator(); cni.hasNext();) { ClassNode cn = cni.next(); ClassNode sn = cn; for (int i=0; sn!=null && i getStaticImports() { return staticImports; } public Map getStaticStarImports() { return staticStarImports; } public void addStaticImport(ClassNode type, String fieldName, String alias) { addStaticImport(type, fieldName, alias, new ArrayList()); } public void addStaticImport(ClassNode type, String fieldName, String alias, List annotations) { ImportNode node = new ImportNode(type, fieldName, alias); node.addAnnotations(annotations); staticImports.put(alias, node); } public void addStaticStarImport(String name, ClassNode type) { addStaticStarImport(name, type, new ArrayList()); } public void addStaticStarImport(String name, ClassNode type, List annotations) { ImportNode node = new ImportNode(type); node.addAnnotations(annotations); staticStarImports.put(name, node); } public String getMainClassName() { return mainClassName; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/MethodNode.java0000644001501200150120000002007611715031256023501 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.objectweb.asm.Opcodes; import java.lang.reflect.Modifier; import java.util.List; /** * Represents a method declaration * * @author James Strachan * @author Hamlet D'Arcy * @version $Revision$ */ public class MethodNode extends AnnotatedNode implements Opcodes { private final String name; private int modifiers; private boolean syntheticPublic; private ClassNode returnType; private Parameter[] parameters; private boolean hasDefaultValue = false; private Statement code; private boolean dynamicReturnType; private VariableScope variableScope; private final ClassNode[] exceptions; private final boolean staticConstructor; // type spec for generics private GenericsType[] genericsTypes = null; private boolean hasDefault; // cached data String typeDescriptor; public MethodNode(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { this.name = name; this.modifiers = modifiers; this.code = code; setReturnType(returnType); VariableScope scope = new VariableScope(); setVariableScope(scope); setParameters(parameters); this.hasDefault = false; this.exceptions = exceptions; this.staticConstructor = (name != null && name.equals("")); } /** * The type descriptor for a method node is a string containing the name of the method, its return type, * and its parameter types in a canonical form. For simplicity, I'm using the format of a Java declaration * without parameter names. * * @return the type descriptor */ public String getTypeDescriptor() { if (typeDescriptor == null) { StringBuffer buf = new StringBuffer(name.length() + parameters.length * 10); buf.append(returnType.getName()); buf.append(' '); buf.append(name); buf.append('('); for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); } Parameter param = parameters[i]; buf.append(param.getType().getName()); } buf.append(')'); typeDescriptor = buf.toString(); } return typeDescriptor; } private void invalidateCachedData() { typeDescriptor = null; } public boolean isVoidMethod() { return returnType == ClassHelper.VOID_TYPE; } public Statement getCode() { return code; } public void setCode(Statement code) { this.code = code; } public int getModifiers() { return modifiers; } public void setModifiers(int modifiers) { invalidateCachedData(); this.modifiers = modifiers; } public String getName() { return name; } public Parameter[] getParameters() { return parameters; } public void setParameters(Parameter[] parameters) { invalidateCachedData(); VariableScope scope = new VariableScope(); this.parameters = parameters; if (parameters != null && parameters.length > 0) { for (Parameter para : parameters) { if (para.hasInitialExpression()) { this.hasDefaultValue = true; } para.setInStaticContext(isStatic()); scope.putDeclaredVariable(para); } } setVariableScope(scope); } public ClassNode getReturnType() { return returnType; } public VariableScope getVariableScope() { return variableScope; } public void setVariableScope(VariableScope variableScope) { this.variableScope = variableScope; variableScope.setInStaticContext(isStatic()); } public boolean isDynamicReturnType() { return dynamicReturnType; } public boolean isAbstract() { return (modifiers & ACC_ABSTRACT) != 0; } public boolean isStatic() { return (modifiers & ACC_STATIC) != 0; } public boolean isPublic() { return (modifiers & ACC_PUBLIC) != 0; } public boolean isPrivate() { return (modifiers & ACC_PRIVATE) != 0; } public boolean isProtected() { return (modifiers & ACC_PROTECTED) != 0; } public boolean hasDefaultValue() { return this.hasDefaultValue; } /** * @return true if this method is the run method from a script */ public boolean isScriptBody() { return getDeclaringClass() != null && getDeclaringClass().isScript() && getName().equals("run") && getColumnNumber() == -1; } public String toString() { return "MethodNode@" + hashCode() + "[" + getTypeDescriptor() + "]"; } public void setReturnType(ClassNode returnType) { invalidateCachedData(); dynamicReturnType |= ClassHelper.DYNAMIC_TYPE == returnType; this.returnType = returnType; if (returnType == null) this.returnType = ClassHelper.OBJECT_TYPE; } public ClassNode[] getExceptions() { return exceptions; } public Statement getFirstStatement() { if (code == null) return null; Statement first = code; while (first instanceof BlockStatement) { List list = ((BlockStatement) first).getStatements(); if (list.isEmpty()) { first = null; } else { first = list.get(0); } } return first; } public GenericsType[] getGenericsTypes() { return genericsTypes; } public void setGenericsTypes(GenericsType[] genericsTypes) { invalidateCachedData(); this.genericsTypes = genericsTypes; } public void setAnnotationDefault(boolean b) { this.hasDefault = b; } public boolean hasAnnotationDefault() { return hasDefault; } public boolean isStaticConstructor() { return staticConstructor; } /** * Indicates that this method has been "promoted" to public by * Groovy when in fact there was no public modifier explicitly * in the source code. I.e. it remembers that it has applied * Groovy's "public methods by default" rule. This property is * typically only of interest to AST transform writers. * * @return true if this class is public but had no explicit public modifier */ public boolean isSyntheticPublic() { return syntheticPublic; } public void setSyntheticPublic(boolean syntheticPublic) { this.syntheticPublic = syntheticPublic; } /** * Provides a nicely formatted string of the method definition. For simplicity, generic types on some of the elements * are not displayed. * @return * string form of node with some generic elements suppressed */ @Override public String getText() { String retType = AstToTextHelper.getClassText(returnType); String exceptionTypes = AstToTextHelper.getThrowsClauseText(exceptions); String parms = AstToTextHelper.getParametersText(parameters); return AstToTextHelper.getModifiersText(modifiers) + " " + retType + " " + name + "(" + parms + ") " + exceptionTypes + " { ... }"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/PackageNode.java0000644001501200150120000000222611627206700023611 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; /** * Represents a package in the AST. * * @author Paul King */ public class PackageNode extends AnnotatedNode { private String name; public PackageNode(String name) { this.name = name; } public String getName() { return name; } /** * @return the text display of this package definition */ public String getText() { return "package " + name; } public void visit(GroovyCodeVisitor visitor) { } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/DynamicVariable.java0000644001501200150120000000354011707612044024503 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.Expression; // An implicitly created variable, such as a variable in a script that's doesn't have an explicit // declaration, or the "it" argument to a closure. public class DynamicVariable implements Variable { private String name; private boolean closureShare = false; private boolean staticContext = false; public DynamicVariable(String name, boolean context) { this.name = name; staticContext = context; } public ClassNode getType() { return ClassHelper.DYNAMIC_TYPE; } public String getName() { return name; } public Expression getInitialExpression() { return null; } public boolean hasInitialExpression() { return false; } public boolean isInStaticContext() { return staticContext; } public boolean isDynamicTyped() { return true; } public boolean isClosureSharedVariable() { return closureShare; } public void setClosureSharedVariable(boolean inClosure) { closureShare = inClosure; } public int getModifiers() { return 0; } public ClassNode getOriginType() { return getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/GenericsType.java0000644001501200150120000001027711715031256024056 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.HashSet; import java.util.Set; /** * This class is used to describe generic type signatures for ClassNodes. * * @author Jochen Theodorou * @see ClassNode */ public class GenericsType extends ASTNode { private final ClassNode[] upperBounds; private final ClassNode lowerBound; private ClassNode type; private String name; private boolean placeholder; private boolean resolved; private boolean wildcard; public GenericsType(ClassNode type, ClassNode[] upperBounds, ClassNode lowerBound) { this.type = type; this.name = type.isGenericsPlaceHolder() ? type.getUnresolvedName() : type.getName(); this.upperBounds = upperBounds; this.lowerBound = lowerBound; placeholder = type.isGenericsPlaceHolder(); resolved = false; } public GenericsType(ClassNode basicType) { this(basicType, null, null); } public ClassNode getType() { return type; } public void setType(ClassNode type) { this.type = type; } public String toString() { Set visited = new HashSet(); return toString(visited); } private String toString(Set visited) { if (placeholder) visited.add(name); String ret = (type == null || placeholder || wildcard) ? name : genericsBounds(type, visited); if (upperBounds != null) { ret += " extends "; for (int i = 0; i < upperBounds.length; i++) { ret += genericsBounds(upperBounds[i], visited); if (i + 1 < upperBounds.length) ret += " & "; } } else if (lowerBound != null) { ret += " super " + genericsBounds(lowerBound, visited); } return ret; } private String genericsBounds(ClassNode theType, Set visited) { String ret = theType.isArray()?theType.getComponentType().getName()+"[]":theType.getName(); GenericsType[] genericsTypes = theType.getGenericsTypes(); if (genericsTypes == null || genericsTypes.length == 0) return ret; // TODO instead of catching Object here stop it from being placed into type in first place if (genericsTypes.length == 1 && genericsTypes[0].isPlaceholder() && theType.getName().equals("java.lang.Object")) { return genericsTypes[0].getName(); } ret += "<"; for (int i = 0; i < genericsTypes.length; i++) { if (i != 0) ret += ", "; GenericsType type = genericsTypes[i]; if (type.isPlaceholder() && visited.contains(type.getName())) { ret += type.getName(); } else { ret += type.toString(visited); } } ret += ">"; return ret; } public ClassNode[] getUpperBounds() { return upperBounds; } public String getName() { return name; } public boolean isPlaceholder() { return placeholder; } public void setPlaceholder(boolean placeholder) { this.placeholder = placeholder; type.setGenericsPlaceHolder(placeholder); } public boolean isResolved() { return resolved || placeholder; } public void setResolved(boolean res) { resolved = res; } public void setName(String name) { this.name = name; } public boolean isWildcard() { return wildcard; } public void setWildcard(boolean wildcard) { this.wildcard = wildcard; } public ClassNode getLowerBound() { return lowerBound; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/Parameter.java0000644001501200150120000000661711707612044023401 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.*; /** * Represents a parameter on a constructor or method call. The type name is * optional - it defaults to java.lang.Object if unknown. * * @author James Strachan * @version $Revision$ */ public class Parameter extends AnnotatedNode implements Variable { public static final Parameter[] EMPTY_ARRAY = { }; private ClassNode type; private final String name; private boolean dynamicTyped; private Expression defaultValue; private boolean hasDefaultValue; private boolean inStaticContext; private boolean closureShare=false; private int modifiers; private ClassNode originType=ClassHelper.DYNAMIC_TYPE; public Parameter(ClassNode type, String name) { this.name = name; this.setType(type); this.originType = type; this.hasDefaultValue = false; } public Parameter(ClassNode type, String name, Expression defaultValue) { this(type,name); this.defaultValue = defaultValue; this.hasDefaultValue = defaultValue != null; } public String toString() { return super.toString() + "[name:" + name + ((type == null) ? "" : " type: " + type.getName()) + ", hasDefaultValue: " + this.hasInitialExpression() + "]"; } public String getName() { return name; } public ClassNode getType() { return type; } public void setType(ClassNode type) { this.type = type; dynamicTyped |= type==ClassHelper.DYNAMIC_TYPE; } public boolean hasInitialExpression() { return this.hasDefaultValue; } /** * @return the default value expression for this parameter or null if * no default value is specified */ public Expression getInitialExpression() { return defaultValue; } public void setInitialExpression(Expression init) { defaultValue = init; hasDefaultValue = defaultValue != null; } public boolean isInStaticContext() { return inStaticContext; } public void setInStaticContext(boolean inStaticContext) { this.inStaticContext = inStaticContext; } public boolean isDynamicTyped() { return dynamicTyped; } public boolean isClosureSharedVariable() { return closureShare; } public void setClosureSharedVariable(boolean inClosure) { closureShare = inClosure; } public int getModifiers() { return modifiers; } public ClassNode getOriginType() { return originType; } public void setOriginType(ClassNode cn) { originType = cn; } public void setModifiers(int modifiers) { this.modifiers = modifiers; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/0000755001501200150120000000000011715031256021561 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ArgumentListExpression.java0000644001501200150120000000445611715031256027133 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Parameter; /** * Represents one or more arguments being passed into a method * * @author James Strachan * @version $Revision$ */ public class ArgumentListExpression extends TupleExpression { public static final Object[] EMPTY_ARRAY = { }; public static final ArgumentListExpression EMPTY_ARGUMENTS = new ArgumentListExpression(); public ArgumentListExpression() { } public ArgumentListExpression(List expressions) { super(expressions); } public ArgumentListExpression(Expression[] expressions) { super(expressions); } public ArgumentListExpression(Parameter[] parameters) { for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; addExpression(new VariableExpression(parameter.getName())); } } public ArgumentListExpression(Expression expr) { super(expr); } public ArgumentListExpression(Expression expr1, Expression expr2) { super(expr1, expr2); } public ArgumentListExpression(Expression expr1, Expression expr2, Expression expr3) { super(expr1, expr2, expr3); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new ArgumentListExpression(transformExpressions(getExpressions(), transformer)); ret.setSourcePosition(this); return ret; } public void visit(GroovyCodeVisitor visitor) { visitor.visitArgumentlistExpression(this); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/TernaryExpression.java0000644001501200150120000000515711715031256026140 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a ternary expression (booleanExpression) ? expression : expression * * @author James Strachan * @version $Revision$ */ public class TernaryExpression extends Expression { private BooleanExpression booleanExpression; private Expression trueExpression; private Expression falseExpression; public TernaryExpression( BooleanExpression booleanExpression, Expression trueExpression, Expression falseExpression) { this.booleanExpression = booleanExpression; this.trueExpression = trueExpression; this.falseExpression = falseExpression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitTernaryExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new TernaryExpression( (BooleanExpression) transformer.transform(booleanExpression), transformer.transform(trueExpression), transformer.transform(falseExpression)); ret.setSourcePosition(this); return ret; } public String toString() { return super.toString() +"[" + booleanExpression + " ? " + trueExpression + " : " + falseExpression + "]"; } public BooleanExpression getBooleanExpression() { return booleanExpression; } public Expression getFalseExpression() { return falseExpression; } public Expression getTrueExpression() { return trueExpression; } public String getText() { return "(" + booleanExpression.getText() + ") ? " + trueExpression.getText() + " : " + falseExpression.getText(); } public ClassNode getType() { return ClassHelper.OBJECT_TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/SpreadExpression.java0000644001501200150120000000311211715031256025717 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a spread expression *x in the list expression [1, *x, 2]. * * @version $Revision$ */ public class SpreadExpression extends Expression { private final Expression expression; public SpreadExpression(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitSpreadExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new SpreadExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return "*" + expression.getText(); } public ClassNode getType() { return expression.getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/AttributeExpression.java0000644001501200150120000000327011715031256026451 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents an attribute access (accessing the field of a class) such as the expression "foo.@bar". * * @author James Strachan * @version $Revision$ */ public class AttributeExpression extends PropertyExpression { public AttributeExpression(Expression objectExpression, Expression property) { super(objectExpression, property, false); } public AttributeExpression(Expression objectExpression, Expression property, boolean safe) { super(objectExpression, property, safe); } public void visit(GroovyCodeVisitor visitor) { visitor.visitAttributeExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { AttributeExpression ret = new AttributeExpression(transformer.transform(getObjectExpression()),transformer.transform(getProperty()),isSafe()); ret.setSourcePosition(this); ret.setSpreadSafe(isSpreadSafe()); return ret; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/NamedArgumentListExpression.java0000644001501200150120000000262311715031256030072 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.List; /** * Represents one or more arguments being passed into a method by name * * @author James Strachan * @version $Revision$ */ public class NamedArgumentListExpression extends MapExpression { public NamedArgumentListExpression() { } public NamedArgumentListExpression(List mapEntryExpressions) { super(mapEntryExpressions); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new NamedArgumentListExpression( transformExpressions(getMapEntryExpressions(), transformer, MapEntryExpression.class)); ret.setSourcePosition(this); return ret; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/MethodPointerExpression.java0000644001501200150120000000513011715031256027264 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import groovy.lang.Closure; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a method pointer on an object such as * foo.&bar which means find the method pointer on foo for the method called "bar" * which is equivalent to * * foo.metaClass.getMethodPointer(foo, "bar") * * @version $Revision$ */ public class MethodPointerExpression extends Expression { private Expression expression; private Expression methodName; public MethodPointerExpression(Expression expression, Expression methodName) { this.expression = expression; this.methodName = methodName; } public Expression getExpression() { if (expression == null) return VariableExpression.THIS_EXPRESSION; else return expression; } public Expression getMethodName() { return methodName; } public void visit(GroovyCodeVisitor visitor) { visitor.visitMethodPointerExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret; Expression mname = transformer.transform(methodName); if (expression == null) { ret = new MethodPointerExpression(VariableExpression.THIS_EXPRESSION, mname); } else { ret = new MethodPointerExpression(transformer.transform(expression), mname); } ret.setSourcePosition(this); return ret; } public String getText() { if (expression == null) { return "&" + methodName; } else { return expression.getText() + ".&" + methodName.getText(); } } public ClassNode getType() { return ClassHelper.CLOSURE_TYPE.getPlainNodeReference(); } public boolean isDynamic() { return false; } public Class getTypeClass() { return Closure.class; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/UnaryMinusExpression.java0000644001501200150120000000310011715031256026610 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * @author sam */ public class UnaryMinusExpression extends Expression { private final Expression expression; public UnaryMinusExpression(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitUnaryMinusExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new UnaryMinusExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return expression.getText(); } public ClassNode getType() { return expression.getType(); } public boolean isDynamic() { return false; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/Expression.java0000644001501200150120000000545311627206700024572 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.GroovyBugError; /** * Represents a base class for expressions which evaluate as an object * * @author James Strachan * @version $Revision$ */ public abstract class Expression extends AnnotatedNode { private ClassNode type=ClassHelper.DYNAMIC_TYPE; /** * Return a copy of the expression calling the transformer on any nested expressions * @param transformer */ public abstract Expression transformExpression(ExpressionTransformer transformer); /** * Transforms the list of expressions * @return a new list of transformed expressions */ protected List transformExpressions(List expressions, ExpressionTransformer transformer) { List list = new ArrayList(expressions.size()); for (Expression expr : expressions ) { list.add(transformer.transform(expr)); } return list; } /** * Transforms the list of expressions, and checks that all transformed expressions have the given type. * * @return a new list of transformed expressions */ protected List transformExpressions(List expressions, ExpressionTransformer transformer, Class transformedType) { List list = new ArrayList(expressions.size()); for (Expression expr : expressions) { Expression transformed = transformer.transform(expr); if (!transformedType.isInstance(transformed)) throw new GroovyBugError(String.format("Transformed expression should have type %s but has type %s", transformedType, transformed.getClass())); list.add(transformedType.cast(transformed)); } return list; } public ClassNode getType() { return type; } public void setType(ClassNode t) { type=t; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/CastExpression.java0000644001501200150120000000506211715031256025401 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a type cast expression * * @author James Strachan * @version $Revision$ */ public class CastExpression extends Expression { private final Expression expression; private boolean ignoreAutoboxing=false; private boolean coerce = false; public static CastExpression asExpression(ClassNode type, Expression expression) { CastExpression answer = new CastExpression(type, expression); answer.setCoerce(true); return answer; } public CastExpression(ClassNode type, Expression expression) { this(type,expression,false); } public CastExpression(ClassNode type, Expression expression, boolean ignoreAutoboxing) { super.setType(type); this.expression = expression; this.ignoreAutoboxing = ignoreAutoboxing; } public boolean isIgnoringAutoboxing(){ return ignoreAutoboxing; } public boolean isCoerce() { return coerce; } public void setCoerce(boolean coerce) { this.coerce = coerce; } public String toString() { return super.toString() +"[(" + getType().getName() + ") " + expression + "]"; } public void visit(GroovyCodeVisitor visitor) { visitor.visitCastExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { CastExpression ret = new CastExpression(getType(), transformer.transform(expression)); ret.setSourcePosition(this); ret.setCoerce(this.isCoerce()); return ret; } public String getText() { return "(" + getType() + ") " + expression.getText(); } public Expression getExpression() { return expression; } public void setType(ClassNode t) { super.setType(t); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/MethodCallExpression.java0000644001501200150120000001503611715031256026525 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import groovy.lang.MetaMethod; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.MethodNode; /** * A method call on an object or class * * @author James Strachan * @version $Revision$ */ public class MethodCallExpression extends Expression { private Expression objectExpression; private Expression method; private Expression arguments; private boolean spreadSafe = false; private boolean safe = false; private boolean implicitThis; // type spec for generics private GenericsType[] genericsTypes = null; private boolean usesGenerics = false; private MethodNode target; public static final Expression NO_ARGUMENTS = new TupleExpression(); /** * @deprecated */ public MetaMethod getMetaMethod() { return null; } public MethodCallExpression(Expression objectExpression, String method, Expression arguments) { this(objectExpression,new ConstantExpression(method),arguments); } public MethodCallExpression(Expression objectExpression, Expression method, Expression arguments) { this.objectExpression = objectExpression; this.method = method; if (!(arguments instanceof TupleExpression)){ this.arguments = new TupleExpression(arguments); } else { this.arguments = arguments; } //TODO: set correct type here // if setting type and a methodcall is the last expression in a method, // then the method will return null if the method itself is not void too! // (in bytecode after call: aconst_null, areturn) this.setType(ClassHelper.DYNAMIC_TYPE); this.setImplicitThis(true); } public void visit(GroovyCodeVisitor visitor) { visitor.visitMethodCallExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { MethodCallExpression answer = new MethodCallExpression(transformer.transform(objectExpression), transformer.transform(method), transformer.transform(arguments)); answer.setSafe(safe); answer.setSpreadSafe(spreadSafe); answer.setImplicitThis(implicitThis); answer.setSourcePosition(this); answer.setMethodTarget(target); return answer; } public Expression getArguments() { return arguments; } public void setArguments(Expression arguments) { if (!(arguments instanceof TupleExpression)){ this.arguments = new TupleExpression(arguments); } else { this.arguments = arguments; } } public Expression getMethod() { return method; } public void setMethod(Expression method) { this.method = method; } /** * This method returns the method name as String if it is no dynamic * calculated method name, but a constant. */ public String getMethodAsString() { if (! (method instanceof ConstantExpression)) return null; ConstantExpression constant = (ConstantExpression) method; return constant.getText(); } public void setObjectExpression(Expression objectExpression) { this.objectExpression = objectExpression; } public Expression getObjectExpression() { return objectExpression; } public String getText() { String object = objectExpression.getText(); String meth = method.getText(); String args = arguments.getText(); String spread = spreadSafe ? "*" : ""; String dereference = safe ? "?" : ""; return object + spread + dereference + "." + meth + args; } /** * @return is this a safe method call, i.e. if true then if the source object is null * then this method call will return null rather than throwing a null pointer exception */ public boolean isSafe() { return safe; } public void setSafe(boolean safe) { this.safe = safe; } public boolean isSpreadSafe() { return spreadSafe; } public void setSpreadSafe(boolean value) { spreadSafe = value; } /** * @return true if no object expression was specified otherwise if * some expression was specified for the object on which to evaluate * the method then return false */ public boolean isImplicitThis() { return implicitThis; } public void setImplicitThis(boolean implicitThis) { this.implicitThis = implicitThis; } public String toString() { return super.toString() + "[object: " + objectExpression + " method: " + method + " arguments: " + arguments + "]"; } /** * @deprecated */ public void setMetaMethod(MetaMethod mmeth) { //this.metaMethod = mmeth; //super.setType(ClassHelper.make(mmeth.getReturnType())); } public GenericsType[] getGenericsTypes() { return genericsTypes; } public void setGenericsTypes(GenericsType[] genericsTypes) { usesGenerics = usesGenerics || genericsTypes != null; this.genericsTypes = genericsTypes; } public boolean isUsingGenerics() { return usesGenerics; } /** * Sets a method call target for a direct method call. * WARNING: A method call made this way will run outside of the MOP! * @param mn the target as MethodNode, mn==null means no target */ public void setMethodTarget(MethodNode mn) { this.target = mn; if (mn!=null) { setType(target.getReturnType()); } else { setType(ClassHelper.OBJECT_TYPE); } } /** * @return the target as method node if set */ public MethodNode getMethodTarget() { return target; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/BitwiseNegationExpression.java0000644001501200150120000000302011715031256027572 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * @author phk */ public class BitwiseNegationExpression extends Expression { private Expression expression; public BitwiseNegationExpression(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitBitwiseNegationExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new BitwiseNegationExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return expression.getText(); } public ClassNode getType() { return expression.getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/PrefixExpression.java0000644001501200150120000000406211715031256025743 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.syntax.Token; /** * Represents a prefix expression like ++foo or --bar * * @author James Strachan * @version $Revision$ */ public class PrefixExpression extends Expression { private Token operation; private Expression expression; public PrefixExpression(Token operation, Expression expression) { this.operation = operation; this.expression = expression; } public String toString() { return super.toString() + "[" + operation + expression + "]"; } public void visit(GroovyCodeVisitor visitor) { visitor.visitPrefixExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new PrefixExpression(operation, transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public void setExpression(Expression expression) { this.expression = expression; } public Token getOperation() { return operation; } public Expression getExpression() { return expression; } public String getText() { return "(" + operation.getText() + expression.getText() + ")"; } public ClassNode getType() { return expression.getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/PropertyExpression.java0000644001501200150120000000743111715031256026335 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a property access such as the expression "foo.bar". * * @author James Strachan * @version $Revision$ */ public class PropertyExpression extends Expression { private Expression objectExpression; private Expression property; private boolean spreadSafe = false; private boolean safe = false; private boolean isStatic = false; private boolean implicitThis = false; public boolean isStatic() { return isStatic; } public PropertyExpression(Expression objectExpression, String property) { this(objectExpression, new ConstantExpression(property), false); } public PropertyExpression(Expression objectExpression, Expression property) { this(objectExpression, property, false); } public PropertyExpression(Expression objectExpression, Expression property, boolean safe) { this.objectExpression = objectExpression; this.property = property; this.safe = safe; } public void visit(GroovyCodeVisitor visitor) { visitor.visitPropertyExpression(this); } public boolean isDynamic() { return true; } public Expression transformExpression(ExpressionTransformer transformer) { PropertyExpression ret = new PropertyExpression(transformer.transform(objectExpression), transformer.transform(property), safe); ret.setSpreadSafe(spreadSafe); ret.setStatic(isStatic); ret.setImplicitThis(implicitThis); ret.setSourcePosition(this); return ret; } public Expression getObjectExpression() { return objectExpression; } public void setObjectExpression(Expression exp) { objectExpression=exp; } public Expression getProperty() { return property; } public String getPropertyAsString() { if (property==null) return null; if (! (property instanceof ConstantExpression)) return null; ConstantExpression constant = (ConstantExpression) property; return constant.getText(); } public String getText() { String object = objectExpression.getText(); String text = property.getText(); String spread = isSpreadSafe() ? "*" : ""; String safe = isSafe() ? "?" : ""; return object + spread + safe + "." + text; } /** * @return is this a safe navigation, i.e. if true then if the source object is null * then this navigation will return null */ public boolean isSafe() { return safe; } public boolean isSpreadSafe() { return spreadSafe; } public void setSpreadSafe(boolean value) { spreadSafe = value; } public String toString() { return super.toString() + "[object: " + objectExpression + " property: " + property + "]"; } public void setStatic(boolean aStatic) { this.isStatic = aStatic; } public boolean isImplicitThis(){ return implicitThis; } public void setImplicitThis(boolean it) { implicitThis = it; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/NotExpression.java0000644001501200150120000000235711715031256025253 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * @author sam */ public class NotExpression extends BooleanExpression { public NotExpression(Expression expression) { super(expression); } public void visit(GroovyCodeVisitor visitor) { visitor.visitNotExpression(this); } public boolean isDynamic() { return false; } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new NotExpression(transformer.transform(getExpression())); ret.setSourcePosition(this); return ret; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/package.html0000644001501200150120000000023311627206700024040 0ustar miguelmiguel package org.codehaus.groovy.ast.expr.*

      AST nodes for Groovy expressions

      groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/EmptyExpression.java0000644001501200150120000000253011707612044025603 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * This class is a place holder for an empty expression. * Empty expression are used in closures lists like (;). During * class Generation this expression should be either ignored or * replace with a null value. * * @author Jochen Theodorou * @see org.codehaus.groovy.ast.stmt.EmptyStatement */ public class EmptyExpression extends Expression { public static final EmptyExpression INSTANCE = new EmptyExpression(); public Expression transformExpression(ExpressionTransformer transformer) { return this; } public void visit(GroovyCodeVisitor visitor) { return; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ConstantExpression.java0000644001501200150120000001015011707612044026273 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a constant expression such as null, true, false * * @author James Strachan * @version $Revision$ */ public class ConstantExpression extends Expression { // The following fields are only used internally; every occurrence of a user-defined expression of the same kind // has its own instance so as to preserve line information. Consequently, to test for such an expression, don't // compare against the field but call isXXXExpression() instead. public static final ConstantExpression NULL = new ConstantExpression(null); public static final ConstantExpression TRUE = new ConstantExpression(Boolean.TRUE); public static final ConstantExpression FALSE = new ConstantExpression(Boolean.FALSE); public static final ConstantExpression EMPTY_STRING = new ConstantExpression(""); public static final ConstantExpression PRIM_TRUE = new ConstantExpression(Boolean.TRUE, true); public static final ConstantExpression PRIM_FALSE = new ConstantExpression(Boolean.FALSE, true); //public static final Expression EMPTY_ARRAY = new PropertyExpression(new ClassExpression(ArgumentListExpression.class.getName()), "EMPTY_ARRAY"); // the following fields are only used internally; there are no user-defined expressions of the same kind public static final ConstantExpression VOID = new ConstantExpression(Void.class); public static final ConstantExpression EMPTY_EXPRESSION = new ConstantExpression(null); private Object value; private String constantName; public ConstantExpression(Object value) { this(value,false); } public ConstantExpression(Object value, boolean keepPrimitive) { this.value = value; if (value != null) { if (keepPrimitive) { if (value instanceof Integer) { setType(ClassHelper.int_TYPE); } else if (value instanceof Boolean) { setType(ClassHelper.boolean_TYPE); } else if (value instanceof Double) { setType(ClassHelper.double_TYPE); } else { setType(ClassHelper.make(value.getClass())); } //TODO: more cases here } else { setType(ClassHelper.make(value.getClass())); } } } public String toString() { return "ConstantExpression[" + value + "]"; } public void visit(GroovyCodeVisitor visitor) { visitor.visitConstantExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { return this; } /** * @return the value of this constant expression */ public Object getValue() { return value; } public String getText() { return (value == null) ? "null" : value.toString(); } public String getConstantName() { return constantName; } public void setConstantName(String constantName) { this.constantName = constantName; } public boolean isNullExpression() { return value == null; } public boolean isTrueExpression() { return Boolean.TRUE.equals(value); } public boolean isFalseExpression() { return Boolean.FALSE.equals(value); } public boolean isEmptyStringExpression() { return "".equals(value); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/BooleanExpression.java0000644001501200150120000000325411715031256026067 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a boolean expression * * @author James Strachan * @version $Revision$ */ public class BooleanExpression extends Expression { private final Expression expression; public BooleanExpression(Expression expression) { this.expression = expression; setType(ClassHelper.boolean_TYPE); // for consistency with AsmClassGenerator. see AsmClassGenerator.visitBooleanExpression. } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitBooleanExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new BooleanExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return expression.getText(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/AnnotationConstantExpression.java0000644001501200150120000000302211707612044030326 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.Map; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents an annotation "constant" that may appear in annotation attributes * (mainly used as a marker). * * @author Alex Popescu * @version $Revision: 3264 $ */ public class AnnotationConstantExpression extends ConstantExpression { public AnnotationConstantExpression(AnnotationNode node) { super(node); setType(node.getClassNode()); } public void visit(GroovyCodeVisitor visitor) { AnnotationNode node = (AnnotationNode) getValue(); Map attrs = node.getMembers(); for (Expression expr : attrs.values()) { expr.visit(visitor); } super.visit(visitor); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ExpressionTransformer.java0000644001501200150120000000173311627206700027012 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; /** * Provides a way to transform expressions * * @author James Strachan * @version $Revision$ */ public interface ExpressionTransformer { /** * Transforms the given expression into another expression */ Expression transform(Expression expression); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/PostfixExpression.java0000644001501200150120000000406711715031256026147 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.syntax.Token; /** * Represents a postfix expression like foo++ or bar++ * * @author James Strachan * @version $Revision$ */ public class PostfixExpression extends Expression { private Token operation; private Expression expression; public PostfixExpression(Expression expression, Token operation) { this.operation = operation; this.expression = expression; } public String toString() { return super.toString() + "[" + expression + operation + "]"; } public void visit(GroovyCodeVisitor visitor) { visitor.visitPostfixExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new PostfixExpression(transformer.transform(expression), operation); ret.setSourcePosition(this); return ret; } public void setExpression(Expression expression) { this.expression = expression; } public Token getOperation() { return operation; } public Expression getExpression() { return expression; } public String getText() { return "(" + expression.getText() + operation.getText() + ")"; } public ClassNode getType() { return expression.getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/SpreadMapExpression.java0000644001501200150120000000324111715031256026360 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a spread map expression *:m * in the map expression [1, *:m, 2, "c":100] * or in the method invoke expression func(1, *:m, 2, "c":100). * * @version $Revision$ */ public class SpreadMapExpression extends Expression { private Expression expression; public SpreadMapExpression(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitSpreadMapExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new SpreadMapExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return "*:" + expression.getText(); } public ClassNode getType() { return expression.getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/MapExpression.java0000644001501200150120000000645211715031256025230 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a map expression [1 : 2, "a" : "b", x : y] which creates a mutable Map * * @author James Strachan * @version $Revision$ */ public class MapExpression extends Expression { private final List mapEntryExpressions; public MapExpression() { this(new ArrayList()); } public MapExpression(List mapEntryExpressions) { this.mapEntryExpressions = mapEntryExpressions; //TODO: get the type's of the expressions to specify the // map type to Map if possible. setType(ClassHelper.MAP_TYPE); } public void addMapEntryExpression(MapEntryExpression expression) { mapEntryExpressions.add(expression); } public List getMapEntryExpressions() { return mapEntryExpressions; } public void visit(GroovyCodeVisitor visitor) { visitor.visitMapExpression(this); } public boolean isDynamic() { return false; } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new MapExpression(transformExpressions(getMapEntryExpressions(), transformer, MapEntryExpression.class)); ret.setSourcePosition(this); return ret; } public String toString() { return super.toString() + mapEntryExpressions; } public String getText() { StringBuffer sb = new StringBuffer(32); sb.append("["); int size = mapEntryExpressions.size(); MapEntryExpression mapEntryExpression = null; if (size > 0) { mapEntryExpression = mapEntryExpressions.get(0); sb.append(mapEntryExpression.getKeyExpression().getText() + ":" + mapEntryExpression.getValueExpression().getText()); for (int i = 1; i < size; i++) { mapEntryExpression = mapEntryExpressions.get(i); sb.append(", " + mapEntryExpression.getKeyExpression().getText() + ":" + mapEntryExpression.getValueExpression().getText()); if (sb.length() > 120 && i < size - 1) { sb.append(", ... "); break; } } } else { sb.append(":"); } sb.append("]"); return sb.toString(); } public void addMapEntryExpression(Expression keyExpression, Expression valueExpression) { addMapEntryExpression(new MapEntryExpression(keyExpression, valueExpression)); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/BinaryExpression.java0000644001501200150120000000724611715031256025741 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; /** * Represents two expressions and an operation * * @author James Strachan * @version $Revision$ */ public class BinaryExpression extends Expression { private Expression leftExpression; private Expression rightExpression; private final Token operation; public BinaryExpression(Expression leftExpression, Token operation, Expression rightExpression) { this.leftExpression = leftExpression; this.operation = operation; this.rightExpression = rightExpression; } public String toString() { return super.toString() + "[" + leftExpression + operation + rightExpression + "]"; } public void visit(GroovyCodeVisitor visitor) { visitor.visitBinaryExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new BinaryExpression(transformer.transform(leftExpression), operation, transformer.transform(rightExpression)); ret.setSourcePosition(this); return ret; } public Expression getLeftExpression() { return leftExpression; } public void setLeftExpression(Expression leftExpression) { this.leftExpression = leftExpression; } public void setRightExpression(Expression rightExpression) { this.rightExpression = rightExpression; } public Token getOperation() { return operation; } public Expression getRightExpression() { return rightExpression; } public String getText() { if (operation.getType() == Types.LEFT_SQUARE_BRACKET) { return leftExpression.getText() + "[" + rightExpression.getText() + "]"; } return "(" + leftExpression.getText() + " " + operation.getText() + " " + rightExpression.getText() + ")"; } /** * Creates an assignment expression in which the specified expression * is written into the specified variable name. */ public static BinaryExpression newAssignmentExpression(Variable variable, Expression rhs) { VariableExpression lhs = new VariableExpression(variable); Token operator = Token.newPlaceholder(Types.ASSIGN); return new BinaryExpression(lhs, operator, rhs); } /** * Creates variable initialization expression in which the specified expression * is written into the specified variable name. */ public static BinaryExpression newInitializationExpression(String variable, ClassNode type, Expression rhs) { VariableExpression lhs = new VariableExpression(variable); if (type != null) { lhs.setType(type); } Token operator = Token.newPlaceholder(Types.ASSIGN); return new BinaryExpression(lhs, operator, rhs); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ConstructorCallExpression.java0000644001501200150120000000536611715031256027637 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * A constructor call * * @author James Strachan * @author Jochen Theodorou * @version $Revision$ */ public class ConstructorCallExpression extends Expression { private final Expression arguments; private boolean usesAnonymousInnerClass; public ConstructorCallExpression(ClassNode type, Expression arguments) { super.setType(type); if (!(arguments instanceof TupleExpression)) { this.arguments = new TupleExpression(arguments); } else { this.arguments = arguments; } } public void visit(GroovyCodeVisitor visitor) { visitor.visitConstructorCallExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression args = transformer.transform(arguments); ConstructorCallExpression ret = new ConstructorCallExpression(getType(), args); ret.setSourcePosition(this); ret.setUsingAnonymousInnerClass(isUsingAnonymousInnerClass()); return ret; } public Expression getArguments() { return arguments; } public String getText() { String text = null; if (isSuperCall()) { text = "super "; } else if (isThisCall()) { text = "this "; } else { text = "new " + getType().getName(); } return text + arguments.getText(); } public String toString() { return super.toString() + "[type: " + getType() + " arguments: " + arguments + "]"; } public boolean isSuperCall() { return getType() == ClassNode.SUPER; } public boolean isSpecialCall() { return isThisCall() || isSuperCall(); } public boolean isThisCall() { return getType() == ClassNode.THIS; } public void setUsingAnonymousInnerClass(boolean usage) { this.usesAnonymousInnerClass = usage; } public boolean isUsingAnonymousInnerClass() { return usesAnonymousInnerClass; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/UnaryPlusExpression.java0000644001501200150120000000310111715031256026441 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * @author Paul King */ public class UnaryPlusExpression extends Expression { private final Expression expression; public UnaryPlusExpression(Expression expression) { this.expression = expression; } public Expression getExpression() { return expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitUnaryPlusExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new UnaryPlusExpression(transformer.transform(expression)); ret.setSourcePosition(this); return ret; } public String getText() { return expression.getText(); } public ClassNode getType() { return expression.getType(); } public boolean isDynamic() { return false; } }groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ListExpression.java0000644001501200150120000000522111715031256025417 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a list expression [1, 2, 3] which creates a mutable List * * @author James Strachan * @version $Revision$ */ public class ListExpression extends Expression { private List expressions; private boolean wrapped = false; public ListExpression() { this(new ArrayList()); } public ListExpression(List expressions) { this.expressions = expressions; //TODO: get the type's of the expressions to specify the // list type to List if possible. setType(ClassHelper.LIST_TYPE); } public void addExpression(Expression expression) { expressions.add(expression); } public List getExpressions() { return expressions; } public void setWrapped(boolean value) { wrapped = value; } public boolean isWrapped() { return wrapped; } public void visit(GroovyCodeVisitor visitor) { visitor.visitListExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new ListExpression(transformExpressions(getExpressions(), transformer)); ret.setSourcePosition(this); return ret; } public Expression getExpression(int i) { return expressions.get(i); } public String getText() { StringBuffer buffer = new StringBuffer("["); boolean first = true; for (Expression expression : expressions) { if (first) { first = false; } else { buffer.append(", "); } buffer.append(expression.getText()); } buffer.append("]"); return buffer.toString(); } public String toString() { return super.toString() + expressions; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/StaticMethodCallExpression.java0000644001501200150120000000460011715031256027670 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import groovy.lang.MetaMethod; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * A static method call on a class * * @author James Strachan * @version $Revision$ */ public class StaticMethodCallExpression extends Expression { private ClassNode ownerType; private String method; private Expression arguments; private MetaMethod metaMethod = null; public StaticMethodCallExpression(ClassNode type, String method, Expression arguments) { ownerType = type; this.method = method; this.arguments = arguments; } public void visit(GroovyCodeVisitor visitor) { visitor.visitStaticMethodCallExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new StaticMethodCallExpression(getOwnerType(), method, transformer.transform(arguments)); ret.setSourcePosition(this); return ret; } public Expression getArguments() { return arguments; } public String getMethod() { return method; } public String getText() { return getOwnerType().getName() + "." + method + arguments.getText(); } public String toString() { return super.toString() + "[" + getOwnerType().getName() + "#" + method + " arguments: " + arguments + "]"; } public ClassNode getOwnerType() { return ownerType; } public void setOwnerType(ClassNode ownerType) { this.ownerType = ownerType; } public void setMetaMethod(MetaMethod metaMethod) { this.metaMethod = metaMethod; } public MetaMethod getMetaMethod() { return metaMethod; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ElvisOperatorExpression.java0000644001501200150120000000417211715031256027306 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a short ternary expression x ?: y, which is equal * to *
       * def truePart = x
       * def booleanPart = truePart as boolean
       * booleanPart? truePart : y
       * 
      * Even if x is no atomic expression, x will be evaluated only * once. Example: *
       * class Foo { 
       *   def index=0 
       *   def getX(){ index++; return index }
       * }
       * def foo = new Foo()
       * def result = foo.x ?: "false case" 
       * assert foo.index == 1
       * assert result == 1 
       * 
       * 
       * @author Jochen Theodorou
       * @since 1.5
       */
      public class ElvisOperatorExpression extends TernaryExpression {
      
          public ElvisOperatorExpression(Expression base, Expression falseExpression) {
              super(getBool(base), base, falseExpression);
          }
          
          private static BooleanExpression getBool(Expression base) {
             BooleanExpression be = new BooleanExpression(base);
             be.setSourcePosition(base);
             return be;
          }
      
          public void visit(GroovyCodeVisitor visitor) {
              visitor.visitShortTernaryExpression(this);
          }
          
          public Expression transformExpression(ExpressionTransformer transformer) {
              Expression ret = new ElvisOperatorExpression(
                      transformer.transform(getTrueExpression()),
                      transformer.transform(getFalseExpression()));
              ret.setSourcePosition(this);
              return ret; 
          }
      }
      groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ClosureExpression.java0000644001501200150120000000565211707612044026131 0ustar  miguelmiguel/*
       * Copyright 2003-2010 the original author or authors.
       *
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       *     http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       */
      package org.codehaus.groovy.ast.expr;
      
      import org.codehaus.groovy.ast.*;
      import org.codehaus.groovy.ast.stmt.Statement;
      import org.codehaus.groovy.runtime.InvokerHelper;
      
      /**
       * Represents a closure expression such as { statement }
       * or { i -> statement } or { i, x, String y ->  statement }
       * 
       * @author James Strachan
       * @author Hamlet D'Arcy
       * @version $Revision$
       */
      public class ClosureExpression extends Expression {
          
          private Parameter[] parameters;
          private Statement code;
          private VariableScope variableScope;
          
          public ClosureExpression(Parameter[] parameters, Statement code) {
              this.parameters = parameters;
              this.code = code;
              super.setType(ClassHelper.CLOSURE_TYPE.getPlainNodeReference());
          }
          
          public void visit(GroovyCodeVisitor visitor) {
              visitor.visitClosureExpression(this);
          }
      
          public Expression transformExpression(ExpressionTransformer transformer) {
              return this;
          }
          
          public String toString() {
              return super.toString() + InvokerHelper.toString(parameters) + "{ " + code + " }";
          }
      
          /**
           * This gets the code statement of the closure. You can read this method to find out what actions
           * the closure is going to perform.
           *
           * @return the code statement of the closure
           */
          public Statement getCode() {
              return code;
          }
      
          /**
           * This sets the code statement of the closure. You can use this method in order to add more actions
           * during the closure execution.
           *
           * @param code the new Statement
           */
          public void setCode(Statement code) {
              this.code = code;
          }
      
          public Parameter[] getParameters() {
              return parameters;
          }
      
          public boolean isParameterSpecified() {
              return parameters != null && parameters.length > 0;
          }
          
          public VariableScope getVariableScope() {
              return variableScope;
          }
      
          public void setVariableScope(VariableScope variableScope) {
              this.variableScope = variableScope;
          }
      
          @Override
          public String getText() {
              String paramText = AstToTextHelper.getParametersText(parameters);
              if (paramText.length() > 0) {
                  return "{ " + paramText + " -> ... }";
              } else {
                  return "{ -> ... }";
              }
          }
      }
      groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/DeclarationExpression.java0000644001501200150120000001575411715031256026745 0ustar  miguelmiguel/*
       * Copyright 2003-2012 the original author or authors.
       *
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       *     http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       */
      package org.codehaus.groovy.ast.expr;
      
      import org.codehaus.groovy.GroovyBugError;
      import org.codehaus.groovy.ast.GroovyCodeVisitor;
      import org.codehaus.groovy.syntax.Token;
      
      /**
       * Represents one or more local variables. Typically it is a single local variable
       * declared by name with an expression like "def foo" or with type "String foo". However, 
       * the multiple assignment feature allows you to create two or more variables using
       * an expression like: def (x, y) = [1, 2].
       * 

      * You can access the left hand side of a declaration using the * "Expression getLeftExpression()" method. In which case you might then * use instanceof and casting to perform operations specific to a * single local variable (VariableExpression) or for the multiple * assignment case (TupleExpression). *

      * Alternatively, if isMultipleAssignmentDeclaration() is false * you can use the method "VariableExpression getVariableExpression()" method. * Similarly, if isMultipleAssignmentDeclaration() is true * you can use the method "TupleExpression getTupleExpression()" method. * Calling either of these expression getters when the "isMultipleAssignment" condition * is not appropriate is unsafe and will result in a ClassCastException. * * @author Jochen Theodorou * @author Hamlet D'Arcy * @version $Revision$ */ public class DeclarationExpression extends BinaryExpression { /** * Creates a DeclarationExpression for VariableExpressions like "def x" or "String y = 'foo'". * @param left * the left hand side of a variable declaration * @param operation * the operation, typically an assignment operator * @param right * the right hand side of a declaration */ public DeclarationExpression(VariableExpression left, Token operation, Expression right) { super(left,operation,right); } /** * Creates a DeclarationExpression for Expressions like "def (x, y) = [1, 2]" * @param left * the left hand side of a declaration. Must be either a VariableExpression or * a TupleExpression with at least one element. * @param operation * the operation, typically an assignment operator * @param right * the right hand side of a declaration */ public DeclarationExpression(Expression left, Token operation, Expression right) { super(left,operation,right); check(left); } private void check(Expression left) { if (left instanceof VariableExpression) { //nothing } else if (left instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) left; if (tuple.getExpressions().size()==0) throw new GroovyBugError("one element required for left side"); } else { throw new GroovyBugError("illegal left expression for declaration: "+left); } } public void visit(GroovyCodeVisitor visitor) { visitor.visitDeclarationExpression(this); } /** * This method returns the left hand side of the declaration cast to the VariableExpression type. * This is an unsafe method to call. In a multiple assignment statement, the left hand side will * be a TupleExpression and a ClassCastException will occur. If you invoke this method then * be sure to invoke isMultipleAssignmentDeclaration() first to check that it is safe to do so. * If that method returns true then this method is safe to call. * @return * left hand side of normal variable declarations * @throws ClassCastException * if the left hand side is not a VariableExpression (and is probably a multiple assignment statement). * */ public VariableExpression getVariableExpression() { return (VariableExpression) this.getLeftExpression(); } /** * This method returns the left hand side of the declaration cast to the TupleExpression type. * This is an unsafe method to call. In a single assignment statement, the left hand side will * be a VariableExpression and a ClassCastException will occur. If you invoke this method then * be sure to invoke isMultipleAssignmentDeclaration() first to check that it is safe to do so. * If that method returns true then this method is safe to call. * @return * left hand side of multiple assignment declarations * @throws ClassCastException * if the left hand side is not a TupleExpression (and is probably a VariableExpression). * */ public TupleExpression getTupleExpression() { return (TupleExpression) this.getLeftExpression(); } /** * This method sets the leftExpression for this BinaryExpression. The parameter must be * either a VariableExpression or a TupleExpression with one or more elements. * @param leftExpression * either a VariableExpression or a TupleExpression with one or more elements. */ public void setLeftExpression(Expression leftExpression) { check(leftExpression); super.setLeftExpression(leftExpression); } public void setRightExpression(Expression rightExpression) { super.setRightExpression(rightExpression); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new DeclarationExpression(transformer.transform(getLeftExpression()), getOperation(), transformer.transform(getRightExpression())); ret.setSourcePosition(this); ret.addAnnotations(getAnnotations()); ret.setDeclaringClass(getDeclaringClass()); return ret; } /** * This method tells you if this declaration is a multiple assignment declaration, which * has the form "def (x, y) = ..." in Groovy. If this method returns true, then the left * hand side is an ArgumentListExpression. Do not call "getVariableExpression()" on this * object if this method returns true, instead use "getLeftExpression()". * @return * true if this declaration is a multiple assignment declaration, which means the * left hand side is an ArgumentListExpression. */ public boolean isMultipleAssignmentDeclaration() { return getLeftExpression() instanceof TupleExpression; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ArrayExpression.java0000644001501200150120000001013511715031256025562 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.Collections; import java.util.List; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents an array object construction either using a fixed size * or an initializer expression * * @author James Strachan * @version $Revision$ */ public class ArrayExpression extends Expression { private List expressions; private List sizeExpression; private ClassNode elementType; private static ClassNode makeArray(ClassNode base, List sizeExpression) { ClassNode ret = base.makeArray(); if (sizeExpression == null) return ret; int size = sizeExpression.size(); for (int i = 1; i < size; i++) { ret = ret.makeArray(); } return ret; } public ArrayExpression(ClassNode elementType, List expressions, List sizeExpression) { //expect to get the elementType super.setType(makeArray(elementType, sizeExpression)); if (expressions == null) expressions = Collections.emptyList(); this.elementType = elementType; this.expressions = expressions; this.sizeExpression = sizeExpression; for (Object item : expressions) { if (item != null && !(item instanceof Expression)) { throw new ClassCastException("Item: " + item + " is not an Expression"); } } if (sizeExpression != null) { for (Object item : sizeExpression) { if (!(item instanceof Expression)) { throw new ClassCastException("Item: " + item + " is not an Expression"); } } } } /** * Creates an array using an initializer expression */ public ArrayExpression(ClassNode elementType, List expressions) { this(elementType, expressions, null); } public void addExpression(Expression expression) { expressions.add(expression); } public List getExpressions() { return expressions; } public void visit(GroovyCodeVisitor visitor) { visitor.visitArrayExpression(this); } public boolean isDynamic() { return false; } public Expression transformExpression(ExpressionTransformer transformer) { List exprList = transformExpressions(expressions, transformer); List sizes = null; if (sizeExpression != null) sizes = transformExpressions(sizeExpression, transformer); Expression ret = new ArrayExpression(elementType, exprList, sizes); ret.setSourcePosition(this); return ret; } public Expression getExpression(int i) { return expressions.get(i); } public ClassNode getElementType() { return elementType; } public String getText() { StringBuffer buffer = new StringBuffer("["); boolean first = true; for (Expression expression : expressions) { if (first) { first = false; } else { buffer.append(", "); } buffer.append(expression.getText()); } buffer.append("]"); return buffer.toString(); } public List getSizeExpression() { return sizeExpression; } public String toString() { return super.toString() + expressions; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ClassExpression.java0000644001501200150120000000276211627206700025560 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents access to a Java/Groovy class in an expression, such * as when invoking a static method or accessing a static type * * @author James Strachan * @version $Revision$ */ public class ClassExpression extends Expression { public ClassExpression(ClassNode type) { super.setType(type); } public void visit(GroovyCodeVisitor visitor) { visitor.visitClassExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { return this; } public String getText() { return getType().getName(); } public String toString() { return super.toString() + "[type: " + getType().getName() + "]"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/FieldExpression.java0000644001501200150120000000415111707612044025531 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a field access such as the expression "this.foo". * * @author James Strachan * @version $Revision$ */ public class FieldExpression extends Expression { private final FieldNode field; private boolean useRef; public FieldExpression(FieldNode field) { this.field = field; } public void visit(GroovyCodeVisitor visitor) { visitor.visitFieldExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { return this; } public String getFieldName() { return field.getName(); } public FieldNode getField() { return field; } public String getText() { return "this." + field.getName(); } public boolean isDynamicTyped() { return field.isDynamicTyped(); } public void setType(ClassNode type) { super.setType(type); field.setType(type); } public ClassNode getType() { return field.getType(); } public void setUseReferenceDirectly(boolean useRef) { this.useRef = useRef; } public boolean isUseReferenceDirectly() { return useRef; } public String toString() { return "field("+getType()+" "+getFieldName()+")"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/ClosureListExpression.java0000644001501200150120000000510111715031256026751 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.VariableScope; /** * This class represents a list of expressions used to * create closures. Example: * * def foo = (1;2;;) * * The right side is a ClosureListExpression consisting of * two ConstantExpressions for the values 1 and 2, and two * EmptyStatement entries. The ClosureListExpression defines a new * variable scope. All created Closures share this scope. * * * @author Jochen Theodorou */ public class ClosureListExpression extends ListExpression { private VariableScope scope; public ClosureListExpression(List expressions) { super(expressions); scope = new VariableScope(); } public ClosureListExpression() { this(new ArrayList(3)); } public void visit(GroovyCodeVisitor visitor) { visitor.visitClosureListExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new ClosureListExpression(transformExpressions(getExpressions(), transformer)); ret.setSourcePosition(this); return ret; } public void setVariableScope(VariableScope scope) { this.scope = scope; } public VariableScope getVariableScope() { return scope; } public String getText() { StringBuffer buffer = new StringBuffer("("); boolean first = true; for (Expression expression : getExpressions()) { if (first) { first = false; } else { buffer.append("; "); } buffer.append(expression.getText()); } buffer.append(")"); return buffer.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/MapEntryExpression.java0000644001501200150120000000410111715031256026237 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents an entry inside a map expression such as 1 : 2. * * @author James Strachan * @version $Revision$ */ public class MapEntryExpression extends Expression { private Expression keyExpression; private Expression valueExpression; public MapEntryExpression(Expression keyExpression, Expression valueExpression) { this.keyExpression = keyExpression; this.valueExpression = valueExpression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitMapEntryExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new MapEntryExpression(transformer.transform(keyExpression), transformer.transform(valueExpression)); ret.setSourcePosition(this); return ret; } public String toString() { return super.toString() + "(key: " + keyExpression + ", value: " + valueExpression + ")"; } public Expression getKeyExpression() { return keyExpression; } public Expression getValueExpression() { return valueExpression; } public void setKeyExpression(Expression keyExpression) { this.keyExpression = keyExpression; } public void setValueExpression(Expression valueExpression) { this.valueExpression = valueExpression; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/VariableExpression.java0000644001501200150120000001532711707612044026242 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Variable; /** * Represents a local variable name, the simplest form of expression. e.g. "foo". * * @author James Strachan * @version $Revision$ */ public class VariableExpression extends Expression implements Variable { // The following fields are only used internally; every occurrence of a user-defined expression of the same kind // has its own instance so as to preserve line information. Consequently, to test for such an expression, don't // compare against the field but call isXXXExpression() instead. public static final VariableExpression THIS_EXPRESSION = new VariableExpression("this", ClassHelper.DYNAMIC_TYPE); public static final VariableExpression SUPER_EXPRESSION = new VariableExpression("super", ClassHelper.DYNAMIC_TYPE); private String variable; private int modifiers; private boolean inStaticContext; private boolean isDynamicTyped=false; private Variable accessedVariable; boolean closureShare=false; boolean useRef=false; private final ClassNode originType; public Variable getAccessedVariable() { return accessedVariable; } public void setAccessedVariable(Variable origin) { this.accessedVariable = origin; } public VariableExpression(String variable, ClassNode type) { this.variable = variable; originType = type; setType(ClassHelper.getWrapper(type)); } public VariableExpression(String variable) { this(variable, ClassHelper.DYNAMIC_TYPE); } public VariableExpression(Variable variable) { this(variable.getName(), variable.getOriginType()); setAccessedVariable(variable); setModifiers(variable.getModifiers()); } public void visit(GroovyCodeVisitor visitor) { visitor.visitVariableExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { return this; } public String getText() { return variable; } public String getName() { return variable; } public String toString() { return super.toString() + "[variable: " + variable + (this.isDynamicTyped() ? "" : " type: " + getType()) + "]"; } public Expression getInitialExpression() { return null; } public boolean hasInitialExpression() { return false; } public boolean isInStaticContext() { if (accessedVariable!=null && accessedVariable!=this) return accessedVariable.isInStaticContext(); return inStaticContext; } public void setInStaticContext(boolean inStaticContext) { this.inStaticContext = inStaticContext; } /** * Set the type of this variable. If you call this method from an AST transformation and that * the {@link #getAccessedVariable() accessed variable} is ({@link #isClosureSharedVariable() shared}, * this operation is unsafe and may lead to a verify error at compile time. Instead, set the type of * the {@link #getAccessedVariable() accessed variable} * @param cn the type to be set on this variable */ public void setType(ClassNode cn){ super.setType(cn); isDynamicTyped |= ClassHelper.DYNAMIC_TYPE==cn; } public boolean isDynamicTyped() { if (accessedVariable!=null && accessedVariable!=this) return accessedVariable.isDynamicTyped(); return isDynamicTyped; } /** * Tells if this variable or the accessed variable is used in a closure context, like in the following * example : *

      def str = 'Hello'
           * def cl = { println str }
           * 
      * The "str" variable is closure shared. * @return true if this variable is used in a closure */ public boolean isClosureSharedVariable() { if (accessedVariable!=null && accessedVariable!=this) return accessedVariable.isClosureSharedVariable(); return closureShare; } /** * Use this method to tell if a variable is used in a closure, like in the following example: *
      def str = 'Hello'
           * def cl = { println str }
           * 
      * The "str" variable is closure shared. The variable expression inside the closure references an * accessed variable "str" which must have the closure shared flag set. * @param inClosure tells if this variable is later referenced in a closure */ public void setClosureSharedVariable(boolean inClosure) { closureShare = inClosure; } public int getModifiers() { return modifiers; } /** * For internal use only. This flag is used by compiler internals and should probably * be converted to a node metadata in future. * @param useRef */ public void setUseReferenceDirectly(boolean useRef) { this.useRef = useRef; } /** * For internal use only. This flag is used by compiler internals and should probably * be converted to a node metadata in future. */ public boolean isUseReferenceDirectly() { return useRef; } public ClassNode getType() { if (accessedVariable!=null && accessedVariable!=this) return accessedVariable.getType(); return super.getType(); } /** * Returns the type which was used when this variable expression was created. For example, * {@link #getType()} may return a boxed type while this method would return the primitive type. * @return the type which was used to define this variable expression */ public ClassNode getOriginType() { if (accessedVariable!=null && accessedVariable!=this) return accessedVariable.getOriginType(); return originType; } public boolean isThisExpression() { return "this".equals(variable); } public boolean isSuperExpression() { return "super".equals(variable); } public void setModifiers(int modifiers) { this.modifiers = modifiers; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/RangeExpression.java0000644001501200150120000000361611715031256025546 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a range expression such as for iterating. * E.g.: *
      for i in 0..10 {...}
      * * @author James Strachan * @version $Revision$ */ public class RangeExpression extends Expression { private Expression from; private Expression to; private boolean inclusive; public RangeExpression(Expression from, Expression to, boolean inclusive) { this.from = from; this.to = to; this.inclusive = inclusive; } public void visit(GroovyCodeVisitor visitor) { visitor.visitRangeExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new RangeExpression(transformer.transform(from), transformer.transform(to), inclusive); ret.setSourcePosition(this); return ret; } public Expression getFrom() { return from; } public Expression getTo() { return to; } public boolean isInclusive() { return inclusive; } public String getText() { return "(" + from.getText() + (!isInclusive()? "..<" : ".." ) + to.getText() + ")"; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/GStringExpression.java0000644001501200150120000000703111715031256026062 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a String expression which contains embedded values inside * it such as "hello there ${user} how are you" which is expanded lazily * * @author James Strachan * @version $Revision$ */ public class GStringExpression extends Expression { private String verbatimText; private List strings = new ArrayList(); private List values = new ArrayList(); public GStringExpression(String verbatimText) { this.verbatimText = verbatimText; super.setType(ClassHelper.GSTRING_TYPE); } public GStringExpression(String verbatimText, List strings, List values) { this.verbatimText = verbatimText; this.strings = strings; this.values = values; super.setType(ClassHelper.GSTRING_TYPE); } public void visit(GroovyCodeVisitor visitor) { visitor.visitGStringExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new GStringExpression( verbatimText, transformExpressions(strings, transformer, ConstantExpression.class), transformExpressions(values, transformer)); ret.setSourcePosition(this); return ret; } public String toString() { return super.toString() + "[strings: " + strings + " values: " + values + "]"; } public String getText() { return verbatimText; } public List getStrings() { return strings; } public List getValues() { return values; } public void addString(ConstantExpression text) { if (text == null) { throw new NullPointerException("Cannot add a null text expression"); } strings.add(text); } public void addValue(Expression value) { // If the first thing is an value, then we need a dummy empty string in front of it so that when we // toString it they come out in the correct order. if (strings.size() == 0) strings.add(ConstantExpression.EMPTY_STRING); values.add(value); } public Expression getValue(int idx) { return values.get(idx); } public boolean isConstantString() { return values.isEmpty(); } public Expression asConstantString() { StringBuffer buffer = new StringBuffer(); for (ConstantExpression expression : strings) { Object value = expression.getValue(); if (value != null) { buffer.append(value); } } return new ConstantExpression(buffer.toString()); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/expr/TupleExpression.java0000644001501200150120000000605111715031256025577 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.expr; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.codehaus.groovy.ast.GroovyCodeVisitor; /** * Represents a tuple expression {1, 2, 3} which creates an immutable List * * @author James Strachan * @version $Revision$ */ public class TupleExpression extends Expression { private List expressions; public TupleExpression() { this(0); } public TupleExpression(Expression expr) { this(1); addExpression(expr); } public TupleExpression(Expression expr1, Expression expr2) { this(2); addExpression(expr1); addExpression(expr2); } public TupleExpression(Expression expr1, Expression expr2, Expression expr3) { this(3); addExpression(expr1); addExpression(expr2); addExpression(expr3); } public TupleExpression(int length) { this.expressions = new ArrayList(length); } public TupleExpression(List expressions) { this.expressions = expressions; } public TupleExpression(Expression[] expressionArray) { this(); expressions.addAll(Arrays.asList(expressionArray)); } public TupleExpression addExpression(Expression expression) { expressions.add(expression); return this; } public List getExpressions() { return expressions; } public void visit(GroovyCodeVisitor visitor) { visitor.visitTupleExpression(this); } public Expression transformExpression(ExpressionTransformer transformer) { Expression ret = new TupleExpression(transformExpressions(getExpressions(), transformer)); ret.setSourcePosition(this); return ret; } public Expression getExpression(int i) { return expressions.get(i); } public String getText() { StringBuffer buffer = new StringBuffer("("); boolean first = true; for (Expression expression : expressions) { if (first) { first = false; } else { buffer.append(", "); } buffer.append(expression.getText()); } buffer.append(")"); return buffer.toString(); } public String toString() { return super.toString() + expressions; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/tools/0000755001501200150120000000000011715031256021743 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/ast/tools/WideningCategories.java0000644001501200150120000001234011715031256026360 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast.tools; import static org.codehaus.groovy.ast.ClassHelper.*; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import java.util.List; /** * This class provides helper methods to determine the type from a widening * operation for example for a plus operation.
      * To determine the resulting type of for example a=exp1+exp2 we look at the * conditions {@link #isIntCategory(ClassNode)}, {@link #isLongCategory(ClassNode)}, * {@link #isBigIntCategory(ClassNode)}, {@link #isDoubleCategory(ClassNode)} and * {@link #isBigDecCategory(ClassNode)} in that order. The first case applying to * exp1 and exp2 is defining the result type of the expression.
      * If for example you look at x = 1 + 2l we have the first category applying to * the number 1 being int, since the 1 is an int. The 2l is a long, therefore the * int category will not apply and the result type can't be int. The next category * in the list is long, and since both apply to long, the result type is a long.
      * * @author Jochen "blackdrag" Theodorou */ public class WideningCategories { /** * It is of an int category, if the provided type is a * byte, char, short, int. */ public static boolean isIntCategory(ClassNode type) { return type==byte_TYPE || type==char_TYPE || type==int_TYPE || type==short_TYPE; } /** * It is of a long category, if the provided type is a * long, its wrapper or if it is a long category. */ public static boolean isLongCategory(ClassNode type) { return type==long_TYPE || isIntCategory(type); } /** * It is of a BigInteger category, if the provided type is a * long category or a BigInteger. */ public static boolean isBigIntCategory(ClassNode type) { return type==BigInteger_TYPE || isLongCategory(type); } /** * It is of a BigDecimal category, if the provided type is a * BigInteger category or a BigDecimal. */ public static boolean isBigDecCategory(ClassNode type) { return type==BigDecimal_TYPE || isBigIntCategory(type); } /** * It is of a double category, if the provided type is a * BigDecimal, a float, double. C(type)=double */ public static boolean isDoubleCategory(ClassNode type) { return type==float_TYPE || type==double_TYPE || isBigDecCategory(type); } public static boolean isNumberCategory(ClassNode type) { return isBigDecCategory(type) || type.isDerivedFrom(Number_TYPE); } /** * Given two class nodes, returns the first common supertype, or the class itself * if there are equal. For example, Double and Float would return Number, while * Set and String would return Object. * @param a first class node * @param b second class node * @return first common supertype */ public static ClassNode firstCommonSuperType(ClassNode a, ClassNode b) { if (a == null || b == null) return ClassHelper.OBJECT_TYPE; if (a == b || a.equals(b)) return a; if (isPrimitiveType(a) && !isPrimitiveType(b)) { if (isNumberType(a) && isNumberType(b)) { return firstCommonSuperType(ClassHelper.getWrapper(a), b); } else { return OBJECT_TYPE; } } else if (isPrimitiveType(b) && !isPrimitiveType(a)) { if (isNumberType(b) && isNumberType(a)) { return firstCommonSuperType(ClassHelper.getWrapper(b), a); } else { return OBJECT_TYPE; } } else if (isPrimitiveType(a) && isPrimitiveType(b)) { return firstCommonSuperType(ClassHelper.getWrapper(a), ClassHelper.getWrapper(b)); } ClassNode superA = a.getSuperClass(); ClassNode superB = b.getSuperClass(); if (a == superB || a.equals(superB)) return superB; if (b == superA || b.equals(superA)) return superA; return firstCommonSuperType(superA, superB); } /** * Given a list of class nodes, returns the first common supertype. * For example, Double and Float would return Number, while * Set and String would return Object. * @param nodes the list of nodes for which to find the first common super type. * @return first common supertype */ public static ClassNode firstCommonSuperType(List nodes) { if (nodes.size()==1) return nodes.get(0); return firstCommonSuperType(nodes.get(0), firstCommonSuperType(nodes.subList(1, nodes.size()))); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/FieldNode.java0000644001501200150120000001072211707612044023302 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.lang.reflect.Field; import org.codehaus.groovy.ast.expr.Expression; import org.objectweb.asm.Opcodes; /** * Represents a field (member variable) * * @author James Strachan * @version $Revision$ */ public class FieldNode extends AnnotatedNode implements Opcodes, Variable { private String name; private int modifiers; private ClassNode type; private ClassNode owner; private Expression initialValueExpression; private boolean dynamicTyped; private boolean holder; private ClassNode originType = ClassHelper.DYNAMIC_TYPE; public static FieldNode newStatic(Class theClass, String name) throws SecurityException, NoSuchFieldException { Field field = theClass.getField(name); ClassNode fldType = ClassHelper.make(field.getType()); return new FieldNode(name, ACC_PUBLIC | ACC_STATIC, fldType, ClassHelper.make(theClass), null); } public FieldNode(String name, int modifiers, ClassNode type, ClassNode owner, Expression initialValueExpression) { this.name = name; this.modifiers = modifiers; this.type = type; if (this.type == ClassHelper.DYNAMIC_TYPE && initialValueExpression != null) this.setType(initialValueExpression.getType()); this.setType(type); this.originType = type; this.owner = owner; this.initialValueExpression = initialValueExpression; } public Expression getInitialExpression() { return initialValueExpression; } public int getModifiers() { return modifiers; } public String getName() { return name; } public ClassNode getType() { return type; } public void setType(ClassNode type) { this.type = type; this.originType = type; dynamicTyped |= type == ClassHelper.DYNAMIC_TYPE; } public ClassNode getOwner() { return owner; } public boolean isHolder() { return holder; } public void setHolder(boolean holder) { this.holder = holder; } public boolean isDynamicTyped() { return dynamicTyped; } public void setModifiers(int modifiers) { this.modifiers = modifiers; } /** * @return true if the field is static */ public boolean isStatic() { return (modifiers & ACC_STATIC) != 0; } /** * @return true if the field is an enum */ public boolean isEnum() { return (modifiers & ACC_ENUM) != 0; } /** * @return true if the field is final */ public boolean isFinal() { return (modifiers & ACC_FINAL) != 0; } /** * @return true if the field is public */ public boolean isPublic() { return (modifiers & ACC_PUBLIC) != 0; } /** * @param owner The owner to set. */ public void setOwner(ClassNode owner) { this.owner = owner; } public boolean hasInitialExpression() { return initialValueExpression != null; } public boolean isInStaticContext() { return isStatic(); } public Expression getInitialValueExpression() { return initialValueExpression; } public void setInitialValueExpression(Expression initialValueExpression) { this.initialValueExpression = initialValueExpression; } /** * @deprecated */ public boolean isClosureSharedVariable() { return false; } /** * @deprecated */ public void setClosureSharedVariable(boolean inClosure) { } public ClassNode getOriginType() { return originType; } public void setOriginType(ClassNode cn) { originType = cn; } public void rename(String name) { declaringClass.renameField(this.name, name); this.name = name; } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/VariableScope.java0000644001501200150120000001424711715031256024175 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Represents a variable scope. This is primarily used to determine variable sharing * across method and closure boundaries. * * @author James Strachan * @author Jochen Theodorou * @version $Revision$ */ public class VariableScope { private Map declaredVariables = Collections.emptyMap(); private Map referencedLocalVariables = Collections.emptyMap(); private Map referencedClassVariables = Collections.emptyMap(); private boolean inStaticContext = false; private boolean resolvesDynamic = false; // Non-null iff this scope corresponds to a class, as opposed to a method, "if" statement, // block statement, etc. private ClassNode clazzScope; private VariableScope parent; public VariableScope() { } public VariableScope(VariableScope parent) { this.parent = parent; } public Variable getDeclaredVariable(String name) { return declaredVariables.get(name); } public boolean isReferencedLocalVariable(String name) { return referencedLocalVariables.containsKey(name); } public boolean isReferencedClassVariable(String name) { return referencedClassVariables.containsKey(name); } public VariableScope getParent() { return parent; } public boolean isInStaticContext() { return inStaticContext; } public void setInStaticContext(boolean inStaticContext) { this.inStaticContext = inStaticContext; } @Deprecated public boolean isResolvingDynamic() { return resolvesDynamic; } @Deprecated public void setDynamicResolving(boolean resolvesDynamic) { this.resolvesDynamic = resolvesDynamic; } public void setClassScope(ClassNode node) { this.clazzScope = node; } /** * Non-null iff this scope corresponds to a class; as opposed to a method, "if" statement, * block statement, etc. */ public ClassNode getClassScope(){ return clazzScope; } /** * Returns true iff this scope corresponds to a class; as opposed to a method, "if" statement, * block statement, etc. */ public boolean isClassScope(){ return clazzScope!=null; } public boolean isRoot() { return parent==null; } public VariableScope copy() { VariableScope copy = new VariableScope(); copy.clazzScope = clazzScope; if (declaredVariables.size() > 0) { copy.declaredVariables = new HashMap(); copy.declaredVariables.putAll(declaredVariables); } copy.inStaticContext = inStaticContext; copy.parent = parent; if (referencedClassVariables.size() > 0) { copy.referencedClassVariables = new HashMap(); copy.referencedClassVariables.putAll(referencedClassVariables); } if (referencedLocalVariables.size() > 0) { copy.referencedLocalVariables = new HashMap(); copy.referencedLocalVariables.putAll(referencedLocalVariables); } copy.resolvesDynamic = resolvesDynamic; return copy; } public void putDeclaredVariable(Variable var) { if (declaredVariables == Collections.EMPTY_MAP) declaredVariables = new HashMap(); declaredVariables.put(var.getName(), var); } public Iterator getReferencedLocalVariablesIterator() { return referencedLocalVariables.values().iterator(); } public int getReferencedLocalVariablesCount() { return referencedLocalVariables.size(); } public Variable getReferencedLocalVariable(String name) { return referencedLocalVariables.get(name); } public void putReferencedLocalVariable(Variable var) { if (referencedLocalVariables == Collections.EMPTY_MAP) referencedLocalVariables = new HashMap(); referencedLocalVariables.put(var.getName(), var); } public void putReferencedClassVariable(Variable var) { if (referencedClassVariables == Collections.EMPTY_MAP) referencedClassVariables = new HashMap(); referencedClassVariables.put(var.getName(), var); } public Variable getReferencedClassVariable(String name) { return referencedClassVariables.get(name); } public Object removeReferencedClassVariable(String name) { if (referencedClassVariables == Collections.EMPTY_MAP) return null; else return referencedClassVariables.remove(name); } /** * Gets a map containing the class variables referenced * by this scope. This not can not be modified. * @return a map containing the class variable references */ public Map getReferencedClassVariables() { if (referencedClassVariables == Collections.EMPTY_MAP) { return referencedClassVariables; } else { return Collections.unmodifiableMap(referencedClassVariables); } } /** * Gets an iterator for the referenced class variables. The * remove operation is not supported. * @return an iterator for the referenced class variables */ public Iterator getReferencedClassVariablesIterator() { return getReferencedClassVariables().values().iterator(); } }groovy-1.8.6/src/main/org/codehaus/groovy/ast/PropertyNode.java0000644001501200150120000000657511627206700024115 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.stmt.Statement; import org.objectweb.asm.Opcodes; /** * Represents a property (member variable, a getter and setter) * * @author James Strachan * @version $Revision$ */ public class PropertyNode extends AnnotatedNode implements Opcodes, Variable { private FieldNode field; private Statement getterBlock; private Statement setterBlock; private final int modifiers; private boolean closureShare = false; public PropertyNode( String name, int modifiers, ClassNode type, ClassNode owner, Expression initialValueExpression, Statement getterBlock, Statement setterBlock) { this(new FieldNode(name, modifiers & ACC_STATIC, type, owner, initialValueExpression), modifiers, getterBlock, setterBlock); } public PropertyNode(FieldNode field, int modifiers, Statement getterBlock, Statement setterBlock) { this.field = field; this.modifiers = modifiers; this.getterBlock = getterBlock; this.setterBlock = setterBlock; } public Statement getGetterBlock() { return getterBlock; } public Expression getInitialExpression() { return field.getInitialExpression(); } public void setGetterBlock(Statement getterBlock) { this.getterBlock = getterBlock; } public void setSetterBlock(Statement setterBlock) { this.setterBlock = setterBlock; } public int getModifiers() { return modifiers; } public String getName() { return field.getName(); } public Statement getSetterBlock() { return setterBlock; } public ClassNode getType() { return field.getType(); } public void setType(ClassNode t) { field.setType(t); } public FieldNode getField() { return field; } public void setField(FieldNode fn) { field = fn; } public boolean isPrivate() { return (modifiers & ACC_PRIVATE) != 0; } public boolean isPublic() { return (modifiers & ACC_PUBLIC) != 0; } public boolean isStatic() { return (modifiers & ACC_STATIC) != 0; } public boolean hasInitialExpression() { return field.hasInitialExpression(); } public boolean isInStaticContext() { return field.isInStaticContext(); } public boolean isDynamicTyped() { return field.isDynamicTyped(); } public boolean isClosureSharedVariable() { return false; } public void setClosureSharedVariable(boolean inClosure) { closureShare = inClosure; } public ClassNode getOriginType() { return getType(); } } groovy-1.8.6/src/main/org/codehaus/groovy/ast/GroovyCodeVisitor.java0000644001501200150120000001054011707612044025107 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.classgen.BytecodeExpression; /** * An implementation of the visitor pattern for working with ASTNodes * * @author James Strachan * @version $Revision$ */ public interface GroovyCodeVisitor { // statements //------------------------------------------------------------------------- void visitBlockStatement(BlockStatement statement); void visitForLoop(ForStatement forLoop); void visitWhileLoop(WhileStatement loop); void visitDoWhileLoop(DoWhileStatement loop); void visitIfElse(IfStatement ifElse); void visitExpressionStatement(ExpressionStatement statement); void visitReturnStatement(ReturnStatement statement); void visitAssertStatement(AssertStatement statement); void visitTryCatchFinally(TryCatchStatement finally1); void visitSwitch(SwitchStatement statement); void visitCaseStatement(CaseStatement statement); void visitBreakStatement(BreakStatement statement); void visitContinueStatement(ContinueStatement statement); void visitThrowStatement(ThrowStatement statement); void visitSynchronizedStatement(SynchronizedStatement statement); void visitCatchStatement(CatchStatement statement); // expressions //------------------------------------------------------------------------- void visitMethodCallExpression(MethodCallExpression call); void visitStaticMethodCallExpression(StaticMethodCallExpression expression); void visitConstructorCallExpression(ConstructorCallExpression expression); void visitTernaryExpression(TernaryExpression expression); void visitShortTernaryExpression(ElvisOperatorExpression expression); void visitBinaryExpression(BinaryExpression expression); void visitPrefixExpression(PrefixExpression expression); void visitPostfixExpression(PostfixExpression expression); void visitBooleanExpression(BooleanExpression expression); void visitClosureExpression(ClosureExpression expression); void visitTupleExpression(TupleExpression expression); void visitMapExpression(MapExpression expression); void visitMapEntryExpression(MapEntryExpression expression); void visitListExpression(ListExpression expression); void visitRangeExpression(RangeExpression expression); void visitPropertyExpression(PropertyExpression expression); void visitAttributeExpression(AttributeExpression attributeExpression); void visitFieldExpression(FieldExpression expression); void visitMethodPointerExpression(MethodPointerExpression expression); void visitConstantExpression(ConstantExpression expression); void visitClassExpression(ClassExpression expression); void visitVariableExpression(VariableExpression expression); void visitDeclarationExpression(DeclarationExpression expression); void visitGStringExpression(GStringExpression expression); void visitArrayExpression(ArrayExpression expression); void visitSpreadExpression(SpreadExpression expression); void visitSpreadMapExpression(SpreadMapExpression expression); void visitNotExpression(NotExpression expression); void visitUnaryMinusExpression(UnaryMinusExpression expression); void visitUnaryPlusExpression(UnaryPlusExpression expression); void visitBitwiseNegationExpression(BitwiseNegationExpression expression); void visitCastExpression(CastExpression expression); void visitArgumentlistExpression(ArgumentListExpression expression); void visitClosureListExpression(ClosureListExpression closureListExpression); void visitBytecodeExpression(BytecodeExpression expression); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/GroovyClassVisitor.java0000644001501200150120000000274411707612044025311 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; /** * A special visitor for working with the structure of a class. In general, your * will want to use the Abstract class based on this class {@link ClassCodeVisitorSupport}. * * @see org.codehaus.groovy.ast.ClassNode * @see org.codehaus.groovy.ast.ClassCodeVisitorSupport * * @author James Strachan * @version $Revision$ */ public interface GroovyClassVisitor { /** * Visit a ClassNode. */ void visitClass(ClassNode node); /** * Visit a ConstructorNode. */ void visitConstructor(ConstructorNode node); /** * Visit a MethodNode. */ void visitMethod(MethodNode node); /** * Visit a FieldNode. */ void visitField(FieldNode node); /** * Visit a PropertyNode. */ void visitProperty(PropertyNode node); } groovy-1.8.6/src/main/org/codehaus/groovy/ast/ClassCodeExpressionTransformer.java0000644001501200150120000001244311627206700027615 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import java.util.List; import java.util.Map; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; /** * Visitor to transform expressions in a whole class. * Transformed Expressions are usually not visited. * * @author Jochen Theodorou */ public abstract class ClassCodeExpressionTransformer extends ClassCodeVisitorSupport implements ExpressionTransformer { protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { for (Parameter p : node.getParameters()) { if (p.hasInitialExpression()) { Expression init = p.getInitialExpression(); p.setInitialExpression(transform(init)); } } super.visitConstructorOrMethod(node, isConstructor); } public void visitSwitch(SwitchStatement statement) { Expression exp = statement.getExpression(); statement.setExpression(transform(exp)); for (CaseStatement caseStatement : statement.getCaseStatements()) { caseStatement.visit(this); } statement.getDefaultStatement().visit(this); } public void visitField(FieldNode node) { visitAnnotations(node); Expression init = node.getInitialExpression(); node.setInitialValueExpression(transform(init)); } public void visitProperty(PropertyNode node) { visitAnnotations(node); Statement statement = node.getGetterBlock(); visitClassCodeContainer(statement); statement = node.getSetterBlock(); visitClassCodeContainer(statement); } public void visitIfElse(IfStatement ifElse) { ifElse.setBooleanExpression((BooleanExpression) (transform(ifElse.getBooleanExpression()))); ifElse.getIfBlock().visit(this); ifElse.getElseBlock().visit(this); } public Expression transform(Expression exp) { if (exp == null) return null; return exp.transformExpression(this); } public void visitAnnotations(AnnotatedNode node) { List annotations = node.getAnnotations(); if (annotations.isEmpty()) return; for (AnnotationNode an : annotations) { // skip built-in properties if (an.isBuiltIn()) continue; for (Map.Entry member : an.getMembers().entrySet()) { member.setValue(transform(member.getValue())); } } } public void visitReturnStatement(ReturnStatement statement) { statement.setExpression(transform(statement.getExpression())); } public void visitAssertStatement(AssertStatement as) { as.setBooleanExpression((BooleanExpression) (transform(as.getBooleanExpression()))); as.setMessageExpression(transform(as.getMessageExpression())); } public void visitCaseStatement(CaseStatement statement) { statement.setExpression(transform(statement.getExpression())); statement.getCode().visit(this); } public void visitDoWhileLoop(DoWhileStatement loop) { loop.setBooleanExpression((BooleanExpression) (transform(loop.getBooleanExpression()))); super.visitDoWhileLoop(loop); } public void visitForLoop(ForStatement forLoop) { forLoop.setCollectionExpression(transform(forLoop.getCollectionExpression())); super.visitForLoop(forLoop); } public void visitSynchronizedStatement(SynchronizedStatement sync) { sync.setExpression(transform(sync.getExpression())); super.visitSynchronizedStatement(sync); } public void visitThrowStatement(ThrowStatement ts) { ts.setExpression(transform(ts.getExpression())); } public void visitWhileLoop(WhileStatement loop) { loop.setBooleanExpression((BooleanExpression) transform(loop.getBooleanExpression())); super.visitWhileLoop(loop); } public void visitExpressionStatement(ExpressionStatement es) { es.setExpression(transform(es.getExpression())); } } groovy-1.8.6/src/main/org/codehaus/groovy/package.html0000644001501200150120000000021511627206700022273 0ustar miguelmiguel package org.codehaus.groovy.*

      Groovy Language for the JVM

      groovy-1.8.6/src/main/org/codehaus/groovy/jsr223/0000755001501200150120000000000011715031256021041 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/jsr223/GroovyScriptEngineImpl.java0000644001501200150120000004241411715031256026333 0ustar miguelmiguel/* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: Redistributions of source code * must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. Neither the name of the Sun Microsystems nor the names of * is contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.codehaus.groovy.jsr223; import groovy.lang.Binding; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovyClassLoader; import groovy.lang.MetaClass; import groovy.lang.MissingMethodException; import groovy.lang.MissingPropertyException; import groovy.lang.Script; import groovy.lang.Tuple; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.MethodClosure; import javax.script.AbstractScriptEngine; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.Invocable; import javax.script.ScriptContext; import javax.script.ScriptEngineFactory; import javax.script.ScriptException; import javax.script.SimpleBindings; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.lang.Class; import java.lang.String; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /* * @author Mike Grogan * @author A. Sundararajan * @author Jim White * @author Guillaume Laforge */ public class GroovyScriptEngineImpl extends AbstractScriptEngine implements Compilable, Invocable { private static boolean debug = false; // script-string-to-generated Class map private Map classMap = new ConcurrentHashMap(); // global closures map - this is used to simulate a single // global functions namespace private Map globalClosures = new ConcurrentHashMap(); // class loader for Groovy generated classes private GroovyClassLoader loader; // lazily initialized factory private volatile GroovyScriptEngineFactory factory; // counter used to generate unique global Script class names private static int counter; static { counter = 0; } public GroovyScriptEngineImpl() { this.loader = new GroovyClassLoader(getParentLoader(), new CompilerConfiguration()); } public GroovyScriptEngineImpl(GroovyClassLoader classLoader) { if (classLoader == null) throw new IllegalArgumentException("GroovyClassLoader is null"); this.loader = classLoader; } public Object eval(Reader reader, ScriptContext ctx) throws ScriptException { return eval(readFully(reader), ctx); } public Object eval(String script, ScriptContext ctx) throws ScriptException { try { Class clazz = getScriptClass(script); if (clazz == null) throw new ScriptException("Script class is null"); return eval(clazz, ctx); } catch (SyntaxException e) { throw new ScriptException(e.getMessage(), e.getSourceLocator(), e.getLine()); } catch (Exception e) { if (debug) e.printStackTrace(); throw new ScriptException(e); } } public Bindings createBindings() { return new SimpleBindings(); } public ScriptEngineFactory getFactory() { if (factory == null) { synchronized (this) { if (factory == null) { factory = new GroovyScriptEngineFactory(); } } } return factory; } // javax.script.Compilable methods public CompiledScript compile(String scriptSource) throws ScriptException { try { return new GroovyCompiledScript(this, getScriptClass(scriptSource)); } catch (SyntaxException e) { throw new ScriptException(e.getMessage(), e.getSourceLocator(), e.getLine()); } catch (IOException e) { throw new ScriptException(e); } catch (CompilationFailedException ee) { throw new ScriptException(ee); } } public CompiledScript compile(Reader reader) throws ScriptException { return compile(readFully(reader)); } // javax.script.Invokable methods. public Object invokeFunction(String name, Object... args) throws ScriptException, NoSuchMethodException { return invokeImpl(null, name, args); } public Object invokeMethod(Object thiz, String name, Object... args) throws ScriptException, NoSuchMethodException { if (thiz == null) { throw new IllegalArgumentException("script object is null"); } return invokeImpl(thiz, name, args); } public T getInterface(Class clazz) { return makeInterface(null, clazz); } public T getInterface(Object thiz, Class clazz) { if (thiz == null) { throw new IllegalArgumentException("script object is null"); } return makeInterface(thiz, clazz); } // package-privates Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException { // Bindings so script has access to this environment. // Only initialize once. if (null == ctx.getAttribute("context", ScriptContext.ENGINE_SCOPE)) { // add context to bindings ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE); // direct output to ctx.getWriter // If we're wrapping with a PrintWriter here, // enable autoFlush because otherwise it might not get done! final Writer writer = ctx.getWriter(); ctx.setAttribute("out", (writer instanceof PrintWriter) ? writer : new PrintWriter(writer, true), ScriptContext.ENGINE_SCOPE); // Not going to do this after all (at least for now). // Scripts can use context.{reader, writer, errorWriter}. // That is a modern version of System.{in, out, err} or Console.{reader, writer}(). // // // New I/O names consistent with ScriptContext and java.io.Console. // // ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE); // // // Direct errors to ctx.getErrorWriter // final Writer errorWriter = ctx.getErrorWriter(); // ctx.setAttribute("errorWriter", (errorWriter instanceof PrintWriter) ? // errorWriter : // new PrintWriter(errorWriter), // ScriptContext.ENGINE_SCOPE); // // // Get input from ctx.getReader // // We don't wrap with BufferedReader here because we expect that if // // the host wants that they do it. Either way Groovy scripts will // // always have readLine because the GDK supplies it for Reader. // ctx.setAttribute("reader", ctx.getReader(), ScriptContext.ENGINE_SCOPE); } // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for differents groovy script if (ctx.getWriter() != null) { ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true), ScriptContext.ENGINE_SCOPE); } /* * We use the following Binding instance so that global variable lookup * will be done in the current ScriptContext instance. */ Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override public Object getVariable(String name) { synchronized (ctx) { int scope = ctx.getAttributesScope(name); if (scope != -1) { return ctx.getAttribute(name, scope); } } throw new MissingPropertyException(name, getClass()); } @Override public void setVariable(String name, Object value) { synchronized (ctx) { int scope = ctx.getAttributesScope(name); if (scope == -1) { scope = ScriptContext.ENGINE_SCOPE; } ctx.setAttribute(name, value, scope); } } }; try { // if this class is not an instance of Script, it's a full-blown class // then simply return that class if (!Script.class.isAssignableFrom(scriptClass)) { return scriptClass; } else { // it's a script Script scriptObject = (Script) scriptClass.newInstance(); scriptObject.setBinding(binding); // create a Map of MethodClosures from this new script object Method[] methods = scriptClass.getMethods(); Map closures = new HashMap(); for (Method m : methods) { String name = m.getName(); closures.put(name, new MethodClosure(scriptObject, name)); } // save all current closures into global closures map globalClosures.putAll(closures); MetaClass oldMetaClass = scriptObject.getMetaClass(); /* * We override the MetaClass of this script object so that we can * forward calls to global closures (of previous or future "eval" calls) * This gives the illusion of working on the same "global" scope. */ scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) { @Override public Object invokeMethod(Object object, String name, Object args) { if (args == null) { return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY); } if (args instanceof Tuple) { return invokeMethod(object, name, ((Tuple) args).toArray()); } if (args instanceof Object[]) { return invokeMethod(object, name, (Object[]) args); } else { return invokeMethod(object, name, new Object[]{args}); } } @Override public Object invokeMethod(Object object, String name, Object[] args) { try { return super.invokeMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, ctx); } } @Override public Object invokeStaticMethod(Object object, String name, Object[] args) { try { return super.invokeStaticMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, ctx); } } }); return scriptObject.run(); } } catch (Exception e) { throw new ScriptException(e); } finally { // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for different groovy script // Groovy's scripting engine implementation adds those two variables in the binding // but should clean up afterwards ctx.removeAttribute("context", ScriptContext.ENGINE_SCOPE); ctx.removeAttribute("out", ScriptContext.ENGINE_SCOPE); } } Class getScriptClass(String script) throws SyntaxException, CompilationFailedException, IOException { Class clazz = classMap.get(script); if (clazz != null) { return clazz; } clazz = loader.parseClass(script, generateScriptName()); classMap.put(script, clazz); return clazz; } public void setClassLoader(GroovyClassLoader classLoader) { this.loader = classLoader; } public GroovyClassLoader getClassLoader() { return this.loader; } //-- Internals only below this point // invokes the specified method/function on the given object. private Object invokeImpl(Object thiz, String name, Object... args) throws ScriptException, NoSuchMethodException { if (name == null) { throw new NullPointerException("method name is null"); } try { if (thiz != null) { return InvokerHelper.invokeMethod(thiz, name, args); } else { return callGlobal(name, args); } } catch (MissingMethodException mme) { throw new NoSuchMethodException(mme.getMessage()); } catch (Exception e) { throw new ScriptException(e); } } // call the script global function of the given name private Object callGlobal(String name, Object[] args) { return callGlobal(name, args, context); } private Object callGlobal(String name, Object[] args, ScriptContext ctx) { Closure closure = globalClosures.get(name); if (closure != null) { return closure.call(args); } else { // Look for closure valued variable in the // given ScriptContext. If available, call it. Object value = ctx.getAttribute(name); if (value instanceof Closure) { return ((Closure) value).call(args); } // else fall thru.. } throw new MissingMethodException(name, getClass(), args); } // generate a unique name for top-level Script classes private synchronized String generateScriptName() { return "Script" + (++counter) + ".groovy"; } private T makeInterface(Object obj, Class clazz) { final Object thiz = obj; if (clazz == null || !clazz.isInterface()) { throw new IllegalArgumentException("interface Class expected"); } return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() { public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { return invokeImpl(thiz, m.getName(), args); } }); } // determine appropriate class loader to serve as parent loader // for GroovyClassLoader instance private ClassLoader getParentLoader() { // check whether thread context loader can "see" Groovy Script class ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader(); try { Class c = ctxtLoader.loadClass(Script.class.getName()); if (c == Script.class) { return ctxtLoader; } } catch (ClassNotFoundException cnfe) { /* ignore */ } // exception was thrown or we get wrong class return Script.class.getClassLoader(); } private String readFully(Reader reader) throws ScriptException { char[] arr = new char[8 * 1024]; // 8K at a time StringBuilder buf = new StringBuilder(); int numChars; try { while ((numChars = reader.read(arr, 0, arr.length)) > 0) { buf.append(arr, 0, numChars); } } catch (IOException exp) { throw new ScriptException(exp); } return buf.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/jsr223/GroovyScriptEngineFactory.java0000644001501200150120000001211611715031256027035 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.jsr223; import groovy.lang.GroovySystem; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A factory class conforming to JSR-223 which is used to instantiate * Groovy ScriptEngines and also exposes metadata describing * Groovy's engine class. * * @author Adapted from original by Mike Grogan * @author Adapted from original by A. Sundararajan * @author Jim White * @author Guillaume Laforge */ public class GroovyScriptEngineFactory implements ScriptEngineFactory { private static final String VERSION = "2.0"; private static final String SHORT_NAME = "groovy"; private static final String LANGUAGE_NAME = "Groovy"; public String getEngineName() { return "Groovy Scripting Engine"; } /** * Note that the scripting.dev.java.net engine had this backwards. * The engine version refers to this engine implementation. * Whereas language version refers to the groovy implementation * (which is obtained from the runtime). */ public String getEngineVersion() { return VERSION; } /** * This is also different than scripting.dev.java.net which used an * initial lowercase. But these are proper names and should be capitalized. */ public String getLanguageName() { return LANGUAGE_NAME; } public String getLanguageVersion() { return GroovySystem.getVersion(); } public List getExtensions() { return EXTENSIONS; } public List getMimeTypes() { return MIME_TYPES; } public List getNames() { return NAMES; } public Object getParameter(String key) { if (ScriptEngine.NAME.equals(key)) { return SHORT_NAME; } else if (ScriptEngine.ENGINE.equals(key)) { return getEngineName(); } else if (ScriptEngine.ENGINE_VERSION.equals(key)) { return VERSION; } else if (ScriptEngine.LANGUAGE.equals(key)) { return LANGUAGE_NAME; } else if (ScriptEngine.LANGUAGE_VERSION.equals(key)) { return GroovySystem.getVersion(); } else if ("THREADING".equals(key)) { return "MULTITHREADED"; } else { throw new IllegalArgumentException("Invalid key"); } } public ScriptEngine getScriptEngine() { return new GroovyScriptEngineImpl(); } public String getMethodCallSyntax(String obj, String method, String... args) { String ret = obj + "." + method + "("; int len = args.length; if (len == 0) { ret += ")"; return ret; } for (int i = 0; i < len; i++) { ret += args[i]; if (i != len - 1) { ret += ","; } else { ret += ")"; } } return ret; } public String getOutputStatement(String toDisplay) { StringBuilder buf = new StringBuilder(); buf.append("println(\""); int len = toDisplay.length(); for (int i = 0; i < len; i++) { char ch = toDisplay.charAt(i); switch (ch) { case '"': buf.append("\\\""); break; case '\\': buf.append("\\\\"); break; default: buf.append(ch); break; } } buf.append("\")"); return buf.toString(); } public String getProgram(String... statements) { StringBuilder ret = new StringBuilder(); int len = statements.length; for (int i = 0; i < len; i++) { ret.append(statements[i]); ret.append('\n'); } return ret.toString(); } private static final List NAMES; private static final List EXTENSIONS; private static final List MIME_TYPES; static { List n = new ArrayList(2); n.add(SHORT_NAME); n.add(LANGUAGE_NAME); NAMES = Collections.unmodifiableList(n); n = new ArrayList(1); n.add("groovy"); EXTENSIONS = Collections.unmodifiableList(n); n = new ArrayList(1); n.add("application/x-groovy"); MIME_TYPES = Collections.unmodifiableList(n); } } groovy-1.8.6/src/main/org/codehaus/groovy/jsr223/GroovyCompiledScript.java0000644001501200150120000000302111715031256026027 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.jsr223; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; /** * Used to represent compiled Groovy scripts. Such scripts may be executed repeatedly * by Groovy's ScriptEngine using the eval method without reparsing overheads. * * @author Mike Grogan * @author A. Sundararajan */ public class GroovyCompiledScript extends CompiledScript { private final GroovyScriptEngineImpl engine; private final Class clasz; public GroovyCompiledScript(GroovyScriptEngineImpl engine, Class clazz) { this.engine = engine; this.clasz = clazz; } public Object eval(ScriptContext context) throws ScriptException { return engine.eval(clasz, context); } public ScriptEngine getEngine() { return engine; } } groovy-1.8.6/src/main/org/codehaus/groovy/GroovyExceptionInterface.java0000644001501200150120000000147711627206700025655 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy; /** * An interface for use by all Groovy compiler exceptions. */ public interface GroovyExceptionInterface { boolean isFatal(); void setFatal( boolean fatal ); } groovy-1.8.6/src/main/org/codehaus/groovy/GroovyBugError.java0000644001501200150120000000610311707612044023615 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy; /** * This class represents an error that is thrown when a bug is * recognized inside the runtime. Basically it is thrown when * a constraint is not fullfilled that should be fullfiled. * * @author Jochen Theodorou */ public class GroovyBugError extends AssertionError { // message string private String message; // optional exception private final Exception exception; /** * constructs a bug error using the given text * @param message the error message text */ public GroovyBugError( String message ) { this(message, null); } /** * Constructs a bug error using the given exception * @param exception cause of this error */ public GroovyBugError( Exception exception ) { this(null, exception); } /** * Constructs a bug error using the given exception and * a text with additional information about the cause * @param msg additional information about this error * @param exception cause of this error */ public GroovyBugError( String msg, Exception exception ) { this.exception = exception; this.message = msg; } /** * Returns a String representation of this class by calling getMessage(). * @see #getMessage() */ public String toString() { return getMessage(); } /** * Returns the detail message string of this error. The message * will consist of the bug text prefixed by "BUG! " if there this * instance was created using a message. If this error was * constructed without using a bug text the message of the cause * is used prefixed by "BUG! UNCAUGHT EXCEPTION: " * * @return the detail message string of this error. */ public String getMessage() { if( message != null ) { return "BUG! "+message; } else { return "BUG! UNCAUGHT EXCEPTION: " + exception.getMessage(); } } public Throwable getCause() { return this.exception; } /** * Returns the bug text to describe this error */ public String getBugText(){ if( message != null ){ return message; } else { return exception.getMessage(); } } /** * Sets the bug text to describe this error */ public void setBugText(String msg) { this.message = msg; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlib.xml0000644001501200150120000000134311627206700022010 0ustar miguelmiguel groovy-1.8.6/src/main/org/codehaus/groovy/util/0000755001501200150120000000000011707612046020774 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/util/Finalizable.java0000644001501200150120000000131611627206700024055 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public interface Finalizable { void finalizeReference(); } groovy-1.8.6/src/main/org/codehaus/groovy/util/ReferenceManager.java0000644001501200150120000001436111627206700025032 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.lang.ref.ReferenceQueue; import java.util.concurrent.atomic.AtomicInteger; public class ReferenceManager { private static class ThreadedReferenceManager extends ReferenceManager { private final Thread thread; private volatile boolean shouldRun = true; public ThreadedReferenceManager(ReferenceQueue queue) { super(queue); thread = new Thread() { public void run() { ReferenceQueue queue = getReferenceQueue(); java.lang.ref.Reference r=null; while (shouldRun) { try { r = queue.remove(1000); } catch (InterruptedException e) { break; } if (r==null) continue; if (r instanceof Reference) { Reference ref = (Reference) r; Finalizable holder = ref.getHandler(); if (holder!=null) holder.finalizeReference(); } r.clear(); r=null; } } }; thread.setContextClassLoader(null); thread.setDaemon(true); thread.setName(ThreadedReferenceManager.class.getName()); thread.start(); } @Override public void stopThread() { shouldRun = false; thread.interrupt(); } @Override public String toString() { return "ReferenceManager(threaded, thread="+thread+")"; } } public static ReferenceManager createThreadedManager(ReferenceQueue queue) { return new ThreadedReferenceManager(queue); } public static ReferenceManager createIdlingManager(ReferenceQueue queue) { return new ReferenceManager(queue); } public static ReferenceManager createCallBackedManager(ReferenceQueue queue) { return new ReferenceManager(queue){ @Override public void removeStallEntries() { ReferenceQueue queue = getReferenceQueue(); for(;;) { java.lang.ref.Reference r = queue.poll(); if (r==null) break; if (r instanceof Reference) { Reference ref = (Reference) r; Finalizable holder = ref.getHandler(); if (holder!=null) holder.finalizeReference(); } r.clear(); r=null; } } @Override public void afterReferenceCreation(Reference r) { removeStallEntries(); } @Override public String toString() { return "ReferenceManager(callback)"; } }; } public static ReferenceManager createThresholdedIdlingManager(final ReferenceQueue queue, final ReferenceManager callback, final int threshold) { if (threshold<0) throw new IllegalArgumentException("threshold must not be below 0."); return new ReferenceManager(queue){ private AtomicInteger refCnt = new AtomicInteger(); private volatile ReferenceManager manager = createIdlingManager(queue); @Override public void afterReferenceCreation(Reference r) { if (manager==callback) { callback.afterReferenceCreation(r); return; } // we use the idle manager, so let us use the reference counter // we change the manager once the threshold is reached. There is // a small chance that the value will go beyond Integer.MAX_VALUE // so we check for values below 0 too. If threshold is low, then // this is unlikely to happen. If threshold is high, then we // have all negative values as fall back int count = refCnt.incrementAndGet(); if (count>threshold || count<0) { manager = callback; } } @Override public String toString() { return "ReferenceManager(thresholded, current manager="+manager+", threshold="+refCnt.get()+"/"+threshold+")"; } }; } private ReferenceQueue queue; public ReferenceManager(ReferenceQueue queue) { this.queue = queue; } protected ReferenceQueue getReferenceQueue() { return queue; } public void afterReferenceCreation(Reference r) {} public void removeStallEntries() {} public void stopThread() {} @Override public String toString() { return "ReferenceManager(idling)"; } private static final ReferenceBundle SOFT_BUNDLE, WEAK_BUNDLE; static { ReferenceQueue queue = new ReferenceQueue(); ReferenceManager callBack = ReferenceManager.createCallBackedManager(queue); ReferenceManager manager = ReferenceManager.createThresholdedIdlingManager(queue, callBack, 500); SOFT_BUNDLE = new ReferenceBundle(manager, ReferenceType.SOFT); WEAK_BUNDLE = new ReferenceBundle(manager, ReferenceType.WEAK); } public static ReferenceBundle getDefaultSoftBundle() { return SOFT_BUNDLE; } public static ReferenceBundle getDefaultWeakBundle() { return WEAK_BUNDLE; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/DoubleKeyHashMap.java0000644001501200150120000000523511627206700024766 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public class DoubleKeyHashMap extends ComplexKeyHashMap { public static class Entry extends ComplexKeyHashMap.Entry{ public Object key1, key2; } public final Object get(Object key1, Object key2) { int h = hash (31*key1.hashCode()+key2.hashCode()); ComplexKeyHashMap.Entry e = table [h & (table.length-1)]; for (; e != null; e = e.next) if (e.hash == h && checkEquals(e, key1, key2)) return e; return null; } public boolean checkEquals(ComplexKeyHashMap.Entry e, Object key1, Object key2) { Entry ee = (Entry) e; return ee.key1 == key1 && ee.key2 == key2; } public Entry getOrPut(Object key1, Object key2) { int h = hash (31*key1.hashCode()+key2.hashCode()); final int index = h & (table.length - 1); ComplexKeyHashMap.Entry e = table [index]; for (; e != null; e = e.next) if (e.hash == h && checkEquals( e, key1, key2)) return (Entry) e; ComplexKeyHashMap.Entry entry = createEntry(key1, key2, h, index); table [index] = entry; if ( ++size == threshold ) resize(2*table.length); return (Entry) entry; } private ComplexKeyHashMap.Entry createEntry(Object key1, Object key2, int h, int index) { Entry entry = createEntry (); entry.next = table [index]; entry.hash = h; entry.key1 = key1; entry.key2 = key2; return entry; } public Entry createEntry() { return new Entry (); } public final ComplexKeyHashMap.Entry remove(Object key1, Object key2) { int h = hash (31*key1.hashCode()+key2.hashCode()); int index = h & (table.length -1); for (ComplexKeyHashMap.Entry e = table [index], prev = null; e != null; prev = e, e = e.next ) { if (e.hash == h && checkEquals(e, key1, key2)) { if (prev == null) table [index] = e.next; else prev.next = e.next; size--; e.next = null; return e; } } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/AbstractConcurrentDoubleKeyMap.java0000644001501200150120000001601611627206700027710 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public abstract class AbstractConcurrentDoubleKeyMap extends AbstractConcurrentMapBase { public AbstractConcurrentDoubleKeyMap(Object segmentInfo) { super(segmentInfo); } static int hash(K1 key1, K2 key2) { int h = 31*key1.hashCode() + key2.hashCode(); h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } public V get(K1 key1, K2 key2) { int hash = hash(key1, key2); return segmentFor(hash).get(key1, key2, hash); } public Entry getOrPut(K1 key1, K2 key2, V value) { int hash = hash(key1,key2); return segmentFor(hash).getOrPut(key1, key2, hash, value); } public void put(K1 key1, K2 key2, V value) { int hash = hash(key1, key2); segmentFor(hash).put(key1, key2, hash).setValue(value); } public void remove(K1 key1, K2 key2) { int hash = hash(key1, key2); segmentFor(hash).remove(key1, key2, hash); } public final Segment segmentFor(int hash) { return (Segment) segments[(hash >>> segmentShift) & segmentMask]; } abstract static class Segment extends AbstractConcurrentMapBase.Segment { Segment(int initialCapacity) { super(initialCapacity); } V get(K1 key1, K2 key2, int hash) { Object[] tab = table; Object o = tab[hash & (tab.length - 1)]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isEqual(key1,key2,hash)) { return e.getValue(); } } else { Object arr [] = (Object[]) o; for (int i = 0; i != arr.length; ++i) { Entry e = (Entry) arr [i]; if (e != null && e.isEqual(key1, key2, hash)) return e.getValue(); } } } return null; } Entry getOrPut(K1 key1, K2 key2, int hash, V value) { Object[] tab = table; Object o = tab[hash & (tab.length - 1)]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isEqual(key1,key2,hash)) { return e; } } else { Object arr [] = (Object[]) o; for (int i = 0; i != arr.length; ++i) { Entry e = (Entry) arr [i]; if (e != null && e.isEqual(key1, key2, hash)) return e; } } } final Entry kvEntry = put(key1, key2, hash); kvEntry.setValue(value); return kvEntry; } Entry put(K1 key1, K2 key2, int hash) { lock(); try { int c = count; if (c++ > threshold) { rehash(); } Object[] tab = table; final int index = hash & (tab.length - 1); final Object o = tab[index]; if (o != null) { if (o instanceof Entry) { final Entry e = (Entry) o; if (e.isEqual(key1,key2,hash)) { return e; } final Object[] arr = new Object[2]; final Entry res = createEntry(key1, key2, hash); arr [0] = res; arr [1] = e; tab[index] = arr; count = c; // write-volatile return res; } else { Object arr [] = (Object[]) o; for (int i = 0; i != arr.length; ++i) { Entry e = (Entry) arr [i]; if (e != null && e.isEqual(key1, key2, hash)) { return e; } } final Object[] newArr = new Object[arr.length+1]; final Entry res = createEntry(key1,key2, hash); arr [0] = res; System.arraycopy(arr, 0, newArr, 1, arr.length); tab[index] = arr; count = c; // write-volatile return res; } } final Entry res = createEntry(key1, key2, hash); tab[index] = res; count = c; // write-volatile return res; } finally { unlock(); } } public void remove(K1 key1, K2 key2, int hash) { lock(); try { int c = count-1; final Object[] tab = table; final int index = hash & (tab.length - 1); Object o = tab[index]; if (o != null) { if (o instanceof Entry) { if (((Entry)o).isEqual(key1, key2, hash)) { tab[index] = null; count = c; } } else { Object arr [] = (Object[]) o; for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e != null && e.isEqual(key1, key2, hash)) { arr [i] = null; count = c; break; } } } } } finally { unlock(); } } protected abstract Entry createEntry(K1 key1, K2 key2, int hash); } interface Entry extends AbstractConcurrentMapBase.Entry{ boolean isEqual(K1 key1, K2 key2, int hash); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ManagedReference.java0000644001501200150120000000316111627206700025010 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; /** * * * @author Alex Tkachman * @author Jochen Theodorou */ public class ManagedReference implements Finalizable { private static final ReferenceManager NULL_MANAGER = new ReferenceManager(null){}; private final Reference> ref; private final ReferenceManager manager; public ManagedReference(ReferenceType type, ReferenceManager rmanager, T value) { if (rmanager==null) rmanager = NULL_MANAGER; this.manager = rmanager; this.ref = type.createReference(value, this, rmanager.getReferenceQueue()); rmanager.afterReferenceCreation(ref); } public ManagedReference(ReferenceBundle bundle, T value) { this(bundle.getType(),bundle.getManager(),value); } public final T get() { return ref.get(); } public final void clear() { ref.clear(); manager.removeStallEntries(); } public void finalizeReference(){ clear(); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ListHashMap.java0000644001501200150120000001306411707612046024020 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * This represents a * @author Jochen "blackdrag" Theodorou */ public class ListHashMap implements Map { private int listFill = 0; private Object[] listKeys; private Object[] listValues; private int size = 0; private Map innerMap; private final int maxListFill; public ListHashMap() { this(3); } public ListHashMap(int listSize){ this.listKeys = new Object[listSize]; this.listValues = new Object[listSize]; maxListFill = listSize; } public void clear() { listFill = 0; innerMap = null; for (int i=0; i makeMap() { Map m = new HashMap(); for (int i=0; i> entrySet() { Map m; if (size>maxListFill) { m = innerMap; } else { m = makeMap(); } return m.entrySet(); } public V get(Object key) { if(size==0) return null; if (size keySet() { Map m; if (size>=maxListFill) { m = innerMap; } else { m = makeMap(); } return m.keySet(); } public V put(K key, V value) { if (size m) { if (size+m.size() entry : m.entrySet()) { listKeys[listFill] = entry.getKey(); listValues[listFill] = entry.getValue(); listFill++; } size += m.size(); return; } if (size entry : innerMap.entrySet()) { listKeys[i] = entry.getKey(); listValues[i] = entry.getValue(); i++; } listFill = innerMap.size(); innerMap = null; } public int size() { return size; } public Collection values() { if (size list = new ArrayList(size); for (int i=0; i { private final class Element extends ManagedReference { Element next; Element previous; public Element(ReferenceBundle bundle, V value) { super(bundle, value); } public void finalizeReference() { if (previous != null && previous.next != null) { previous.next = next; } if (next != null && next.previous != null) { next.previous = previous; } if (this == head) head = next; next = null; if (this == tail) tail = previous; previous = null; super.finalizeReference(); } } private final class Iter implements Iterator { private Element current; private boolean currentHandled = false; Iter() { current = head; } public boolean hasNext() { if (current == null) return false; if (currentHandled) { return current.next != null; } else { return current != null; } } public T next() { if (currentHandled) current = current.next; currentHandled = true; if (current == null) return null; return current.get(); } public void remove() { if (current != null) current.finalizeReference(); } } private Element tail; private Element head; private ReferenceBundle bundle; public ManagedLinkedList(ReferenceBundle bundle) { this.bundle = bundle; } /** * adds a value to the list * * @param value the value */ public void add(T value) { Element element = new Element(bundle, value); element.previous = tail; if (tail != null) tail.next = element; tail = element; if (head == null) head = element; } /** * returns an iterator, which allows the removal of elements. * The next() method of the iterator may return null values. This * is especially the case if the value was removed. * * @return the Iterator */ public Iterator iterator() { return new Iter(); } /** * Returns an array of non null elements from the source array. * * @param tArray the source array * @return the array */ public T[] toArray(T[] tArray) { List array = new ArrayList(100); for (Iterator it = iterator(); it.hasNext();) { T val = it.next(); if (val != null) array.add(val); } return array.toArray(tArray); } /** * returns if the list is empty * * @return true if the list is empty */ public boolean isEmpty() { return head == null; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ComplexKeyHashMap.java0000644001501200150120000001053011627206700025155 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.util.NoSuchElementException; public class ComplexKeyHashMap { public static class Entry { public int hash; public Entry next; public Object value; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } protected Entry table []; protected static final int DEFAULT_CAPACITY = 32; protected static final int MINIMUM_CAPACITY = 4; protected static final int MAXIMUM_CAPACITY = 1 << 28; protected int size; protected transient int threshold; public ComplexKeyHashMap() { init(DEFAULT_CAPACITY); } public ComplexKeyHashMap(boolean b) { } public ComplexKeyHashMap(int expectedMaxSize) { init (capacity(expectedMaxSize)); } public static int hash(int h) { h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void clear() { Object[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } public void init(int initCapacity) { threshold = (initCapacity * 6)/8; table = new Entry[initCapacity]; } public void resize(int newLength) { Entry[] oldTable = table; int oldLength = table.length; Entry[] newTable = new Entry[newLength]; for (int j = 0; j < oldLength; j++) { for (Entry e = oldTable [j]; e != null;) { Entry next = e.next; int index = e.hash & (newLength-1); e.next = newTable[index]; newTable [index] = e; e = next; } } table = newTable; threshold = (6 * newLength) / 8; } private int capacity(int expectedMaxSize) { // Compute min capacity for expectedMaxSize given a load factor of 3/4 int minCapacity = (8 * expectedMaxSize)/6; // Compute the appropriate capacity int result; if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) { result = MAXIMUM_CAPACITY; } else { result = MINIMUM_CAPACITY; while (result < minCapacity) result <<= 1; } return result; } public interface EntryIterator { boolean hasNext (); Entry next (); } public ComplexKeyHashMap.Entry[] getTable() { return table; } public EntryIterator getEntrySetIterator() { return new EntryIterator() { Entry next; // next entry to return int index; // current slot Entry current; // current entry { Entry[] t = table; int i = t.length; Entry n = null; if (size != 0) { // advance to first entry while (i > 0 && (n = t[--i]) == null) {} } next = n; index = i; } public boolean hasNext() { return next != null; } public Entry next() { return nextEntry(); } Entry nextEntry() { Entry e = next; if (e == null) throw new NoSuchElementException(); Entry n = e.next; Entry[] t = table; int i = index; while (n == null && i > 0) n = t[--i]; index = i; next = n; return current = e; } }; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/LockableObject.java0000644001501200150120000000372411627206700024505 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.util.concurrent.locks.AbstractQueuedSynchronizer; /** * A bit simplified lock designed to be inherited by. */ public class LockableObject extends AbstractQueuedSynchronizer { transient Thread owner; protected final boolean isHeldExclusively() { return getState() != 0 && owner == Thread.currentThread(); } public final void lock() { if (compareAndSetState(0, 1)) owner = Thread.currentThread(); else acquire(1); } public final void unlock() { release(1); } protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (compareAndSetState(0, acquires)) { owner = current; return true; } } else if (current == owner) { setState(c+ acquires); return true; } return false; } protected final boolean tryRelease(int releases) { int c = getState() - releases; if (Thread.currentThread() != owner) throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { free = true; owner = null; } setState(c); return free; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/HashCodeHelper.java0000644001501200150120000000704111627206700024454 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.util.Arrays; /** * A utility class to help calculate hashcode values * using an algorithm similar to that outlined in * "Effective Java, Joshua Bloch, 2nd Edition". */ public class HashCodeHelper { private static final int SEED = 127; private static final int MULT = 31; public static int initHash() { return SEED; } public static int updateHash(int current, boolean var) { return shift(current) + (var ? 1 : 0); } public static int updateHash(int current, char var) { return shift(current) + (int) var; } public static int updateHash(int current, int var) { return shift(current) + var; } public static int updateHash(int current, long var) { return shift(current) + (int) (var ^ (var >>> 32)); } public static int updateHash(int current, float var) { return updateHash(current, Float.floatToIntBits(var)); } public static int updateHash(int current, double var) { return updateHash(current, Double.doubleToLongBits(var)); } public static int updateHash(int current, Object var) { if (var == null) return updateHash(current, 0); if (var.getClass().isArray()) return shift(current) + Arrays.hashCode((Object[]) var); return updateHash(current, var.hashCode()); } public static int updateHash(int current, boolean[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, char[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, byte[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, short[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, int[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, long[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, float[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } public static int updateHash(int current, double[] var) { if (var == null) return updateHash(current, 0); return shift(current) + Arrays.hashCode(var); } private static int shift(int current) { return MULT * current; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ReferenceBundle.java0000644001501200150120000000333011627206700024663 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.lang.ref.ReferenceQueue; public class ReferenceBundle{ private ReferenceManager manager; private ReferenceType type; public ReferenceBundle(ReferenceManager manager, ReferenceType type){ this.manager = manager; this.type = type; } public ReferenceType getType() { return type; } public ReferenceManager getManager() { return manager; } private static final ReferenceBundle softReferences, weakReferences; static { ReferenceQueue queue = new ReferenceQueue(); ReferenceManager callBack = ReferenceManager.createCallBackedManager(queue); ReferenceManager manager = ReferenceManager.createThresholdedIdlingManager(queue, callBack, 5000); softReferences = new ReferenceBundle(manager, ReferenceType.SOFT); weakReferences = new ReferenceBundle(manager, ReferenceType.WEAK); } public static ReferenceBundle getSoftBundle() { return softReferences; } public static ReferenceBundle getWeakBundle() { return weakReferences; } }groovy-1.8.6/src/main/org/codehaus/groovy/util/ReferenceType.java0000644001501200150120000000677011627206700024406 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; public enum ReferenceType { SOFT { @Override protected Reference createReference(T value, V handler, ReferenceQueue queue) { return new SoftRef(value, handler, queue); } }, WEAK { @Override protected Reference createReference(T value, V handler, ReferenceQueue queue) { return new WeakRef(value, handler, queue); } }, PHANTOM { @Override protected Reference createReference(T value, V handler, ReferenceQueue queue) { return new PhantomRef(value, handler, queue); } }, HARD { @Override protected Reference createReference(T value, V handler, ReferenceQueue queue) { return new HardRef(value, handler, queue); } }; protected abstract Reference createReference(T value, V handler, ReferenceQueue queue); private static class SoftRef extends SoftReference implements Reference { private final V handler; public SoftRef(TT referent, V handler, ReferenceQueue q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class WeakRef extends WeakReference implements Reference { private final V handler; public WeakRef(TT referent, V handler, ReferenceQueue q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class PhantomRef extends PhantomReference implements Reference { private final V handler; public PhantomRef(TT referent, V handler, ReferenceQueue q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class HardRef implements Reference { private TT ref; private final V handler; public HardRef(TT referent, V handler, ReferenceQueue q) { this.ref = referent; this.handler = handler; } public V getHandler() { return handler; } public TT get() { return ref; } public void clear() { ref = null; } } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ManagedConcurrentMap.java0000644001501200150120000000637011627206700025677 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public class ManagedConcurrentMap extends AbstractConcurrentMap { protected ReferenceBundle bundle; public ManagedConcurrentMap(ReferenceBundle bundle) { super(bundle); this.bundle = bundle; if (bundle==null) throw new IllegalArgumentException("bundle must not be null"); } protected Segment createSegment(Object segmentInfo, int cap) { ReferenceBundle bundle = (ReferenceBundle) segmentInfo; if (bundle==null) throw new IllegalArgumentException("bundle must not be null"); return new ManagedConcurrentMap.Segment(bundle, cap); } public static class Segment extends AbstractConcurrentMap.Segment{ protected final ReferenceBundle bundle; public Segment(ReferenceBundle bundle, int cap) { super(cap); this.bundle = bundle; if (bundle==null) throw new IllegalArgumentException("bundle must not be null"); } protected AbstractConcurrentMap.Entry createEntry(K key, int hash, V value) { if (bundle==null) throw new IllegalArgumentException("bundle must not be null"); return new EntryWithValue(bundle, this, key, hash, value); } } public static class Entry extends ManagedReference implements AbstractConcurrentMap.Entry { private final Segment segment; private int hash; public Entry(ReferenceBundle bundle, Segment segment, K key, int hash) { super(bundle, key); this.segment = segment; this.hash = hash; } public boolean isValid() { return get() != null; } public boolean isEqual(K key, int hash) { return this.hash == hash && get() == key; } public V getValue() { return (V)this; } public void setValue(V value) { } public int getHash() { return hash; } public void finalizeRef() { super.finalizeReference(); segment.removeEntry(this); } } public static class EntryWithValue extends Entry { private V value; public EntryWithValue(ReferenceBundle bundle, Segment segment, K key, int hash, V value) { super(bundle, segment, key, hash); setValue(value); } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public void finalizeRef() { value = null; super.finalizeRef(); } } }groovy-1.8.6/src/main/org/codehaus/groovy/util/ReleaseInfo.java0000644001501200150120000000541411627206700024034 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Properties; /** * Exposes the Groovy release information * * @author Roshan Dawrani */ public class ReleaseInfo { private static final Properties RELEASE_INFO = new Properties(); private static final String RELEASE_INFO_FILE = "META-INF/groovy-release-info.properties"; private static final String KEY_IMPLEMENTATION_VERSION = "ImplementationVersion"; private static final String KEY_BUNDLE_VERSION = "BundleVersion"; private static final String KEY_BUILD_DATE = "BuildDate"; private static final String KEY_BUILD_TIME = "BuildTime"; static { URL url = null; ClassLoader cl = ReleaseInfo.class.getClassLoader(); // we need no security check for getting the system class // loader since if we do the invoker has a null loader, // in which case no security check will be done if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl instanceof URLClassLoader) { // this avoids going through the parent classloaders/bootstrap url = ((URLClassLoader) cl).findResource(RELEASE_INFO_FILE); } else { // fallback option as ClassLoader#findResource() is protected url = cl.getResource(RELEASE_INFO_FILE); } if (url != null) { try { InputStream is = url.openStream(); if(is != null) { RELEASE_INFO.load(is); } } catch(IOException ioex) { // ignore. In case of some exception, release info is not available } } } public static String getVersion() { return get(KEY_IMPLEMENTATION_VERSION); } public static Properties getAllProperties() { return RELEASE_INFO; } private static String get(String propName) { String propValue = RELEASE_INFO.getProperty(propName); return (propValue == null ? "" : propValue); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/ManagedDoubleKeyMap.java0000644001501200150120000000671711627206700025445 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public class ManagedDoubleKeyMap extends AbstractConcurrentDoubleKeyMap { public ManagedDoubleKeyMap(ReferenceBundle bundle) { super(bundle); } protected AbstractConcurrentDoubleKeyMap.Segment createSegment(Object segmentInfo, int cap) { ReferenceBundle bundle = (ReferenceBundle) segmentInfo; return new Segment(bundle, cap); } static class Segment extends AbstractConcurrentDoubleKeyMap.Segment{ private ReferenceBundle bundle; public Segment(ReferenceBundle bundle, int cap) { super(cap); this.bundle = bundle; } protected AbstractConcurrentDoubleKeyMap.Entry createEntry(K1 key1, K2 key2, int hash) { return new EntryWithValue(bundle, key1, key2, hash, this); } } static class Ref extends ManagedReference { final Entry entry; public Ref(ReferenceBundle bundle, K referent, Entry entry) { super(bundle, referent); this.entry = entry; } public void finalizeRef() { this.entry.clean(); } } public static class Entry implements AbstractConcurrentDoubleKeyMap.Entry { private final int hash; final Ref ref1; final Ref ref2; final Segment segment; public Entry(ReferenceBundle bundle, K1 key1, K2 key2, int hash, Segment segment) { this.hash = hash; this.segment = segment; ref1 = new Ref(bundle, key1, this); ref2 = new Ref(bundle, key2, this); } public boolean isValid() { return ref1.get() != null && ref2.get () != null; } public boolean isEqual(K1 key1, K2 key2, int hash) { return this.hash == hash && ref1.get() == key1 && ref2.get() == key2; } public V getValue() { return (V)this; } public void setValue(V value) { } public int getHash() { return hash; } public void clean() { segment.removeEntry(this); ref1.clear(); ref2.clear(); } } private static class EntryWithValue extends Entry { private V value; public EntryWithValue(ReferenceBundle bundle, K1 key1, K2 key2, int hash, Segment segment) { super(bundle, key1, key2, hash, segment); } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public void clean() { super.clean(); value = null; } } } groovy-1.8.6/src/main/org/codehaus/groovy/util/AbstractConcurrentMap.java0000644001501200150120000001561111627206700026104 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public abstract class AbstractConcurrentMap extends AbstractConcurrentMapBase { public AbstractConcurrentMap(Object segmentInfo) { super(segmentInfo); } public Segment segmentFor (int hash) { return (Segment) super.segmentFor(hash); } public V get(K key) { int hash = hash(key); return (V) segmentFor(hash).get(key, hash); } public Entry getOrPut(K key, V value) { int hash = hash(key); return segmentFor(hash).getOrPut(key, hash, value); } public void put(K key, V value) { int hash = hash(key); segmentFor(hash).put(key, hash, value); } public void remove(K key) { int hash = hash(key); segmentFor(hash).remove(key, hash); } public abstract static class Segment extends AbstractConcurrentMapBase.Segment { protected Segment(int initialCapacity) { super(initialCapacity); } public final V get(K key, int hash) { Object[] tab = table; Object o = tab[hash & (tab.length - 1)]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isEqual(key, hash)) { return e.getValue(); } } else { Object arr [] = (Object[]) o; for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e != null && e.isEqual(key, hash)) { return e.getValue(); } } } } return null; } public final Entry getOrPut(K key, int hash, V value) { Object[] tab = table; Object o = tab[hash & (tab.length - 1)]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isEqual(key, hash)) { return e; } } else { Object arr [] = (Object[]) o; for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e != null && e.isEqual(key, hash)) { return e; } } } } return put(key, hash, value); } public final Entry put(K key, int hash, V value) { lock(); try { int c = count; if (c++ > threshold) { rehash(); } Object[] tab = table; int index = hash & (tab.length - 1); Object o = tab[index]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isEqual(key, hash)) { e.setValue(value); return e; } else { Object arr [] = new Object [2]; final Entry ee = createEntry(key, hash, value); arr [0] = ee; arr [1] = e; tab[index] = arr; count = c; return ee; } } else { Object arr [] = (Object[]) o; for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e != null && e.isEqual(key, hash)) { e.setValue(value); return e; } } final Entry ee = createEntry(key, hash, value); for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e == null) { arr [i] = ee; count = c; return ee; } } Object newArr [] = new Object[arr.length+1]; newArr [0] = ee; System.arraycopy(arr, 0, newArr, 1, arr.length); tab [index] = newArr; count = c; return ee; } } Entry e = createEntry(key, hash, value); tab[index] = e; count = c; // write-volatile return e; } finally { unlock(); } } public void remove(K key, int hash) { lock(); try { int c = count-1; final Object[] tab = table; final int index = hash & (tab.length - 1); Object o = tab[index]; if (o != null) { if (o instanceof Entry) { if (((Entry)o).isEqual(key, hash)) { tab[index] = null; count = c; } } else { Object arr [] = (Object[]) o; for (int i = 0; i < arr.length; i++) { Entry e = (Entry) arr[i]; if (e != null && e.isEqual(key, hash)) { arr [i] = null; count = c; break; } } } } } finally { unlock(); } } protected abstract Entry createEntry(K key, int hash, V value); } public interface Entry extends AbstractConcurrentMapBase.Entry{ boolean isEqual(K key, int hash); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/AbstractConcurrentMapBase.java0000644001501200150120000002341211627206700026675 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public abstract class AbstractConcurrentMapBase { protected static final int MAXIMUM_CAPACITY = 1 << 30; static final int MAX_SEGMENTS = 1 << 16; static final int RETRIES_BEFORE_LOCK = 2; final int segmentMask; final int segmentShift; protected final Segment[] segments; public AbstractConcurrentMapBase(Object segmentInfo) { int sshift = 0; int ssize = 1; while (ssize < 16) { ++sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = new Segment[ssize]; int c = 512 / ssize; if (c * ssize < 512) ++c; int cap = 1; while (cap < c) cap <<= 1; for (int i = 0; i < this.segments.length; ++i) this.segments[i] = createSegment(segmentInfo, cap); } protected abstract Segment createSegment(Object segmentInfo, int cap); protected static int hash(K key) { int h = System.identityHashCode(key); h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } public Segment segmentFor(int hash) { return segments[(hash >>> segmentShift) & segmentMask]; } public int fullSize() { int count = 0; for (int i = 0; i < segments.length; i++) { segments[i].lock(); try { for (int j = 0; j < segments[i].table.length; j++) { Object o = segments[i].table [j]; if (o != null) { if (o instanceof Entry) { count++; } else { Object arr [] = (Object[]) o; count += arr.length; } } } } finally { segments[i].unlock(); } } return count; } public int size() { int count = 0; for (int i = 0; i < segments.length; i++) { segments[i].lock(); try { for (int j = 0; j < segments[i].table.length; j++) { Object o = segments[i].table [j]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isValid()) count++; } else { Object arr [] = (Object[]) o; for (int k = 0; k < arr.length; k++) { Entry info = (Entry) arr[k]; if (info != null && info.isValid()) count++; } } } } } finally { segments[i].unlock(); } } return count; } public static class Segment extends LockableObject { volatile int count; int threshold; protected volatile Object[] table; protected Segment(int initialCapacity) { setTable(new Object[initialCapacity]); } void setTable(Object[] newTable) { threshold = (int) (newTable.length * 0.75f); table = newTable; } void removeEntry (Entry e) { lock (); int newCount = count; try { Object [] tab = table; int index = e.getHash() & (tab.length-1); Object o = tab[index]; if (o != null) { if (o instanceof Entry) { if (o == e) { tab [index] = null; newCount--; } } else { Object arr [] = (Object[]) o; Object res = null; for (int i = 0; i < arr.length; i++) { Entry info = (Entry) arr[i]; if (info != null) { if(info != e) { if (info.isValid()) { res = put(info, res); } else { newCount--; } } else { newCount--; } } } tab [index] = res; } count = newCount; } } finally { unlock(); } } void rehash() { Object[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) return; int newCount = 0; for (int i = 0; i < oldCapacity ; i++) { Object o = oldTable [i]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isValid()) { newCount++; } else { oldTable[i] = null; } } else { Object arr [] = (Object[]) o; int localCount = 0; for (int index = 0; index < arr.length; index++) { Entry e = (Entry) arr[index]; if (e != null && e.isValid()) { localCount++; } else { arr [index] = null; } } if (localCount == 0) oldTable[i] = null; else newCount += localCount; } } } Object[] newTable = new Object[newCount+1 < threshold ? oldCapacity : oldCapacity << 1]; int sizeMask = newTable.length - 1; newCount = 0; for (int i = 0; i < oldCapacity ; i++) { Object o = oldTable[i]; if (o != null) { if (o instanceof Entry) { Entry e = (Entry) o; if (e.isValid()) { int index = e.getHash() & sizeMask; put(e, index, newTable); newCount++; } } else { Object arr [] = (Object[]) o; for (int j = 0; j < arr.length; j++) { Entry e = (Entry) arr[j]; if (e != null && e.isValid()) { int index = e.getHash() & sizeMask; put(e, index, newTable); newCount++; } } } } } threshold = (int)(newTable.length * 0.75f); table = newTable; count = newCount; } private void put(Entry ee, int index, Object[] tab) { Object o = tab[index]; if (o != null) { if (o instanceof Entry) { Object arr [] = new Object [2]; arr [0] = ee; arr [1] = (Entry) o; tab[index] = arr; return; } else { Object arr [] = (Object[]) o; Object newArr [] = new Object[arr.length+1]; newArr [0] = ee; System.arraycopy(arr, 0, newArr, 1, arr.length); tab [index] = newArr; return; } } tab[index] = ee; } private Object put(Entry ee, Object o) { if (o != null) { if (o instanceof Entry) { Object arr [] = new Object [2]; arr [0] = ee; arr [1] = (Entry) o; return arr; } else { Object arr [] = (Object[]) o; Object newArr [] = new Object[arr.length+1]; newArr [0] = ee; System.arraycopy(arr, 0, newArr, 1, arr.length); return newArr; } } return ee; } } public interface Entry { V getValue(); void setValue(V value); int getHash(); boolean isValid(); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/StringUtil.groovy0000644001501200150120000000347411627206700024354 0ustar miguelmiguel/* * Copyright 2009-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util /** * Provides Groovy with functionality similar to the unix tr command * which translates a string replacing characters from a source set * with characters from a replacement set. * * @author UEHARA Junji (uehaj) * @author NAKANO Yasuharu (nobeans) * @since 1.7.3 */ class StringUtil { static String tr(String text, String source, String replacement) { if (!text || !source) { return text } source = expandHyphen(source) replacement = expandHyphen(replacement) // padding replacement with a last character, if necessary replacement = replacement.padRight(source.size(), replacement[replacement.size() - 1]) return text.collect { original -> if (source.contains(original)) { replacement[source.lastIndexOf(original)] } else { original } }.join() } // no expansion for hyphen at start or end of Strings private static String expandHyphen(String text) { if (!text.contains('-')) { return text } return text.replaceAll(/(.)-(.)/, { all, begin, end -> (begin..end).join() }) } } groovy-1.8.6/src/main/org/codehaus/groovy/util/SingleKeyHashMap.java0000644001501200150120000001067611627206700025002 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public class SingleKeyHashMap extends ComplexKeyHashMap { public static class Entry extends ComplexKeyHashMap.Entry{ public Object key; public Object getKey() { return key; } } public SingleKeyHashMap () { super (); } public SingleKeyHashMap (boolean b) { super (false); } public boolean containsKey(String name) { return get(name) != null; } public void put(Object key, Object value) { getOrPut(key).value = value; } public final Object get(Object key) { int h = hash (key.hashCode()); ComplexKeyHashMap.Entry e = table [h & (table.length-1)]; for (; e != null; e = e.next) if (e.hash == h && ((Entry) e).key.equals(key)) return ((Entry)e).value; return null; } public Entry getOrPut(Object key) { int h = hash (key.hashCode()); final ComplexKeyHashMap.Entry[] t = table; final int index = h & (t.length - 1); ComplexKeyHashMap.Entry e = t[index]; for (; e != null; e = e.next) if (e.hash == h && ((Entry) e).key.equals(key)) return (Entry) e; Entry entry = new Entry(); entry.next = t [index]; entry.hash = h; entry.key = key; t[index] = entry; if ( ++size == threshold ) resize(2* t.length); return entry; } public Entry getOrPutEntry(Entry element) { Object key = element.key; int h = element.hash; final ComplexKeyHashMap.Entry[] t = table; final int index = h & (t.length - 1); ComplexKeyHashMap.Entry e = t[index]; for (; e != null; e = e.next) if (e.hash == h && ((Entry) e).key.equals(key)) return (Entry) e; Entry entry = new Entry(); entry.next = t [index]; entry.hash = h; entry.key = key; t[index] = entry; if ( ++size == threshold ) resize(2* t.length); return entry; } public Entry putCopyOfUnexisting(Entry ee) { int h = ee.hash; final ComplexKeyHashMap.Entry[] t = table; final int index = h & (t.length - 1); Entry entry = new Entry(); entry.next = t [index]; entry.hash = h; entry.key = ee.key; entry.value = ee.value; t[index] = entry; if ( ++size == threshold ) resize(2* t.length); return entry; } public final ComplexKeyHashMap.Entry remove(Object key) { int h = hash (key.hashCode()); int index = h & (table.length -1); for (ComplexKeyHashMap.Entry e = table [index], prev = null; e != null; prev = e, e = e.next ) { if (e.hash == h && ((Entry) e).key.equals(key)) { if (prev == null) table [index] = e.next; else prev.next = e.next; size--; e.next = null; return e; } } return null; } public static SingleKeyHashMap copy (SingleKeyHashMap dst, SingleKeyHashMap src, Copier copier) { dst.threshold = src.threshold; dst.size = src.size; final int len = src.table.length; final ComplexKeyHashMap.Entry[] t = new ComplexKeyHashMap.Entry[len], tt = src.table; for (int i = 0; i != len; ++i) { for (Entry e = (Entry) tt[i]; e != null; e = (Entry) e.next) { Entry ee = new Entry(); ee.hash = e.hash; ee.key = e.key; ee.value = copier.copy(e.value); ee.next = t [i]; t [i] = ee; } } dst.table = t; return dst; } public interface Copier { Object copy (Object value); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/Reference.java0000644001501200150120000000137211627206700023535 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public interface Reference { T get(); void clear(); V getHandler(); } groovy-1.8.6/src/main/org/codehaus/groovy/util/TripleKeyHashMap.java0000644001501200150120000000516311627206700025013 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; public class TripleKeyHashMap extends ComplexKeyHashMap { public static class Entry extends ComplexKeyHashMap.Entry{ public Object key1, key2, key3; } public final Object get(Object key1, Object key2, Object key3) { int h = hash (31*(31*key1.hashCode()+key2.hashCode())+key3.hashCode()); ComplexKeyHashMap.Entry e = table [h & (table.length-1)]; for (; e != null; e = e.next) if (e.hash == h && checkEquals((Entry) e, key1, key2, key3)) return e; return null; } public boolean checkEquals(Entry e, Object key1, Object key2, Object key3) { return e.key1.equals(key1) && e.key2.equals(key2) && e.key3.equals(key3); } public Entry getOrPut(Object key1, Object key2, Object key3) { int h = hash (31*(31*key1.hashCode()+key2.hashCode())+key3.hashCode()); final int index = h & (table.length - 1); ComplexKeyHashMap.Entry e = table [index]; for (; e != null; e = e.next) if (e.hash == h && checkEquals((Entry) e, key1, key2, key3)) return (Entry) e; Entry entry = createEntry (); entry.next = table [index]; entry.hash = h; entry.key1 = key1; entry.key2 = key2; entry.key3 = key3; table [index] = entry; if ( ++size == threshold ) resize(2*table.length); return entry; } public Entry createEntry() { return new Entry (); } public final ComplexKeyHashMap.Entry remove(Object key1, Object key2, Object key3) { int h = hash (31*(31*key1.hashCode()+key2.hashCode())+key3.hashCode()); int index = h & (table.length -1); for (ComplexKeyHashMap.Entry e = table [index], prev = null; e != null; prev = e, e = e.next ) { if (e.hash == h && checkEquals((Entry) e, key1, key2, key3)) { if (prev == null) table [index] = e.next; else prev.next = e.next; size--; e.next = null; return e; } } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/util/LazyReference.java0000644001501200150120000000431511627206700024375 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; /** * Soft reference with lazy initialization under lock */ public abstract class LazyReference extends LockableObject { private static final ManagedReference INIT = new ManagedReference(ReferenceType.HARD,null,null){}; private static final ManagedReference NULL_REFERENCE = new ManagedReference(ReferenceType.HARD,null,null){}; private ManagedReference reference = INIT; private final ReferenceBundle bundle; public LazyReference(ReferenceBundle bundle) { this.bundle = bundle; } public T get() { ManagedReference resRef = reference; if (resRef == INIT) return getLocked(false); if (resRef == NULL_REFERENCE) return null; T res = resRef.get(); // res== null means it got collected if (res==null) return getLocked(true); return res; } private T getLocked (boolean force) { lock (); try { ManagedReference resRef = reference; if (!force && resRef != INIT) return resRef.get(); T res = initValue(); if (res == null) { reference = NULL_REFERENCE; } else { reference = new ManagedReference(bundle,res); } return res; } finally { unlock(); } } public void clear() { reference = INIT; } public abstract T initValue(); public String toString() { T res = reference.get(); if (res == null) return ""; else return res.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/util/FastArray.java0000644001501200150120000000635111627206700023535 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.util; import java.util.AbstractList; import java.util.Collection; import java.util.List; public class FastArray implements Cloneable { private Object[] data; public int size; public static final FastArray EMPTY_LIST = new FastArray(0); public FastArray(int initialCapacity) { data = new Object[initialCapacity]; } public FastArray() { this (8); } public FastArray(Collection c) { this (c.toArray()); } public FastArray(Object[] objects) { data = objects; size = objects.length; } public Object get(int index) { return data [index]; } public void add(Object o) { if (size == data.length) { Object [] newData = new Object[size == 0 ? 8 : size*2]; System.arraycopy(data, 0, newData, 0, size); data = newData; } data [size++] = o; } public void set(int index, Object o) { data [index] = o; } public int size() { return size; } public void clear() { data = new Object[data.length]; size = 0; } public void addAll(FastArray newData) { addAll(newData.data, newData.size); } public void addAll(Object [] newData, int size) { if (size == 0) return; final int newSize = this.size + size; if (newSize > data.length) { Object nd [] = new Object [newSize]; System.arraycopy(data, 0, nd, 0, this.size); data = nd; } System.arraycopy(newData, 0, data, this.size, size); this.size = newSize; } public FastArray copy() { final Object[] newData = new Object[size]; System.arraycopy(data, 0, newData, 0, size); return new FastArray(newData); } public boolean isEmpty() { return size == 0; } public void addAll(List coll) { final Object[] newData = coll.toArray(); addAll(newData, newData.length); } public void remove(int index) { int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(data, index+1, data, index, numMoved); data[--size] = null; } public List toList () { return new AbstractList() { public Object get(int index) { return FastArray.this.get(index); } public int size() { return size; } }; } public Object[] getArray() { return data; } public String toString() { if (size() == 0) return "[]"; return toList().toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/0000755001501200150120000000000011715031256021477 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/InvokerHelper.java0000644001501200150120000007465611715031256025141 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.*; import groovy.xml.XmlUtil; import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl; import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed; import org.codehaus.groovy.runtime.powerassert.PowerAssertionError; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.wrappers.PojoWrapper; import org.codehaus.groovy.util.ReleaseInfo; import org.w3c.dom.Element; import java.beans.Introspector; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A static helper class to make bytecode generation easier and act as a facade over the Invoker * * @author James Strachan * @version $Revision$ */ public class InvokerHelper { private static final Object[] EMPTY_MAIN_ARGS = new Object[]{new String[0]}; public static final Object[] EMPTY_ARGS = {}; protected static final Object[] EMPTY_ARGUMENTS = EMPTY_ARGS; protected static final Class[] EMPTY_TYPES = {}; public static final MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); public static void removeClass(Class clazz) { metaRegistry.removeMetaClass(clazz); Introspector.flushFromCaches(clazz); } public static Object invokeMethodSafe(Object object, String methodName, Object arguments) { if (object != null) { return invokeMethod(object, methodName, arguments); } return null; } public static Object invokeStaticMethod(String klass, String methodName, Object arguments) throws ClassNotFoundException { Class type = Class.forName(klass); return invokeStaticMethod(type, methodName, arguments); } public static Object invokeStaticNoArgumentsMethod(Class type, String methodName) { return invokeStaticMethod(type, methodName, EMPTY_ARGS); } public static Object invokeConstructorOf(String klass, Object arguments) throws ClassNotFoundException { Class type = Class.forName(klass); return invokeConstructorOf(type, arguments); } public static Object invokeNoArgumentsConstructorOf(Class type) { return invokeConstructorOf(type, EMPTY_ARGS); } public static Object invokeClosure(Object closure, Object arguments) { return invokeMethod(closure, "doCall", arguments); } public static List asList(Object value) { if (value == null) { return Collections.EMPTY_LIST; } if (value instanceof List) { return (List) value; } if (value.getClass().isArray()) { return Arrays.asList((Object[]) value); } if (value instanceof Enumeration) { List answer = new ArrayList(); for (Enumeration e = (Enumeration) value; e.hasMoreElements();) { answer.add(e.nextElement()); } return answer; } // lets assume its a collection of 1 return Collections.singletonList(value); } public static String toString(Object arguments) { if (arguments instanceof Object[]) return toArrayString((Object[]) arguments); if (arguments instanceof Collection) return toListString((Collection) arguments); if (arguments instanceof Map) return toMapString((Map) arguments); return format(arguments, false); } public static String inspect(Object self) { return format(self, true); } public static Object getAttribute(Object object, String attribute) { if (object == null) { object = NullObject.getNullObject(); } if (object instanceof Class) { return metaRegistry.getMetaClass((Class) object).getAttribute(object, attribute); } else if (object instanceof GroovyObject) { return ((GroovyObject) object).getMetaClass().getAttribute(object, attribute); } else { return metaRegistry.getMetaClass(object.getClass()).getAttribute(object, attribute); } } public static void setAttribute(Object object, String attribute, Object newValue) { if (object == null) { object = NullObject.getNullObject(); } if (object instanceof Class) { metaRegistry.getMetaClass((Class) object).setAttribute(object, attribute, newValue); } else if (object instanceof GroovyObject) { ((GroovyObject) object).getMetaClass().setAttribute(object, attribute, newValue); } else { metaRegistry.getMetaClass(object.getClass()).setAttribute(object, attribute, newValue); } } public static Object getProperty(Object object, String property) { if (object == null) { object = NullObject.getNullObject(); } if (object instanceof GroovyObject) { GroovyObject pogo = (GroovyObject) object; return pogo.getProperty(property); } else if (object instanceof Class) { Class c = (Class) object; return metaRegistry.getMetaClass(c).getProperty(object, property); } else { return ((MetaClassRegistryImpl) metaRegistry).getMetaClass(object).getProperty(object, property); } } public static Object getPropertySafe(Object object, String property) { if (object != null) { return getProperty(object, property); } return null; } public static void setProperty(Object object, String property, Object newValue) { if (object == null) { object = NullObject.getNullObject(); } if (object instanceof GroovyObject) { GroovyObject pogo = (GroovyObject) object; pogo.setProperty(property, newValue); } else if (object instanceof Class) { metaRegistry.getMetaClass((Class) object).setProperty((Class) object, property, newValue); } else { ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(object).setProperty(object, property, newValue); } } /** * This is so we don't have to reorder the stack when we call this method. * At some point a better name might be in order. */ public static void setProperty2(Object newValue, Object object, String property) { setProperty(object, property, newValue); } /** * This is so we don't have to reorder the stack when we call this method. * At some point a better name might be in order. */ public static void setGroovyObjectProperty(Object newValue, GroovyObject object, String property) { object.setProperty(property, newValue); } public static Object getGroovyObjectProperty(GroovyObject object, String property) { return object.getProperty(property); } /** * This is so we don't have to reorder the stack when we call this method. * At some point a better name might be in order. */ public static void setPropertySafe2(Object newValue, Object object, String property) { if (object != null) { setProperty2(newValue, object, property); } } /** * Returns the method pointer for the given object name */ public static Closure getMethodPointer(Object object, String methodName) { if (object == null) { throw new NullPointerException("Cannot access method pointer for '" + methodName + "' on null object"); } return new MethodClosure(object, methodName); } public static Object unaryMinus(Object value) { if (value instanceof Integer) { Integer number = (Integer) value; return Integer.valueOf(-number.intValue()); } if (value instanceof Long) { Long number = (Long) value; return -number; } if (value instanceof BigInteger) { return ((BigInteger) value).negate(); } if (value instanceof BigDecimal) { return ((BigDecimal) value).negate(); } if (value instanceof Double) { Double number = (Double) value; return -number; } if (value instanceof Float) { Float number = (Float) value; return -number; } if (value instanceof Short) { Short number = (Short) value; return Short.valueOf((short) -number.shortValue()); } if (value instanceof Byte) { Byte number = (Byte) value; return Byte.valueOf((byte) -number.byteValue()); } if (value instanceof ArrayList) { // value is an list. List newlist = new ArrayList(); Iterator it = ((ArrayList) value).iterator(); for (; it.hasNext();) { newlist.add(unaryMinus(it.next())); } return newlist; } return invokeMethod(value, "negative", EMPTY_ARGS); } public static Object unaryPlus(Object value) { if (value instanceof Integer || value instanceof Long || value instanceof BigInteger || value instanceof BigDecimal || value instanceof Double || value instanceof Float || value instanceof Short || value instanceof Byte) { return value; } if (value instanceof ArrayList) { // value is a list. List newlist = new ArrayList(); Iterator it = ((ArrayList) value).iterator(); for (; it.hasNext();) { newlist.add(unaryPlus(it.next())); } return newlist; } return invokeMethod(value, "positive", EMPTY_ARGS); } /** * Find the right hand regex within the left hand string and return a matcher. * * @param left string to compare * @param right regular expression to compare the string to */ public static Matcher findRegex(Object left, Object right) { String stringToCompare; if (left instanceof String) { stringToCompare = (String) left; } else { stringToCompare = toString(left); } String regexToCompareTo; if (right instanceof String) { regexToCompareTo = (String) right; } else if (right instanceof Pattern) { Pattern pattern = (Pattern) right; return pattern.matcher(stringToCompare); } else { regexToCompareTo = toString(right); } return Pattern.compile(regexToCompareTo).matcher(stringToCompare); } /** * Find the right hand regex within the left hand string and return a matcher. * * @param left string to compare * @param right regular expression to compare the string to */ public static boolean matchRegex(Object left, Object right) { if (left == null || right == null) return false; Pattern pattern; if (right instanceof Pattern) { pattern = (Pattern) right; } else { pattern = Pattern.compile(toString(right)); } String stringToCompare = toString(left); Matcher matcher = pattern.matcher(stringToCompare); RegexSupport.setLastMatcher(matcher); return matcher.matches(); } public static Tuple createTuple(Object[] array) { return new Tuple(array); } public static SpreadMap spreadMap(Object value) { if (value instanceof Map) { Object[] values = new Object[((Map) value).keySet().size() * 2]; int index = 0; Iterator it = ((Map) value).keySet().iterator(); for (; it.hasNext();) { Object key = it.next(); values[index++] = key; values[index++] = ((Map) value).get(key); } return new SpreadMap(values); } throw new SpreadMapEvaluatingException("Cannot spread the map " + value.getClass().getName() + ", value " + value); } public static List createList(Object[] values) { List answer = new ArrayList(values.length); answer.addAll(Arrays.asList(values)); return answer; } public static Map createMap(Object[] values) { Map answer = new LinkedHashMap(values.length / 2); int i = 0; while (i < values.length - 1) { if ((values[i] instanceof SpreadMap) && (values[i + 1] instanceof Map)) { Map smap = (Map) values[i + 1]; Iterator iter = smap.keySet().iterator(); for (; iter.hasNext();) { Object key = iter.next(); answer.put(key, smap.get(key)); } i += 2; } else { answer.put(values[i++], values[i++]); } } return answer; } public static void assertFailed(Object expression, Object message) { if (message == null || "".equals(message)) { throw new PowerAssertionError(expression.toString()); } throw new AssertionError(String.valueOf(message) + ". Expression: " + expression); } public static Object runScript(Class scriptClass, String[] args) { Binding context = new Binding(args); Script script = createScript(scriptClass, context); return invokeMethod(script, "run", EMPTY_ARGS); } public static Script createScript(Class scriptClass, Binding context) { Script script = null; // for empty scripts if (scriptClass == null) { script = new Script() { public Object run() { return null; } }; } else { try { final GroovyObject object = (GroovyObject) scriptClass .newInstance(); if (object instanceof Script) { script = (Script) object; } else { // it could just be a class, so lets wrap it in a Script // wrapper // though the bindings will be ignored script = new Script() { public Object run() { Object args = getBinding().getVariables().get("args"); Object argsToPass = EMPTY_MAIN_ARGS; if (args != null && args instanceof String[]) { argsToPass = args; } object.invokeMethod("main", argsToPass); return null; } }; setProperties(object, context.getVariables()); } } catch (Exception e) { throw new GroovyRuntimeException( "Failed to create Script instance for class: " + scriptClass + ". Reason: " + e, e); } } script.setBinding(context); return script; } /** * Sets the properties on the given object */ public static void setProperties(Object object, Map map) { MetaClass mc = getMetaClass(object); for (Object o : map.entrySet()) { Map.Entry entry = (Map.Entry) o; String key = entry.getKey().toString(); Object value = entry.getValue(); try { mc.setProperty(object, key, value); } catch (MissingPropertyException mpe) { // Ignore } } } /** * @deprecated Use GroovySystem version instead. */ public static String getVersion() { return ReleaseInfo.getVersion(); } /** * Writes the given object to the given stream */ public static void write(Writer out, Object object) throws IOException { if (object instanceof String) { out.write((String) object); } else if (object instanceof Object[]) { out.write(toArrayString((Object[]) object)); } else if (object instanceof Map) { out.write(toMapString((Map) object)); } else if (object instanceof Collection) { out.write(toListString((Collection) object)); } else if (object instanceof Writable) { Writable writable = (Writable) object; writable.writeTo(out); } else if (object instanceof InputStream || object instanceof Reader) { // Copy stream to stream Reader reader; if (object instanceof InputStream) { reader = new InputStreamReader((InputStream) object); } else { reader = (Reader) object; } char[] chars = new char[8192]; int i; while ((i = reader.read(chars)) != -1) { out.write(chars, 0, i); } reader.close(); } else { out.write(toString(object)); } } @SuppressWarnings("unchecked") public static Iterator asIterator(Object o) { return (Iterator) invokeMethod(o, "iterator", EMPTY_ARGS); } protected static String format(Object arguments, boolean verbose) { return format(arguments, verbose, -1); } public static String format(Object arguments, boolean verbose, int maxSize) { if (arguments == null) { final NullObject nullObject = NullObject.getNullObject(); return (String) nullObject.getMetaClass().invokeMethod(nullObject, "toString", EMPTY_ARGS); } if (arguments.getClass().isArray()) { if (arguments instanceof char[]) { return new String((char[]) arguments); } return format(DefaultTypeTransformation.asCollection(arguments), verbose, maxSize); } if (arguments instanceof Range) { Range range = (Range) arguments; if (verbose) { return range.inspect(); } else { return range.toString(); } } if (arguments instanceof Collection) { return formatList((Collection) arguments, verbose, maxSize); } if (arguments instanceof Map) { return formatMap((Map) arguments, verbose, maxSize); } if (arguments instanceof Element) { return XmlUtil.serialize((Element) arguments); } if (arguments instanceof String) { if (verbose) { String arg = ((String) arguments).replaceAll("\\n", "\\\\n"); // line feed arg = arg.replaceAll("\\r", "\\\\r"); // carriage return arg = arg.replaceAll("\\t", "\\\\t"); // tab arg = arg.replaceAll("\\f", "\\\\f"); // form feed arg = arg.replaceAll("'", "\\\\'"); // single quotation mark arg = arg.replaceAll("\\\\", "\\\\"); // backslash return "\'" + arg + "\'"; } else { return (String) arguments; } } // TODO: For GROOVY-2599 do we need something like below but it breaks other things // return (String) invokeMethod(arguments, "toString", EMPTY_ARGS); return arguments.toString(); } private static String formatMap(Map map, boolean verbose, int maxSize) { if (map.isEmpty()) { return "[:]"; } StringBuffer buffer = new StringBuffer("["); boolean first = true; for (Object o : map.entrySet()) { if (first) { first = false; } else { buffer.append(", "); } if (maxSize != -1 && buffer.length() > maxSize) { buffer.append("..."); break; } Map.Entry entry = (Map.Entry) o; buffer.append(format(entry.getKey(), verbose)); buffer.append(":"); if (entry.getValue() == map) { buffer.append("(this Map)"); } else { buffer.append(format(entry.getValue(), verbose, sizeLeft(maxSize, buffer))); } } buffer.append("]"); return buffer.toString(); } private static int sizeLeft(int maxSize, StringBuffer buffer) { return maxSize == -1 ? maxSize : Math.max(0, maxSize - buffer.length()); } private static String formatList(Collection collection, boolean verbose, int maxSize) { StringBuffer buffer = new StringBuffer("["); boolean first = true; for (Object item : collection) { if (first) { first = false; } else { buffer.append(", "); } if (maxSize != -1 && buffer.length() > maxSize) { buffer.append("..."); break; } if (item == collection) { buffer.append("(this Collection)"); } else { buffer.append(format(item, verbose, sizeLeft(maxSize, buffer))); } } buffer.append("]"); return buffer.toString(); } /** * A helper method to format the arguments types as a comma-separated list. * * @param arguments the type to process * @return the string representation of the type */ public static String toTypeString(Object[] arguments) { if (arguments == null) { return "null"; } StringBuffer argBuf = new StringBuffer(); for (int i = 0; i < arguments.length; i++) { if (i > 0) { argBuf.append(", "); } argBuf.append(arguments[i] != null ? arguments[i].getClass().getName() : "null"); } return argBuf.toString(); } /** * A helper method to return the string representation of a map with bracket boundaries "[" and "]". * * @param arg the map to process * @return the string representation of the map */ public static String toMapString(Map arg) { return toMapString(arg, -1); } /** * A helper method to return the string representation of a map with bracket boundaries "[" and "]". * * @param arg the map to process * @param maxSize stop after approximately this many characters and append '...' * @return the string representation of the map */ public static String toMapString(Map arg, int maxSize) { return formatMap(arg, false, maxSize); } /** * A helper method to return the string representation of a list with bracket boundaries "[" and "]". * * @param arg the collection to process * @return the string representation of the collection */ public static String toListString(Collection arg) { return toListString(arg, -1); } /** * A helper method to return the string representation of a list with bracket boundaries "[" and "]". * * @param arg the collection to process * @param maxSize stop after approximately this many characters and append '...' * @return the string representation of the collection */ public static String toListString(Collection arg, int maxSize) { return formatList(arg, false, maxSize); } /** * A helper method to return the string representation of an array of objects * with brace boundaries "{" and "}". * * @param arguments the array to process * @return the string representation of the array */ public static String toArrayString(Object[] arguments) { if (arguments == null) { return "null"; } String sbdry = "["; String ebdry = "]"; StringBuffer argBuf = new StringBuffer(sbdry); for (int i = 0; i < arguments.length; i++) { if (i > 0) { argBuf.append(", "); } argBuf.append(format(arguments[i], false)); } argBuf.append(ebdry); return argBuf.toString(); } public static List createRange(Object from, Object to, boolean inclusive) { try { return ScriptBytecodeAdapter.createRange(from, to, inclusive); } catch (RuntimeException re) { throw re; } catch (Error e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } public static Object bitwiseNegate(Object value) { if (value instanceof Integer) { Integer number = (Integer) value; return ~number; } if (value instanceof Long) { Long number = (Long) value; return ~number; } if (value instanceof BigInteger) { return ((BigInteger) value).not(); } if (value instanceof String) { // value is a regular expression. return DefaultGroovyMethods.bitwiseNegate(value.toString()); } if (value instanceof GString) { // value is a regular expression. return DefaultGroovyMethods.bitwiseNegate(value.toString()); } if (value instanceof ArrayList) { // value is an list. List newlist = new ArrayList(); Iterator it = ((ArrayList) value).iterator(); for (; it.hasNext();) { newlist.add(bitwiseNegate(it.next())); } return newlist; } return invokeMethod(value, "bitwiseNegate", EMPTY_ARGS); } public static MetaClassRegistry getMetaRegistry() { return metaRegistry; } public static MetaClass getMetaClass(Object object) { if (object instanceof GroovyObject) return ((GroovyObject) object).getMetaClass(); else return ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(object); } public static MetaClass getMetaClass(Class cls) { return metaRegistry.getMetaClass(cls); } /** * Invokes the given method on the object. */ public static Object invokeMethod(Object object, String methodName, Object arguments) { if (object == null) { object = NullObject.getNullObject(); //throw new NullPointerException("Cannot invoke method " + methodName + "() on null object"); } // if the object is a Class, call a static method from that class if (object instanceof Class) { Class theClass = (Class) object; MetaClass metaClass = metaRegistry.getMetaClass(theClass); return metaClass.invokeStaticMethod(object, methodName, asArray(arguments)); } // it's an instance; check if it's a Java one if (!(object instanceof GroovyObject)) { return invokePojoMethod(object, methodName, arguments); } // a groovy instance (including builder, closure, ...) return invokePogoMethod(object, methodName, arguments); } static Object invokePojoMethod(Object object, String methodName, Object arguments) { MetaClass metaClass = InvokerHelper.getMetaClass(object); return metaClass.invokeMethod(object, methodName, asArray(arguments)); } static Object invokePogoMethod(Object object, String methodName, Object arguments) { GroovyObject groovy = (GroovyObject) object; boolean intercepting = groovy instanceof GroovyInterceptable; try { // if it's a pure interceptable object (even intercepting toString(), clone(), ...) if (intercepting) { return groovy.invokeMethod(methodName, asUnwrappedArray(arguments)); } //else try a statically typed method or a GDK method return groovy.getMetaClass().invokeMethod(object, methodName, asArray(arguments)); } catch (MissingMethodException e) { if (e instanceof MissingMethodExecutionFailed) { throw (MissingMethodException) e.getCause(); } else if (!intercepting && e.getMethod().equals(methodName) && object.getClass() == e.getType()) { // in case there's nothing else, invoke the object's own invokeMethod() return groovy.invokeMethod(methodName, asUnwrappedArray(arguments)); } else { throw e; } } } public static Object invokeSuperMethod(Object object, String methodName, Object arguments) { if (object == null) { throw new NullPointerException("Cannot invoke method " + methodName + "() on null object"); } Class theClass = object.getClass(); MetaClass metaClass = metaRegistry.getMetaClass(theClass.getSuperclass()); return metaClass.invokeMethod(object, methodName, asArray(arguments)); } public static Object invokeStaticMethod(Class type, String method, Object arguments) { MetaClass metaClass = metaRegistry.getMetaClass(type); return metaClass.invokeStaticMethod(type, method, asArray(arguments)); } public static Object invokeConstructorOf(Class type, Object arguments) { MetaClass metaClass = metaRegistry.getMetaClass(type); return metaClass.invokeConstructor(asArray(arguments)); } /** * Converts the given object into an array; if its an array then just * cast otherwise wrap it in an array */ public static Object[] asArray(Object arguments) { if (arguments == null) { return EMPTY_ARGUMENTS; } if (arguments instanceof Object[]) { return (Object[]) arguments; } return new Object[]{arguments}; } public static Object[] asUnwrappedArray(Object arguments) { Object[] args = asArray(arguments); for (int i = 0; i < args.length; i++) { if (args[i] instanceof PojoWrapper) { args[i] = ((PojoWrapper) args[i]).unwrap(); } } return args; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DefaultCachedMethodKey.java0000644001501200150120000000264011627206700026632 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import org.codehaus.groovy.reflection.CachedClass; /** * A default implementation of MethodKey * * @author James Strachan * @version $Revision: 7922 $ */ public class DefaultCachedMethodKey extends MethodKey{ private final CachedClass[] parameterTypes; public DefaultCachedMethodKey(Class sender, String name, CachedClass[] parameterTypes, boolean isCallToSuper) { super(sender, name,isCallToSuper); this.parameterTypes = parameterTypes; } public int getParameterCount() { return parameterTypes.length; } public Class getParameterType(int index) { CachedClass c = parameterTypes[index]; if (c==null) return Object.class; return c.getTheClass(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/0000755001501200150120000000000011707612046023345 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/Wrapper.java0000644001501200150120000000250411707612046025631 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; import groovy.lang.GroovyObject; import groovy.lang.MetaClass; /** * @author John Wilson */ public abstract class Wrapper implements GroovyObject { protected final Class constrainedType; public Wrapper(final Class constrainedType) { this.constrainedType = constrainedType; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getMetaClass() */ public MetaClass getMetaClass() { return getDelegatedMetaClass(); } public Class getType() { return this.constrainedType; } public abstract Object unwrap(); protected abstract Object getWrapped(); protected abstract MetaClass getDelegatedMetaClass(); } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/GroovyObjectWrapper.java0000644001501200150120000000417111627206700030165 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; import groovy.lang.GroovyObject; import groovy.lang.MetaClass; /** * @author John Wilson */ public class GroovyObjectWrapper extends Wrapper { protected final GroovyObject wrapped; public GroovyObjectWrapper(final GroovyObject wrapped, final Class constrainedType) { super(constrainedType); this.wrapped = wrapped; } public Object unwrap() { return this.wrapped; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getProperty(java.lang.String) */ public Object getProperty(final String property) { return this.wrapped.getProperty(property); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object) */ public Object invokeMethod(final String name, final Object args) { return this.wrapped.invokeMethod(name, args); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setMetaClass(groovy.lang.MetaClass) */ public void setMetaClass(final MetaClass metaClass) { this.wrapped.setMetaClass(metaClass); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(final String property, final Object newValue) { this.wrapped.setProperty(property, newValue); } protected Object getWrapped() { return this.wrapped; } protected MetaClass getDelegatedMetaClass() { return this.wrapped.getMetaClass(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/ShortWrapper.java0000644001501200150120000000150311627206700026644 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson * */ public class ShortWrapper extends PojoWrapper { public ShortWrapper(final short wrapped) { super(wrapped, short.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/DoubleWrapper.java0000644001501200150120000000151311627206700026760 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class DoubleWrapper extends PojoWrapper { public DoubleWrapper(final double wrapped) { super(wrapped, double.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.java0000644001501200150120000000150711627206700026616 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class FloatWrapper extends PojoWrapper { public FloatWrapper(final float wrapped) { super(wrapped, float.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/package.html0000644001501200150120000000025611627206700025626 0ustar miguelmiguel package org.codehaus.groovy.runtime.wrappers.*

      Groovy wrapper classes for primitive types.

      groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/LongWrapper.java0000644001501200150120000000150311627206700026444 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class LongWrapper extends PojoWrapper { public LongWrapper(final long wrapped) { super(wrapped, long.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/ByteWrapper.java0000644001501200150120000000150311627206700026450 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class ByteWrapper extends PojoWrapper { public ByteWrapper(final byte wrapped) { super(wrapped, byte.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/CharWrapper.java0000644001501200150120000000150311627206700026422 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class CharWrapper extends PojoWrapper { public CharWrapper(final char wrapped) { super(wrapped, char.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/PojoWrapper.java0000644001501200150120000000421011627206700026452 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; import groovy.lang.MetaClass; /** * @author John Wilson */ public class PojoWrapper extends Wrapper { protected MetaClass delegate; protected final Object wrapped; public PojoWrapper(final Object wrapped, final Class constrainedType) { super(constrainedType); this.wrapped = wrapped; } public Object unwrap() { return this.wrapped; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#getProperty(java.lang.String) */ public Object getProperty(final String property) { return this.delegate.getProperty(this.wrapped, property); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object) */ public Object invokeMethod(final String methodName, final Object arguments) { return this.delegate.invokeMethod(this.wrapped, methodName, arguments); } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setMetaClass(groovy.lang.MetaClass) */ public void setMetaClass(final MetaClass metaClass) { this.delegate = metaClass; } /* (non-Javadoc) * @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) */ public void setProperty(final String property, final Object newValue) { this.delegate.setProperty(this.wrapped, property, newValue); } protected Object getWrapped() { return this.wrapped; } protected MetaClass getDelegatedMetaClass() { return this.delegate; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/IntWrapper.java0000644001501200150120000000147611627206700026310 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class IntWrapper extends PojoWrapper { public IntWrapper(final int wrapped) { super(wrapped, int.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/wrappers/BooleanWrapper.java0000644001501200150120000000155611627206700027134 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.wrappers; /** * @author John Wilson */ public class BooleanWrapper extends PojoWrapper { public BooleanWrapper(final boolean wrapped) { super(wrapped ? Boolean.TRUE : Boolean.FALSE, boolean.class); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/WritableFile.java0000644001501200150120000000321611627206700024715 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Writable; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * A Writable File. * * @author John Wilson * */ public class WritableFile extends File implements Writable { private final String encoding; public WritableFile(final File delegate) { this(delegate, null); } public WritableFile(final File delegate, final String encoding) { super(delegate.toURI()); this.encoding = encoding; } public Writer writeTo(final Writer out) throws IOException { final Reader reader = (this.encoding == null) ? DefaultGroovyMethods.newReader(this) : DefaultGroovyMethods.newReader(this, this.encoding); try { int c = reader.read(); while (c != -1) { out.write(c); c = reader.read(); } } finally { reader.close(); } return out; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ConvertedMap.java0000644001501200150120000000452511645141222024734 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.lang.reflect.Method; import java.util.Map; import groovy.lang.Closure; /** * This class is a general adapter to adapt a map of closures to * any Java interface. *

      * * @author Jochen Theodorou */ public class ConvertedMap extends ConversionHandler { /** * to create a ConvertedMap object. * * @param closures the map of closures */ protected ConvertedMap(Map closures) { super(closures); } public Object invokeCustom(Object proxy, Method method, Object[] args) throws Throwable { Map m = (Map) getDelegate(); Closure cl = (Closure) m.get(method.getName()); if(cl == null && "toString".equals(method.getName())) { return m.toString(); } if (cl == null) { throw new UnsupportedOperationException(); } return cl.call(args); } public String toString() { return DefaultGroovyMethods.toString(getDelegate()); } protected boolean checkMethod(Method method) { return isCoreObjectMethod(method); } /** * Checks whether a method is a core method from java.lang.Object. * Such methods often receive special treatment because they are * deemed fundamental enough to not be tampered with. * call toString() is an exception to allow overriding toString() by a closure specified in the map * * @param method the method to check * @return true if the method is deemed to be a core method */ public static boolean isCoreObjectMethod(Method method) { return ConversionHandler.isCoreObjectMethod(method) && !"toString".equals(method.getName()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ReverseListIterator.java0000644001501200150120000000337311627206700026331 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * A reverse iterator over a list. Utilizes the {@link ListIterator} * obtained from the provided {@link List} and converts it to an * {@link Iterator} that efficiently traverses the List in * reverse. The fail-fast semantics of this iterator are the same as the * semantics of the underlying ListIterator. * * @author Mike Dillon */ public class ReverseListIterator implements Iterator { private ListIterator delegate; /** * Constructs a new ReverseListIterator for the provided list. * @param list the list to iterate over in reverse */ public ReverseListIterator(List list) { this.delegate = list.listIterator(list.size()); } /** * {@inheritDoc} */ public boolean hasNext() { return delegate.hasPrevious(); } /** * {@inheritDoc} */ public T next() { return delegate.previous(); } /** * {@inheritDoc} */ public void remove() { delegate.remove(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ReflectionMethodInvoker.java0000644001501200150120000000405411707612046027141 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.lang.reflect.Method; /** * Utility class to call methods through reflection, and falls through using the Invoker to call the method if it fails. * The class is particularly useful for Groovy classes implementing GroovyInterceptable, * since it is not possible to call any method from this class, * because it is intercepted by the invokeMethod() method. * * @author Guillaume Laforge */ public class ReflectionMethodInvoker { /** * Invoke a method through reflection. * Falls through to using the Invoker to call the method in case the reflection call fails.. * * @param object the object on which to invoke a method * @param methodName the name of the method to invoke * @param parameters the parameters of the method call * @return the result of the method call */ public static Object invoke(Object object, String methodName, Object[] parameters) { try { Class[] classTypes = new Class[parameters.length]; for (int i = 0; i < classTypes.length; i++) { classTypes[i] = parameters[i].getClass(); } Method method = object.getClass().getMethod(methodName, classTypes); return method.invoke(object, parameters); } catch (Throwable t) { return InvokerHelper.invokeMethod(object, methodName, parameters); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/MethodClosure.java0000644001501200150120000000405511627206700025123 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import groovy.lang.MetaMethod; import java.util.List; /** * Represents a method on an object using a closure which can be invoked * at any time * * @author James Strachan * @version $Revision$ */ public class MethodClosure extends Closure { private String method; public MethodClosure(Object owner, String method) { super(owner); this.method = method; final Class clazz = owner.getClass()==Class.class?(Class) owner:owner.getClass(); maximumNumberOfParameters = 0; parameterTypes = new Class [0]; List methods = InvokerHelper.getMetaClass(clazz).respondsTo(owner, method); for(MetaMethod m : methods) { if (m.getParameterTypes().length > maximumNumberOfParameters) { Class[] pt = m.getNativeParameterTypes(); maximumNumberOfParameters = pt.length; parameterTypes = pt; } } } public String getMethod() { return method; } protected Object doCall(Object arguments) { return InvokerHelper.invokeMethod(getOwner(), method, arguments); } public Object getProperty(String property) { if ("method".equals(property)) { return getMethod(); } else return super.getProperty(property); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java0000644001501200150120000010260511715031256026572 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.*; import org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack; import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed; import org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.wrappers.GroovyObjectWrapper; import org.codehaus.groovy.runtime.wrappers.PojoWrapper; import org.codehaus.groovy.runtime.wrappers.Wrapper; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A static helper class to interface bytecode and runtime * * @author Jochen Theodorou * @version $Revision$ */ public class ScriptBytecodeAdapter { public static final Object[] EMPTY_ARGS = {}; private static final Integer ZERO = Integer.valueOf(0); private static final Integer MINUS_ONE = Integer.valueOf(-1); private static final Integer ONE = Integer.valueOf(1); // -------------------------------------------------------- // exception handling // -------------------------------------------------------- public static Throwable unwrap(GroovyRuntimeException gre) { if (gre instanceof MissingPropertyExceptionNoStack) { MissingPropertyExceptionNoStack noStack = (MissingPropertyExceptionNoStack) gre; return new MissingPropertyException(noStack.getProperty(), noStack.getType()); } if (gre instanceof MissingMethodExceptionNoStack) { MissingMethodExceptionNoStack noStack = (MissingMethodExceptionNoStack) gre; return new MissingMethodException(noStack.getMethod(), noStack.getType(), noStack.getArguments(), noStack.isStatic()); } Throwable th = gre; if (th.getCause() != null && th.getCause() != gre) th = th.getCause(); if (th != gre && (th instanceof GroovyRuntimeException)) return unwrap((GroovyRuntimeException) th); return th; } // -------------------------------------------------------- // methods for this // -------------------------------------------------------- public static Object invokeMethodOnCurrentN(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { Object result = null; boolean intercepting = receiver instanceof GroovyInterceptable; try { try { // if it's a pure interceptable object (even intercepting toString(), clone(), ...) if (intercepting) { result = receiver.invokeMethod(messageName, messageArguments); } //else if there's a statically typed method or a GDK method else { result = receiver.getMetaClass().invokeMethod(senderClass, receiver, messageName, messageArguments, false, true); } } catch (MissingMethodException e) { if (e instanceof MissingMethodExecutionFailed) { throw (MissingMethodException)e.getCause(); } else if (!intercepting && receiver.getClass() == e.getType() && e.getMethod().equals(messageName)) { // in case there's nothing else, invoke the object's own invokeMethod() result = receiver.invokeMethod(messageName, messageArguments); } else { throw e; } } } catch (GroovyRuntimeException gre) { throw unwrap(gre); } return result; } public static Object invokeMethodOnCurrentNSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnCurrentN(senderClass, receiver, messageName, messageArguments); } public static Object invokeMethodOnCurrentNSpreadSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(invokeMethodNSafe(senderClass, it.next(), messageName, messageArguments)); } return answer; } public static Object invokeMethodOnCurrent0(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { return invokeMethodOnCurrentN(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethodOnCurrent0Safe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnCurrentNSafe(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethodOnCurrent0SpreadSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnCurrentNSpreadSafe(senderClass, receiver, messageName, EMPTY_ARGS); } // -------------------------------------------------------- // methods for super // -------------------------------------------------------- public static Object invokeMethodOnSuperN(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { MetaClass metaClass = receiver.getMetaClass(); // ignore interception and missing method fallback Object result = null; try { result = metaClass.invokeMethod(senderClass, receiver, messageName, messageArguments, true, true); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } return result; } public static Object invokeMethodOnSuperNSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnSuperN(senderClass, receiver, messageName, messageArguments); } public static Object invokeMethodOnSuperNSpreadSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(invokeMethodNSafe(senderClass, it.next(), messageName, messageArguments)); } return answer; } public static Object invokeMethodOnSuper0(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { return invokeMethodOnSuperN(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethodOnSuper0Safe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnSuperNSafe(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethodOnSuper0SpreadSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { return invokeMethodOnSuperNSpreadSafe(senderClass, receiver, messageName, EMPTY_ARGS); } // -------------------------------------------------------- // normal method invocation // -------------------------------------------------------- public static Object invokeMethodN(Class senderClass, Object receiver, String messageName, Object[] messageArguments) throws Throwable { try { return InvokerHelper.invokeMethod(receiver, messageName, messageArguments); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object invokeMethodNSafe(Class senderClass, Object receiver, String messageName, Object[] messageArguments) throws Throwable { if (receiver == null) return null; return invokeMethodN(senderClass, receiver, messageName, messageArguments); } public static Object invokeMethodNSpreadSafe(Class senderClass, Object receiver, String messageName, Object[] messageArguments) throws Throwable { if (receiver == null) return null; List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(invokeMethodNSafe(senderClass, it.next(), messageName, messageArguments)); } return answer; } public static Object invokeMethod0(Class senderClass, Object receiver, String messageName) throws Throwable { return invokeMethodN(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethod0Safe(Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return null; return invokeMethodNSafe(senderClass, receiver, messageName, EMPTY_ARGS); } public static Object invokeMethod0SpreadSafe(Class senderClass, Object receiver, String messageName) throws Throwable { return invokeMethodNSpreadSafe(senderClass, receiver, messageName, EMPTY_ARGS); } // -------------------------------------------------------- // static normal method invocation // -------------------------------------------------------- public static Object invokeStaticMethodN(Class senderClass, Class receiver, String messageName, Object[] messageArguments) throws Throwable { try { return InvokerHelper.invokeStaticMethod(receiver, messageName, messageArguments); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object invokeStaticMethod0(Class senderClass, Class receiver, String messageName) throws Throwable { return invokeStaticMethodN(senderClass, receiver, messageName, EMPTY_ARGS); } // -------------------------------------------------------- // normal constructor invocation (via new) // -------------------------------------------------------- public static Object invokeNewN(Class senderClass, Class receiver, Object arguments) throws Throwable { try { return InvokerHelper.invokeConstructorOf(receiver, arguments); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object invokeNew0(Class senderClass, Class receiver) throws Throwable { return invokeNewN(senderClass, receiver, EMPTY_ARGS); } // -------------------------------------------------------- // special constructor invocation (via this/super) // -------------------------------------------------------- public static int selectConstructorAndTransformArguments(Object[] arguments, int numberOfConstructors, Class which) throws Throwable { MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(which); try { return metaClass.selectConstructorAndTransformArguments(numberOfConstructors, arguments); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } // -------------------------------------------------------- // field handling super: get // -------------------------------------------------------- public static Object getFieldOnSuper(Class senderClass, Object receiver, String messageName) throws Throwable { try { if (receiver instanceof Class) { return InvokerHelper.getAttribute(receiver, messageName); } else { MetaClass mc = ((GroovyObject) receiver).getMetaClass(); return mc.getAttribute(senderClass, receiver, messageName, true); } } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object getFieldOnSuperSafe(Class senderClass, Object receiver, String messageName) throws Throwable { return getFieldOnSuper(senderClass, receiver, messageName); } public static Object getFieldOnSuperSpreadSafe(Class senderClass, Object receiver, String messageName) throws Throwable { List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getFieldOnSuper(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // field handling super: set // -------------------------------------------------------- public static void setFieldOnSuper(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { try { if (receiver instanceof Class) { InvokerHelper.setAttribute(receiver, messageName, messageArgument); } else { MetaClass mc = ((GroovyObject) receiver).getMetaClass(); mc.setAttribute(senderClass, receiver, messageName, messageArgument, true, true); } } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setFieldOnSuperSafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { setFieldOnSuper(messageArgument, senderClass, receiver, messageName); } public static void setFieldOnSuperSpreadSafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setFieldOnSuper(messageArgument, senderClass, it.next(), messageName); } } // -------------------------------------------------------- // normal field handling : get // -------------------------------------------------------- public static Object getField(Class senderClass, Object receiver, String messageName) throws Throwable { try { return InvokerHelper.getAttribute(receiver, messageName); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object getFieldSafe(Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return null; return getField(senderClass, receiver, messageName); } public static Object getFieldSpreadSafe(Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return null; List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getFieldSafe(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // normal field handling : set // -------------------------------------------------------- public static void setField(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { try { InvokerHelper.setAttribute(receiver, messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setFieldSafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return; setField(messageArgument, senderClass, receiver, messageName); } public static void setFieldSpreadSafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return; for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setFieldSafe(messageArgument, senderClass, it.next(), messageName); } } // -------------------------------------------------------- // normal GroovyObject field handling : get // -------------------------------------------------------- public static Object getGroovyObjectField(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { try { return receiver.getMetaClass().getAttribute(receiver, messageName); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object getGroovyObjectFieldSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return null; try { return receiver.getMetaClass().getAttribute(receiver, messageName); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object getGroovyObjectFieldSpreadSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return null; List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getFieldSafe(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // normal field handling : set // -------------------------------------------------------- public static void setGroovyObjectField(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { try { receiver.getMetaClass().setAttribute(receiver, messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setGroovyObjectFieldSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return; try { receiver.getMetaClass().setAttribute(receiver, messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setGroovyObjectFieldSpreadSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return; for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setFieldSafe(messageArgument, senderClass, it.next(), messageName); } } // -------------------------------------------------------- // Property handling super: get // -------------------------------------------------------- public static Object getPropertyOnSuper(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { return invokeMethodOnSuperN(senderClass, receiver, "getProperty", new Object[]{messageName}); } public static Object getPropertyOnSuperSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { return getPropertyOnSuper(senderClass, receiver, messageName); } public static Object getPropertyOnSuperSpreadSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getPropertySafe(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // Property handling super: set // -------------------------------------------------------- public static void setPropertyOnSuper(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { try { InvokerHelper.setAttribute(receiver, messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setPropertyOnSuperSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { setPropertyOnSuper(messageArgument, senderClass, receiver, messageName); } public static void setPropertyOnSuperSpreadSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setPropertySafe(messageArgument, senderClass, it.next(), messageName); } } // -------------------------------------------------------- // normal Property handling : get // -------------------------------------------------------- public static Object getProperty(Class senderClass, Object receiver, String messageName) throws Throwable { try { return InvokerHelper.getProperty(receiver, messageName); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object getPropertySafe(Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return null; return getProperty(senderClass, receiver, messageName); } public static Object getPropertySpreadSafe(Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return null; List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getPropertySafe(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // normal Property handling : set // -------------------------------------------------------- public static void setProperty(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { try { if (receiver==null) receiver=NullObject.getNullObject(); InvokerHelper.setProperty(receiver, messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setPropertySafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return; setProperty(messageArgument, senderClass, receiver, messageName); } public static void setPropertySpreadSafe(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { if (receiver == null) return; for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setPropertySafe(messageArgument, senderClass, it.next(), messageName); } } // -------------------------------------------------------- // normal GroovyObject Property handling : get // -------------------------------------------------------- public static Object getGroovyObjectProperty(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { return receiver.getProperty(messageName); } public static Object getGroovyObjectPropertySafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return null; return getGroovyObjectProperty(senderClass, receiver, messageName); } public static Object getGroovyObjectPropertySpreadSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return null; List answer = new ArrayList(); for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { answer.add(getPropertySafe(senderClass, it.next(), messageName)); } return answer; } // -------------------------------------------------------- // normal GroovyObject Property handling : set // -------------------------------------------------------- public static void setGroovyObjectProperty(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { try { receiver.setProperty(messageName, messageArgument); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static void setGroovyObjectPropertySafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return; receiver.setProperty(messageName, messageArgument); } public static void setGroovyObjectPropertySpreadSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable { if (receiver == null) return; for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) { setPropertySafe(messageArgument, senderClass, it.next(), messageName); } } // ********************************************************************************** // ********************************************************************************** // ************** methods not covered by the new MOP ************** // ********************************************************************************** // ********************************************************************************** // -------------------------------------------------------- // Closures // -------------------------------------------------------- /** * Returns the method pointer for the given object name * * @param object the object containing the method * @param methodName the name of the method of interest * @return the resulting Closure */ public static Closure getMethodPointer(Object object, String methodName) { return InvokerHelper.getMethodPointer(object, methodName); } // TODO: set sender class public static Object invokeClosure(Object closure, Object[] arguments) throws Throwable { return invokeMethodN(closure.getClass(), closure, "call", arguments); } // -------------------------------------------------------- // type conversion // -------------------------------------------------------- /** * Provides a hook for type coercion of the given object to the required type * * @param type of object to convert the given object to * @param object the object to be converted * @return the original object or a new converted value * @throws Throwable if the coercion fails */ public static Object asType(Object object, Class type) throws Throwable { if (object == null) object = NullObject.getNullObject(); return invokeMethodN(object.getClass(), object, "asType", new Object[]{type}); } /** * Provides a hook for type casting of the given object to the required type * * @param type of object to convert the given object to * @param object the object to be converted * @return the original object or a new converted value * @throws Throwable if the type casting fails */ public static Object castToType(Object object, Class type) throws Throwable { return DefaultTypeTransformation.castToType(object, type); } public static Tuple createTuple(Object[] array) { return new Tuple(array); } public static List createList(Object[] values) { return InvokerHelper.createList(values); } public static Wrapper createPojoWrapper(Object val, Class clazz) { return new PojoWrapper(val, clazz); } public static Wrapper createGroovyObjectWrapper(GroovyObject val, Class clazz) { return new GroovyObjectWrapper(val, clazz); } public static Map createMap(Object[] values) { return InvokerHelper.createMap(values); } //TODO: refactor public static List createRange(Object from, Object to, boolean inclusive) throws Throwable { if (from instanceof Integer && to instanceof Integer) { int ito = (Integer) to; int ifrom = (Integer) from; if (!inclusive) { if (ifrom == ito) { return new EmptyRange((Comparable) from); } if (ifrom > ito) { ito++; } else { ito--; } } return new IntRange(ifrom, ito); } if (!inclusive) { if (compareEqual(from, to)) { return new EmptyRange((Comparable) from); } if (compareGreaterThan(from, to)) { to = invokeMethod0(ScriptBytecodeAdapter.class, to, "next"); } else { to = invokeMethod0(ScriptBytecodeAdapter.class, to, "previous"); } } if (from instanceof Integer && to instanceof Integer) return new IntRange(DefaultTypeTransformation.intUnbox(from), DefaultTypeTransformation.intUnbox(to)); else return new ObjectRange((Comparable) from, (Comparable) to); } //assert public static void assertFailed(Object expression, Object message) { InvokerHelper.assertFailed(expression, message); } //isCase //TODO: set sender class public static boolean isCase(Object switchValue, Object caseExpression) throws Throwable { if (caseExpression == null) { return switchValue == null; } return DefaultTypeTransformation.castToBoolean(invokeMethodN(caseExpression.getClass(), caseExpression, "isCase", new Object[]{switchValue})); } //compare public static boolean compareIdentical(Object left, Object right) { return left == right; } public static boolean compareNotIdentical(Object left, Object right) { return left != right; } public static boolean compareEqual(Object left, Object right) { return DefaultTypeTransformation.compareEqual(left, right); } public static boolean compareNotEqual(Object left, Object right) { return !compareEqual(left, right); } public static Integer compareTo(Object left, Object right) { int answer = DefaultTypeTransformation.compareTo(left, right); if (answer == 0) { return ZERO; } else { return answer > 0 ? ONE : MINUS_ONE; } } public static boolean compareLessThan(Object left, Object right) { return compareTo(left, right).intValue() < 0; } public static boolean compareLessThanEqual(Object left, Object right) { return compareTo(left, right).intValue() <= 0; } public static boolean compareGreaterThan(Object left, Object right) { return compareTo(left, right).intValue() > 0; } public static boolean compareGreaterThanEqual(Object left, Object right) { return compareTo(left, right).intValue() >= 0; } //regexpr public static Pattern regexPattern(Object regex) { return DefaultGroovyMethods.bitwiseNegate(regex.toString()); } public static Matcher findRegex(Object left, Object right) throws Throwable { return InvokerHelper.findRegex(left, right); } public static boolean matchRegex(Object left, Object right) { return InvokerHelper.matchRegex(left, right); } //spread expressions public static Object[] despreadList(Object[] args, Object[] spreads, int[] positions) { List ret = new ArrayList(); int argsPos = 0; int spreadPos = 0; for (int pos = 0; pos < positions.length; pos++) { for (; argsPos < positions[pos]; argsPos++) { ret.add(args[argsPos]); } Object value = spreads[spreadPos]; if (value == null) { ret.add(null); } else if (value instanceof List) { ret.addAll((List) value); } else if (value.getClass().isArray()) { ret.addAll(DefaultTypeTransformation.primitiveArrayToList(value)); } else { throw new IllegalArgumentException("cannot spread the type " + value.getClass().getName() + " with value " + value); } spreadPos++; } for (; argsPos < args.length; argsPos++) { ret.add(args[argsPos]); } return ret.toArray(); } public static Object spreadMap(Object value) { return InvokerHelper.spreadMap(value); } public static Object unaryMinus(Object value) throws Throwable { return InvokerHelper.unaryMinus(value); } public static Object unaryPlus(Object value) throws Throwable { try { return InvokerHelper.unaryPlus(value); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static Object bitwiseNegate(Object value) throws Throwable { try { return InvokerHelper.bitwiseNegate(value); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } } public static MetaClass initMetaClass(Object object) { return InvokerHelper.getMetaClass(object.getClass()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/FlushingStreamWriter.java0000644001501200150120000000252011627206700026471 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.io.IOException; /** * Stream writer which flushes after each write operation. * * @author Guillaume Laforge */ public class FlushingStreamWriter extends OutputStreamWriter { public FlushingStreamWriter(OutputStream out) { super(out); } public void write(char[] cbuf, int off, int len) throws IOException { super.write(cbuf, off, len); flush(); } public void write(int c) throws IOException { super.write(c); flush(); } public void write(String str, int off, int len) throws IOException { super.write(str, off, len); flush(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/TimeCategory.java0000644001501200150120000001255511715031256024746 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.time.BaseDuration; import groovy.time.DatumDependentDuration; import groovy.time.Duration; import groovy.time.TimeDuration; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * This class has been moved to a public (i.e. non org.codehaus.* package). * @deprecated in favor of {@link groovy.time.TimeCategory} */ public class TimeCategory { /* * Methods to allow Date Duration arithmetic */ public static Date plus(final Date date, final BaseDuration duration) { return duration.plus(date); } public static Date minus(final Date date, final BaseDuration duration) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, -duration.getYears()); cal.add(Calendar.MONTH, -duration.getMonths()); cal.add(Calendar.DAY_OF_YEAR, -duration.getDays()); cal.add(Calendar.HOUR_OF_DAY, -duration.getHours()); cal.add(Calendar.MINUTE, -duration.getMinutes()); cal.add(Calendar.SECOND, -duration.getSeconds()); cal.add(Calendar.MILLISECOND, -duration.getMillis()); return cal.getTime(); } public static TimeZone getTimeZone(Date self) { Calendar calendar = Calendar.getInstance(); calendar.setTime(self); return calendar.getTimeZone(); } public static Duration getDaylightSavingsOffset(Date self) { TimeZone timeZone = getTimeZone(self); int millis = (timeZone.useDaylightTime() && timeZone.inDaylightTime(self)) ? timeZone.getDSTSavings() : 0; return new TimeDuration(0, 0, 0, millis); } public static Duration getDaylightSavingsOffset(BaseDuration self) { return getDaylightSavingsOffset(new Date(self.toMilliseconds() + 1)); } public static Duration getRelativeDaylightSavingsOffset(Date self, Date other) { Duration d1 = getDaylightSavingsOffset(self); Duration d2 = getDaylightSavingsOffset(other); return new TimeDuration(0, 0, 0, (int) (d2.toMilliseconds() - d1.toMilliseconds())); } public static TimeDuration minus(final Date lhs, final Date rhs) { long milliseconds = lhs.getTime() - rhs.getTime(); long days = milliseconds / (24 * 60 * 60 * 1000); milliseconds -= days * 24 * 60 * 60 * 1000; int hours = (int) (milliseconds / (60 * 60 * 1000)); milliseconds -= hours * 60 * 60 * 1000; int minutes = (int) (milliseconds / (60 * 1000)); milliseconds -= minutes * 60 * 1000; int seconds = (int) (milliseconds / 1000); milliseconds -= seconds * 1000; return new TimeDuration((int) days, hours, minutes, seconds, (int) milliseconds); } /* * Methods on Integer to implement 1.month, 4.years etc. */ public static DatumDependentDuration getMonths(final Integer self) { return new DatumDependentDuration(0, self.intValue(), 0, 0, 0, 0, 0); } public static DatumDependentDuration getMonth(final Integer self) { return getMonths(self); } public static DatumDependentDuration getYears(final Integer self) { return new DatumDependentDuration(self.intValue(), 0, 0, 0, 0, 0, 0); } public static DatumDependentDuration getYear(final Integer self) { return getYears(self); } /* * Methods on Integer to implement 1.week, 4.days etc. */ public static Duration getWeeks(final Integer self) { return new Duration(self.intValue() * 7, 0, 0, 0, 0); } public static Duration getWeek(final Integer self) { return getWeeks(self); } public static Duration getDays(final Integer self) { return new Duration(self.intValue(), 0, 0, 0, 0); } public static Duration getDay(final Integer self) { return getDays(self); } public static TimeDuration getHours(final Integer self) { return new TimeDuration(0, self.intValue(), 0, 0, 0); } public static TimeDuration getHour(final Integer self) { return getHours(self); } public static TimeDuration getMinutes(final Integer self) { return new TimeDuration(0, 0, self.intValue(), 0, 0); } public static TimeDuration getMinute(final Integer self) { return getMinutes(self); } public static TimeDuration getSeconds(final Integer self) { return new TimeDuration(0, 0, 0, self.intValue(), 0); } public static TimeDuration getSecond(final Integer self) { return getSeconds(self); } public static TimeDuration getMilliseconds(final Integer self) { return new TimeDuration(0, 0, 0, 0, self.intValue()); } public static TimeDuration getMillisecond(final Integer self) { return getMilliseconds(self); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/0000755001501200150120000000000011707612046024060 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/AssertionRenderer.java0000644001501200150120000001500211707612046030357 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; import java.util.*; import org.codehaus.groovy.runtime.DefaultGroovyMethods; /** * Creates a string representation of an assertion and its recorded values. * * @author Peter Niederwieser */ public final class AssertionRenderer { private final String text; private final ValueRecorder recorder; private final List lines = new ArrayList(); // startColumns.get(i) is the first non-empty column of lines.get(i) private final List startColumns = new ArrayList(); private AssertionRenderer(String text, ValueRecorder recorder) { if (text.contains("\n")) throw new IllegalArgumentException("source text may not contain line breaks"); this.text = text; this.recorder = recorder; } /** * Creates a string representation of an assertion and its recorded values. * * @param text the assertion's source text * @param recorder a recorder holding the values recorded during evaluation * of the assertion * @return a string representation of the assertion and its recorded values */ public static String render(String text, ValueRecorder recorder) { return new AssertionRenderer(text, recorder).render(); } private String render() { renderText(); sortValues(); renderValues(); return linesToString(); } private void renderText() { lines.add(new StringBuilder(text)); startColumns.add(0); lines.add(new StringBuilder()); // empty line startColumns.add(0); } private void sortValues() { // it's important to use a stable sort here, otherwise // renderValues() will skip the wrong values Collections.sort(recorder.getValues(), new Comparator() { public int compare(Value v1, Value v2) { return v2.getColumn() - v1.getColumn(); } } ); } private void renderValues() { List values = recorder.getValues(); nextValue: for (int i = 0; i < values.size(); i++) { Value value = values.get(i); int startColumn = value.getColumn(); if (startColumn < 1) continue; // skip values with unknown source position // if multiple values are associated with the same column, only // render the value which was recorded last (i.e. the value // corresponding to the outermost expression) // important for GROOVY-4344 Value next = i + 1 < values.size() ? values.get(i + 1) : null; if (next != null && next.getColumn() == value.getColumn()) continue; String str = valueToString(value.getValue()); if (str == null) continue; // null signals the value shouldn't be rendered String[] strs = str.split("\r\n|\r|\n"); int endColumn = strs.length == 1 ? value.getColumn() + str.length() : // exclusive Integer.MAX_VALUE; // multi-line strings are always placed on new lines for (int j = 1; j < lines.size(); j++) if (endColumn < startColumns.get(j)) { placeString(lines.get(j), str, startColumn); startColumns.set(j, startColumn); continue nextValue; } else { placeString(lines.get(j), "|", startColumn); if (j > 1) // make sure that no values are ever placed on empty line startColumns.set(j, startColumn + 1); // + 1: no whitespace required between end of value and "|" } // value could not be placed on existing lines, so place it on new line(s) for (String s : strs) { StringBuilder newLine = new StringBuilder(); lines.add(newLine); placeString(newLine, s, startColumn); startColumns.add(startColumn); } } } private String linesToString() { StringBuilder firstLine = lines.get(0); for (int i = 1; i < lines.size(); i++) firstLine.append('\n').append(lines.get(i).toString()); return firstLine.toString(); } private static void placeString(StringBuilder line, String str, int column) { while (line.length() < column) line.append(' '); line.replace(column - 1, column - 1 + str.length(), str); } /** * Returns a string representation of the given value, or null if * the value should not be included (because it does not add any valuable * information). * * @param value a value * @return a string representation of the given value */ private static String valueToString(Object value) { String toString; try { toString = DefaultGroovyMethods.toString(value); } catch (Exception e) { return String.format("%s (toString() threw %s)", javaLangObjectToString(value), e.getClass().getName()); } if (toString == null) { return String.format("%s (toString() == null)", javaLangObjectToString(value)); } if (toString.equals("")) { if (hasStringLikeType(value)) return "\"\""; return String.format("%s (toString() == \"\")", javaLangObjectToString(value)); } return toString; } private static boolean hasStringLikeType(Object value) { Class clazz = value.getClass(); return clazz == String.class || clazz == StringBuffer.class || clazz == StringBuilder.class; } private static String javaLangObjectToString(Object value) { String hash = Integer.toHexString(System.identityHashCode(value)); return value.getClass().getName() + "@" + hash; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/SourceTextNotAvailableException.java0000644001501200150120000000257611707612046033203 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.control.SourceUnit; /** * Indicates that the source text for an assertion statement is not available. * * @author Peter Niederwieser */ public class SourceTextNotAvailableException extends RuntimeException { // only accepts AssertStatementS so that better error messages can be produced public SourceTextNotAvailableException(AssertStatement stat, SourceUnit unit, String msg) { super(String.format("%s for %s at (%d,%d)-(%d,%d) in %s", msg, stat.getBooleanExpression().getText(), stat.getLineNumber(), stat.getColumnNumber(), stat.getLastLineNumber(), stat.getLastColumnNumber(), unit.getName())); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/PowerAssertionError.java0000644001501200150120000000177611707612046030734 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; /** * Indicates that a power assertion has failed. * * @author Peter Niederwieser */ public class PowerAssertionError extends java.lang.AssertionError { public PowerAssertionError(String msg) { super(msg); } @Override public String toString() { return String.format("Assertion failed: \n\n%s\n", getMessage()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/Value.java0000644001501200150120000000221611707612046026000 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; /** * A value recorded during evaluation of an assertion, along with the column it * is associated with in the assertion's normalized source text. * * @author Peter Niederwieser */ public class Value { private final Object value; private final int column; public Value(Object value, int column) { this.value = value; this.column = column; } public Object getValue() { return value; } public int getColumn() { return column; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/ValueRecorder.java0000644001501200150120000000225711707612046027473 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; import java.util.ArrayList; import java.util.List; /** * Records values produced during evaluation of an assertion statement's truth * expression. * * @author Peter Niederwieser */ public class ValueRecorder { private final List values = new ArrayList(); public void clear() { values.clear(); } public Object record(Object value, int anchor) { values.add(new Value(value, anchor)); return value; } public List getValues() { return values; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/powerassert/SourceText.java0000644001501200150120000001130611707612046027031 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.powerassert; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.control.SourceUnit; import java.util.ArrayList; import java.util.List; /** * Provides the source text for an assertion statement and translates * coordinates in the original source text to coordinates relative to the * assertion's (normalized) source text. * * @author Peter Niederwieser */ public class SourceText { private final int firstLine; private String normalizedText; private final List lineOffsets = new ArrayList(); private final List textOffsets = new ArrayList(); /** * Constructs a SourceText by reading the given assertion's source * text from the given source unit. * * @param stat an assertion statement * @param sourceUnit the source unit containing the assertion statement * @param janitor a Janitor for cleaning up reader sources */ public SourceText(AssertStatement stat, SourceUnit sourceUnit, Janitor janitor) { if (!hasPlausibleSourcePosition(stat)) throw new SourceTextNotAvailableException(stat, sourceUnit, "Invalid source position"); firstLine = stat.getLineNumber(); textOffsets.add(0); normalizedText = ""; for (int line = stat.getLineNumber(); line <= stat.getLastLineNumber(); line++) { String lineText = sourceUnit.getSample(line, 0, janitor); if (lineText == null) throw new SourceTextNotAvailableException(stat, sourceUnit, "SourceUnit.getSample() returned null"); if (line == stat.getLastLineNumber()) lineText = lineText.substring(0, stat.getLastColumnNumber() - 1); if (line == stat.getLineNumber()) { lineText = lineText.substring(stat.getColumnNumber() - 1); lineOffsets.add(stat.getColumnNumber() - 1); } else lineOffsets.add(countLeadingWhitespace(lineText)); lineText = lineText.trim(); if (line != stat.getLastLineNumber() && lineText.length() > 0) lineText += ' '; normalizedText += lineText; textOffsets.add(normalizedText.length()); } } /** * Returns the assertion's source text after removing line breaks. *

      Limitation: Line comments within the assertion's source text are not * handled. * * @return the assertion's source text after removing line breaks. */ public String getNormalizedText() { return normalizedText; } /** * Returns the column in getNormalizedText() corresponding * to the given line and column in the original source text. The * first character in the normalized text has column 1. * * @param line a line number * @param column a column number * @return the column in getNormalizedText() corresponding to the given line * and column in the original source text */ public int getNormalizedColumn(int line, int column) { int deltaLine = line - firstLine; if (deltaLine < 0 || deltaLine >= lineOffsets.size()) // wrong line information return -1; int deltaColumn = column - lineOffsets.get(deltaLine); if (deltaColumn < 0) // wrong column information return -1; return textOffsets.get(deltaLine) + deltaColumn; } private boolean hasPlausibleSourcePosition(ASTNode node) { return node.getLineNumber() > 0 && node.getColumnNumber() > 0 && node.getLastLineNumber() >= node.getLineNumber() && node.getLastColumnNumber() > (node.getLineNumber() == node.getLastLineNumber() ? node.getColumnNumber() : 0); } private int countLeadingWhitespace(String lineText) { int result = 0; while (result < lineText.length() && Character.isWhitespace(lineText.charAt(result))) result++; return result; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/NumberAwareComparator.java0000644001501200150120000000327011627206700026604 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.util.Comparator; /** * Compares two objects using Groovy's friendly comparison algorithm, i.e. * handles nulls gracefully (nul being less than everything else) and * performs numeric type coercion if required. */ public class NumberAwareComparator implements Comparator { public int compare(T o1, T o2) { try { return DefaultTypeTransformation.compareTo(o1, o2); } catch (ClassCastException cce) { /* ignore */ } catch (GroovyRuntimeException gre) { /* ignore */ } // since the object does not have a valid compareTo method // we compare using the hashcodes. null cases are handled by // DefaultTypeTransformation.compareTo int x1 = o1.hashCode(); int x2 = o2.hashCode(); if (x1 == x2) return 0; if (x1 < x2) return -1; return 1; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/MethodKey.java0000644001501200150120000000733711627206700024245 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * An abstract base class for a key used for comparators and Map keys to lookup a method by * name and parameter types * * @author James Strachan * @version $Revision$ */ public abstract class MethodKey { private int hash; private String name; private Class sender; private boolean isCallToSuper; public MethodKey(Class sender, String name, boolean isCallToSuper) { this.sender = sender; this.name = name; this.isCallToSuper = isCallToSuper; } /** * Creates an immutable copy that we can cache. */ public MethodKey createCopy() { int size = getParameterCount(); Class[] paramTypes = new Class[size]; for (int i = 0; i < size; i++) { paramTypes[i] = getParameterType(i); } return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper); } public boolean equals(Object that) { if (this == that) { return true; } else if (that instanceof MethodKey) { return equals((MethodKey) that); } return false; } public boolean equals(MethodKey that) { int size; if (sender!=that.sender) return false; if (isCallToSuper!=that.isCallToSuper) return false; if (!name.equals(that.name)) return false; if ((size = getParameterCount()) != that.getParameterCount()) return false; for (int i = 0; i < size; i++) { if (getParameterType(i) != that.getParameterType(i)) { return false; } } return true; } public int hashCode() { if (hash == 0) { hash = createHashCode(); if (hash == 0) { hash = 0xcafebabe; } } return hash; } public String toString() { return super.toString() + "[name:" + name + "; params:" + getParamterTypes(); } public String getName() { return name; } public List getParamterTypes() { int size = getParameterCount(); if (size <= 0) { return Collections.EMPTY_LIST; } List params = new ArrayList(size); for (int i = 0; i < size; i++) { params.add(getParameterType(i)); } return params; } public abstract int getParameterCount(); public abstract Class getParameterType(int index); protected int createHashCode() { int answer = name.hashCode(); int size = getParameterCount(); /** @todo we should use the real Josh Bloch algorithm here */ // can't remember the exact Josh Bloch algorithm and I've not got the book handy // but its something like this IIRC for (int i = 0; i < size; i++) { answer *= 37; answer += 1 + getParameterType(i).hashCode(); } answer *= 37; answer += isCallToSuper?1:0; answer *= 37; answer += 1 + sender.hashCode(); return answer; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/package.html0000644001501200150120000000035511627206700023763 0ustar miguelmiguel package org.codehaus.groovy.runtime.*

      Runtime classes for Groovy - whether the dynamic interpreter is being used, the compiler or the bytecode generator.

      groovy-1.8.6/src/main/org/codehaus/groovy/runtime/SwingGroovyMethods.java0000644001501200150120000010005411627206700026163 0ustar miguelmiguel/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GString; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.util.Enumeration; import java.util.Iterator; /** * This class defines all the new Swing-related groovy methods which enhance * the normal JDK Swing classes when inside the Groovy environment. * Static methods are used with the first parameter the destination class. * * @author Andres Almiray */ public class SwingGroovyMethods { /** * Provide the standard Groovy size() method for Container. * * @param self a Container * @return the component count of the container * @since 1.6.4 */ public static int size(Container self) { return self.getComponentCount(); } /** * Support the subscript operator for Container. * * @param self a Container * @param index the index of the Component to get * @return the component at the given index * @since 1.6.4 */ public static Component getAt(Container self, int index) { return self.getComponent(index); } /** * Overloads the left shift operator to provide an easy way to add * components to a Container. * * @param self a Container * @param c a Component to be added to the container. * @return same container, after the value was added to it. * @since 1.6.4 */ public static Container leftShift(Container self, Component c) { self.add(c); return self; } /** * Returns an {@link java.util.Iterator} which traverses the Container one Component at a time. * * @param self a Container * @return an Iterator for a Container * @since 1.6.4 */ public static Iterator iterator(Container self) { return DefaultGroovyMethods.iterator(self.getComponents()); } /** * Removes all components from the Container. * * @param self a Container * @since 1.6.4 */ public static void clear(Container self) { self.removeAll(); } /** * Provide the standard Groovy size() method for ButtonGroup. * * @param self a ButtonGroup * @return the button count of the buttonGroup * @since 1.6.4 */ public static int size(ButtonGroup self) { return self.getButtonCount(); } /** * Support the subscript operator for ButtonGroup. * * @param self a ButtonGroup * @param index the index of the AbstractButton to get * @return the button at the given index * @since 1.6.4 */ public static AbstractButton getAt(ButtonGroup self, int index) { int size = self.getButtonCount(); if (index < 0 || index >= size) return null; Enumeration buttons = self.getElements(); for (int i = 0; i <= index; i++) { AbstractButton b = (AbstractButton) buttons.nextElement(); if (i == index) return b; } return null; } /** * Overloads the left shift operator to provide an easy way to add * buttons to a ButtonGroup. * * @param self a ButtonGroup * @param b an AbstractButton to be added to the buttonGroup. * @return same buttonGroup, after the value was added to it. * @since 1.6.4 */ public static ButtonGroup leftShift(ButtonGroup self, AbstractButton b) { self.add(b); return self; } /** * Returns an {@link java.util.Iterator} which traverses the ButtonGroup one AbstractButton at a time. * * @param self a ButtonGroup * @return an Iterator for a ButtonGroup * @since 1.6.4 */ public static Iterator iterator(ButtonGroup self) { return DefaultGroovyMethods.iterator(self.getElements()); } /** * Provide the standard Groovy size() method for ListModel. * * @param self a ListModel * @return the size of the ListModel * @since 1.6.4 */ public static int size(ListModel self) { return self.getSize(); } /** * Support the subscript operator for ListModel. * * @param self a ListModel * @param index the index of the element to get * @return the element at the given index * @since 1.6.4 */ public static Object getAt(ListModel self, int index) { return self.getElementAt(index); } /** * Returns an {@link java.util.Iterator} which traverses the ListModel one element at a time. * * @param self a ListModel * @return an Iterator for a ListModel * @since 1.6.4 */ public static Iterator iterator(final ListModel self) { return new Iterator() { private int index = 0; public boolean hasNext() { return index < self.getSize(); } public Object next() { return self.getElementAt(index++); } public void remove() { throw new UnsupportedOperationException("LisModel is immutable."); } }; } /** * Overloads the left shift operator to provide an easy way to add * elements to a DefaultListModel. * * @param self a DefaultListModel * @param e an element to be added to the listModel. * @return same listModel, after the value was added to it. * @since 1.6.4 */ public static DefaultListModel leftShift(DefaultListModel self, Object e) { self.addElement(e); return self; } /** * Allow DefaultListModel to work with subscript operators.

      * WARNING: this operation does not replace the element at the * specified index, rather it inserts the element at that index, thus * increasing the size of of the model by 1. * * @param self a DefaultListModel * @param index an index * @param e the element to insert at the given index * @since 1.6.4 */ public static void putAt(DefaultListModel self, int index, Object e) { self.set(index, e); } /** * Removes all elements from the DefaultListModel. * * @param self a DefaultListModel * @since 1.6.4 */ public static void clear(DefaultListModel self) { self.removeAllElements(); } /** * Returns an {@link java.util.Iterator} which traverses the DefaultListModel one element at a time. * * @param self a DefaultListModel * @return an Iterator for a DefaultListModel * @since 1.6.4 */ public static Iterator iterator(final DefaultListModel self) { return new Iterator() { private int index = 0; public boolean hasNext() { return index > -1 && index < self.getSize(); } public Object next() { return self.getElementAt(index++); } public void remove() { if (hasNext()) self.removeElementAt(index--); } }; } /** * Provide the standard Groovy size() method for JComboBox. * * @param self a JComboBox * @return the intem count of the comboBox * @since 1.6.4 */ public static int size(JComboBox self) { return self.getItemCount(); } /** * Support the subscript operator for JComboBox. * * @param self a JComboBox * @param index the index of the item to get * @return the tem at the given index * @since 1.6.4 */ public static Object getAt(JComboBox self, int index) { return self.getItemAt(index); } /** * Overloads the left shift operator to provide an easy way to add * items to a JComboBox. * * @param self a JComboBox * @param i an item to be added to the comboBox. * @return same comboBox, after the value was added to it. * @since 1.6.4 */ public static JComboBox leftShift(JComboBox self, Object i) { self.addItem(i); return self; } /** * Removes all items from the JComboBox. * * @param self a JComboBox * @since 1.6.4 */ public static void clear(JComboBox self) { self.removeAllItems(); } /** * Returns an {@link java.util.Iterator} which traverses the ComboBox one item at a time. * * @param self a ComboBox * @return an Iterator for a ComboBox * @since 1.6.4 */ public static Iterator iterator(JComboBox self) { return iterator(self.getModel()); } /** * Overloads the left shift operator to provide an easy way to add * items to a MutableComboBoxModel. * * @param self a MutableComboBoxModel * @param i an item to be added to the model. * @return same model, after the value was added to it. * @since 1.6.4 */ public static MutableComboBoxModel leftShift(MutableComboBoxModel self, Object i) { self.addElement(i); return self; } /** * Allow MutableComboBoxModel to work with subscript operators.

      * WARNING: this operation does not replace the item at the * specified index, rather it inserts the item at that index, thus * increasing the size of the model by 1. * * @param self a MutableComboBoxModel * @param index an index * @param i the item to insert at the given index * @since 1.6.4 */ public static void putAt(MutableComboBoxModel self, int index, Object i) { self.insertElementAt(i, index); } /** * Returns an {@link java.util.Iterator} which traverses the MutableComboBoxModel one item at a time. * * @param self a MutableComboBoxModel * @return an Iterator for a MutableComboBoxModel * @since 1.6.4 */ public static Iterator iterator(final MutableComboBoxModel self) { return new Iterator() { private int index = 0; public boolean hasNext() { return index > -1 && index < self.getSize(); } public Object next() { return self.getElementAt(index++); } public void remove() { if (hasNext()) self.removeElementAt(index--); } }; } /** * Removes all items from the model. * * @param self a DefaultComboBoxModel * @since 1.7.3 */ public static void clear(DefaultComboBoxModel self) { self.removeAllElements(); } /** * Provide the standard Groovy size() method for TableModel. * * @param self a TableModel * @return the row count of the TableModel * @since 1.6.4 */ public static int size(TableModel self) { return self.getRowCount(); } /** * Support the subscript operator for TableModel. * * @param self a TableModel * @param index the index of the row to get * @return the row at the given index * @since 1.6.4 */ public static Object[] getAt(TableModel self, int index) { int cols = self.getColumnCount(); Object[] rowData = new Object[cols]; for (int col = 0; col < cols; col++) { rowData[col] = self.getValueAt(index, col); } return rowData; } /** * Returns an {@link java.util.Iterator} which traverses the TableModel one row at a time. * * @param self a TableModel * @return an Iterator for a TableModel * @since 1.6.4 */ public static Iterator iterator(final TableModel self) { return new Iterator() { private int row = 0; public boolean hasNext() { return row < self.getRowCount(); } public Object next() { int cols = self.getColumnCount(); Object[] rowData = new Object[cols]; for (int col = 0; col < cols; col++) { rowData[col] = self.getValueAt(row, col); } row++; return rowData; } public void remove() { throw new UnsupportedOperationException("TableModel is immutable."); } }; } /** * Overloads the left shift operator to provide an easy way to add * rows to a DefaultTableModel.

      *

      * if row.size < model.size -> row will be padded with nulls
      * if row.size > model.size -> additional columns will be discarded
      * * @param self a DefaultTableModel * @param row a row to be added to the model. * @return same model, after the value was added to it. * @since 1.6.4 */ public static DefaultTableModel leftShift(DefaultTableModel self, Object row) { if (row == null) { // adds an empty row self.addRow((Object[]) null); return self; } self.addRow(buildRowData(self, row)); return self; } /** * Allow DefaultTableModel to work with subscript operators.

      * WARNING: this operation does not replace the item at the * specified index, rather it inserts the item at that index, thus * increasing the size of the model by 1.

      *

      * if row.size < model.size -> row will be padded with nulls
      * if row.size > model.size -> additional columns will be discarded
      * * @param self a DefaultTableModel * @param index an index * @param row the row to insert at the given index * @since 1.6.4 */ public static void putAt(DefaultTableModel self, int index, Object row) { if (row == null) { // adds an empty row self.insertRow(index, (Object[]) null); return; } self.insertRow(index, buildRowData(self, row)); } private static Object[] buildRowData(DefaultTableModel delegate, Object row) { int cols = delegate.getColumnCount(); Object[] rowData = new Object[cols]; int i = 0; for (Iterator it = DefaultGroovyMethods.iterator(row); it.hasNext() && i < cols;) { rowData[i++] = it.next(); } return rowData; } /** * Returns an {@link java.util.Iterator} which traverses the DefaultTableModel one item at a time. * * @param self a DefaultTableModel * @return an Iterator for a DefaultTableModel * @since 1.6.4 */ public static Iterator iterator(final DefaultTableModel self) { return new Iterator() { private int row = 0; public boolean hasNext() { return row > -1 && row < self.getRowCount(); } public Object next() { int cols = self.getColumnCount(); Object[] rowData = new Object[cols]; for (int col = 0; col < cols; col++) { rowData[col] = self.getValueAt(row, col); } row++; return rowData; } public void remove() { if (hasNext()) self.removeRow(row--); } }; } /** * Provide the standard Groovy size() method for TableColumnModel. * * @param self a TableColumnModel * @return the column count of the TableColumnModel * @since 1.6.4 */ public static int size(TableColumnModel self) { return self.getColumnCount(); } /** * Support the subscript operator for TableColumnModel. * * @param self a TableColumnModel * @param index the index of the column to get * @return the column at the given index * @since 1.6.4 */ public static TableColumn getAt(TableColumnModel self, int index) { return self.getColumn(index); } /** * Returns an {@link java.util.Iterator} which traverses the TableColumnModel one TableColumn at a time. * * @param self a TableColumnModel * @return an Iterator for a TableColumnModel * @since 1.6.4 */ public static Iterator iterator(final TableColumnModel self) { return new Iterator() { private int index = 0; public boolean hasNext() { return index > -1 && index < self.getColumnCount(); } public TableColumn next() { return self.getColumn(index++); } public void remove() { if (hasNext()) self.removeColumn(self.getColumn(index--)); } }; } /** * Overloads the left shift operator to provide an easy way to add * columns to a TableColumnModel. * * @param self a TableColumnModel * @param column a TableColumn to be added to the model. * @return same model, after the value was added to it. * @since 1.6.4 */ public static TableColumnModel leftShift(TableColumnModel self, TableColumn column) { self.addColumn(column); return self; } /** * Provide the standard Groovy size() method for TreePath. * * @param self a TreePath * @return the path count of the treePath * @since 1.6.4 */ public static int size(TreePath self) { return self.getPathCount(); } /** * Support the subscript operator for TreePath. * * @param self a TreePath * @param index the index of the path to get * @return the path at the given index * @since 1.6.4 */ public static Object getAt(TreePath self, int index) { return self.getPath()[index]; } /** * Overloads the left shift operator to provide an easy way to add * paths to a treePath.

      * WARNING: this operation returns a new TreePath, not the original one.

      * * @param self a TreePath * @param p an object to be added to the treePath. * @return same treePath, after the value was added to it. * @since 1.6.4 */ public static TreePath leftShift(TreePath self, Object p) { return self.pathByAddingChild(p); } /** * Returns an {@link java.util.Iterator} which traverses the TreePath one path at a time. * * @param self a TreePath * @return an Iterator for a TreePath * @since 1.6.4 */ public static Iterator iterator(TreePath self) { return DefaultGroovyMethods.iterator(self.getPath()); } /** * Provide the standard Groovy size() method for TreeNode. * * @param self a TreeNode * @return the child count of the treeNode * @since 1.6.4 */ public static int size(TreeNode self) { return self.getChildCount(); } /** * Support the subscript operator for TreeNode. * * @param self a TreeNode * @param index the index of the child node to get * @return the child node at the given index * @since 1.6.4 */ public static TreeNode getAt(TreeNode self, int index) { return self.getChildAt(index); } /** * Returns an {@link java.util.Iterator} which traverses the TreeNode one node at a time. * * @param self a TreeNode * @return an Iterator for a TreeNode * @since 1.6.4 */ @SuppressWarnings("unchecked") public static Iterator iterator(TreeNode self) { return DefaultGroovyMethods.iterator(self.children()); } /** * Overloads the left shift operator to provide an easy way to add * nodes to a MutableTreeNode.

      * * @param self a MutableTreeNode * @param node a node to be added to the treeNode. * @return same treeNode, after the value was added to it. * @since 1.6.4 */ public static MutableTreeNode leftShift(MutableTreeNode self, MutableTreeNode node) { self.insert(node, self.getChildCount()); return self; } /** * Allow MutableTreeNode to work with subscript operators.

      * WARNING: this operation does not replace the node at the * specified index, rather it inserts the node at that index, thus * increasing the size of the treeNode by 1.

      * * @param self a MutableTreeNode * @param index an index * @param node the node to insert at the given index * @since 1.6.4 */ public static void putAt(MutableTreeNode self, int index, MutableTreeNode node) { self.insert(node, index); } /** * Overloads the left shift operator to provide an easy way to add * nodes to a DefaultMutableTreeNode.

      * * @param self a DefaultMutableTreeNode * @param node a node to be added to the treeNode. * @return same treeNode, after the value was added to it. * @since 1.6.4 */ public static DefaultMutableTreeNode leftShift(DefaultMutableTreeNode self, DefaultMutableTreeNode node) { self.add(node); return self; } /** * Removes all children nodes from the DefaultMutableTreeNode. * * @param self a DefaultMutableTreeNode * @since 1.6.4 */ public static void clear(DefaultMutableTreeNode self) { self.removeAllChildren(); } /** * Provide the standard Groovy size() method for JMenu. * * @param self a JMenu * @return the menu component count of the menu * @since 1.6.4 */ public static int size(JMenu self) { return self.getMenuComponentCount(); } /** * Support the subscript operator for JMenu. * * @param self a JMenu * @param index the index of the menu component to get * @return the menu component at the given index * @since 1.6.4 */ public static Component getAt(JMenu self, int index) { return self.getMenuComponent(index); } /** * Overloads the left shift operator to provide an easy way to add * components to a menu.

      * * @param self a JMenu * @param action an action to be added to the menu. * @return same menu, after the value was added to it. * @since 1.6.4 */ public static JMenu leftShift(JMenu self, Action action) { self.add(action); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a menu.

      * * @param self a JMenu * @param component a component to be added to the menu. * @return same menu, after the value was added to it. * @since 1.6.4 */ public static JMenu leftShift(JMenu self, Component component) { self.add(component); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a menu.

      * * @param self a JMenu * @param item an item to be added to the menu. * @return same menu, after the value was added to it. * @since 1.6.4 */ public static JMenu leftShift(JMenu self, JMenuItem item) { self.add(item); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a menu.

      * * @param self a JMenu * @param str a String to be added to the menu. * @return same menu, after the value was added to it. * @since 1.6.4 */ public static JMenu leftShift(JMenu self, String str) { self.add(str); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a menu.

      * * @param self a JMenu * @param gstr a GString to be added to the menu. * @return same menu, after the value was added to it. * @since 1.6.4 */ public static JMenu leftShift(JMenu self, GString gstr) { self.add(gstr.toString()); return self; } /** * Returns an {@link java.util.Iterator} which traverses the JMenu one component at a time. * * @param self a JMenu * @return an Iterator for a JMenu * @since 1.6.4 */ public static Iterator/**/ iterator(JMenu self) { return DefaultGroovyMethods.iterator(self.getMenuComponents()); } /** * Provide the standard Groovy size() method for JMenuBar. * * @param self a JMenuBar * @return the menu count of the menuBar * @since 1.6.4 */ public static int size(JMenuBar self) { return self.getMenuCount(); } /** * Support the subscript operator for JMenuBar. * * @param self a JMenuBar * @param index the index of the menu to get * @return the menu at the given index * @since 1.6.4 */ public static JMenu getAt(JMenuBar self, int index) { return self.getMenu(index); } /** * Overloads the left shift operator to provide an easy way to add * menus to a menuBar.

      * * @param self a JMenuBar * @param menu a menu to be added to the menuBar. * @return same menuBar, after the value was added to it. * @since 1.6.4 */ public static JMenuBar leftShift(JMenuBar self, JMenu menu) { self.add(menu); return self; } /** * Returns an {@link java.util.Iterator} which traverses the JMenuBar one menu at a time. * * @param self a JMenuBar * @return an Iterator for a JMenuBar * @since 1.6.4 */ public static Iterator/**/ iterator(JMenuBar self) { return DefaultGroovyMethods.iterator(self.getSubElements()); } /** * Overloads the left shift operator to provide an easy way to add * components to a popupMenu.

      * * @param self a JPopupMenu * @param action an action to be added to the popupMenu. * @return same popupMenu, after the value was added to it. * @since 1.6.4 */ public static JPopupMenu leftShift(JPopupMenu self, Action action) { self.add(action); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a popupMenu.

      * * @param self a JPopupMenu * @param component a component to be added to the popupMenu. * @return same popupMenu, after the value was added to it. * @since 1.6.4 */ public static JPopupMenu leftShift(JPopupMenu self, Component component) { self.add(component); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a popupMenu.

      * * @param self a JPopupMenu * @param item an item to be added to the popupMenu. * @return same popupMenu, after the value was added to it. * @since 1.6.4 */ public static JPopupMenu leftShift(JPopupMenu self, JMenuItem item) { self.add(item); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a popupMenu.

      * * @param self a JPopupMenu * @param str a String to be added to the popupMenu. * @return same popupMenu, after the value was added to it. * @since 1.6.4 */ public static JPopupMenu leftShift(JPopupMenu self, String str) { self.add(str); return self; } /** * Overloads the left shift operator to provide an easy way to add * components to a popupMenu.

      * * @param self a JPopupMenu * @param gstr a GString to be added to the popupMenu. * @return same popupMenu, after the value was added to it. * @since 1.6.4 */ public static JPopupMenu leftShift(JPopupMenu self, GString gstr) { self.add(gstr.toString()); return self; } /** * Returns an {@link java.util.Iterator} which traverses the JPopupMenu one MenuElement at a time. * * @param self a JPopupMenu * @return an Iterator for a JPopupMenu * @since 1.6.4 */ public static Iterator iterator(JPopupMenu self) { return DefaultGroovyMethods.iterator(self.getSubElements()); } /** * Provide the standard Groovy size() method for JTabbedPane. * * @param self a JTabbedPane * @return the tab count of the tabbedPane * @since 1.6.4 */ public static int size(JTabbedPane self) { return self.getTabCount(); } /** * Removes all elements from the JTabbedPane. * * @param self a JTabbedPane * @since 1.6.4 */ public static void clear(JTabbedPane self) { self.removeAll(); } /** * Support the subscript operator for JTabbedPane. * * @param self a JTabbedPane * @param index the index of the tab component to get * @return the component at the given index * @since 1.6.4 */ public static Component getAt(JTabbedPane self, int index) { return self.getComponentAt(index); } /** * Returns an {@link java.util.Iterator} which traverses the JTabbedPane one Component tab at a time. * * @param self a JTabbedPane * @return an Iterator for a JTabbedPane * @since 1.6.4 */ public static Iterator iterator(final JTabbedPane self) { return new Iterator() { private int index = 0; public boolean hasNext() { return index > -1 && index < self.getTabCount(); } public Component next() { return self.getComponentAt(index++); } public void remove() { if (hasNext()) self.removeTabAt(index--); } }; } /** * Overloads the left shift operator to provide an easy way to add * components to a toolBar.

      * * @param self a JToolBar * @param action an Action to be added to the toolBar. * @return same toolBar, after the value was added to it. * @since 1.6.4 */ public static JToolBar leftShift(JToolBar self, Action action) { self.add(action); return self; } /** * Support the subscript operator for JToolBar. * * @param self a JToolBar * @param index the index of the tab component to get * @return the tab component at the given index * @since 1.6.4 */ public static Component getAt(JToolBar self, int index) { return self.getComponentAtIndex(index); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/GStringImpl.java0000644001501200150120000000375511627206700024553 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GString; /** * Default implementation of a GString used by the compiler. A GString * consist of a list of values and strings which can be combined to * create a new String. * * @author Jochen Theodorou * @see groovy.lang.GString */ public class GStringImpl extends GString { private String[] strings; /** * Create a new GString with values and strings. *

      * Each value is prefixed by a string, after the last value * an additional String might be used. This means * strings.length == values.length || strings.length == values.length + 1. *

      * NOTE: The lengths are not checked. Using different lengths might result * in unpredictable behaviour. *

      * * @param values the value parts * @param strings the string parts */ public GStringImpl(Object[] values, String[] strings) { super(values); this.strings = strings; } /** * Get the strings of this GString. *

      * This methods returns the same array as used in the constructor. Changing * the values will result in changes of the GString. It is not recommended * to do so. *

      */ public String[] getStrings() { return strings; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ConversionHandler.java0000644001501200150120000001327411707612046025777 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GroovyRuntimeException; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * This class is a general adapter to map a call to a Java interface * to a given delegate. *

      * * @author Ben Yu * @author Jochen Theodorou */ public abstract class ConversionHandler implements InvocationHandler, Serializable { private Object delegate; private static final long serialVersionUID = 1162833717190835227L; /** * Creates a ConversionHandler with an delegate. * * @param delegate the delegate * @throws IllegalArgumentException if the given delegate is null */ public ConversionHandler(Object delegate) { if (delegate == null) throw new IllegalArgumentException("delegate must not be null"); this.delegate = delegate; } /** * Returns the delegate. * * @return the delegate */ public Object getDelegate() { return delegate; } /** * This method is a default implementation for the invoke method given in * InvocationHandler. Any call to a method with a declaring class that is * not Object, excluding toString(), is redirected to invokeCustom. * Methods like equals and hashcode are called on the class itself instead * of the delegate because they are considered fundamental methods that should * not be overwritten. The toString() method gets special treatment as it is * deemed to be a method that you might wish to override when called from Groovy. *

      * In many scenarios, it is better to overwrite the invokeCustom method where * the core Object related methods are filtered out. * * @param proxy the proxy * @param method the method * @param args the arguments * @return the result of the invocation by method or delegate * @throws Throwable if caused by the delegate or the method * @see #invokeCustom(Object, Method, Object[]) * @see InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!checkMethod(method)) { try { return invokeCustom(proxy, method, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } try { return method.invoke(this, args); } catch (InvocationTargetException ite) { throw ite.getTargetException(); } } protected boolean checkMethod(Method method) { return isCoreObjectMethod(method); } /** * This method is called for all Methods not defined on Object. * The delegate should be called here. * * @param proxy the proxy * @param method the method * @param args the arguments * @return the result of the invocation of the delegate * @throws Throwable any exception causes by the delegate * @see #invoke(Object, Method, Object[]) * @see InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) */ public abstract Object invokeCustom(Object proxy, Method method, Object[] args) throws Throwable; /** * Indicates whether some other object is "equal to" this one. * The delegate is used if the class of the parameter and the * current class are equal. In other cases the method will return * false. The exact class is here used, if inheritance is needed, * this method must be overwritten. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof Proxy) { obj = Proxy.getInvocationHandler(obj); } if (obj instanceof ConversionHandler) { return (((ConversionHandler) obj).getDelegate()).equals(delegate); } else { return false; } } /** * Returns a hash code value for the delegate. * * @see java.lang.Object#hashCode() */ public int hashCode() { return delegate.hashCode(); } /** * Returns a String version of the delegate. * * @see java.lang.Object#toString() */ public String toString() { return delegate.toString(); } /** * Checks whether a method is a core method from java.lang.Object. * Such methods often receive special treatment because they are * deemed fundamental enough to not be tampered with. * * @param method the method to check * @return true if the method is deemed to be a core method */ public static boolean isCoreObjectMethod(Method method) { return Object.class.equals(method.getDeclaringClass()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DateGroovyMethods.java0000644001501200150120000005147111715031256025761 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; /** * This class defines new groovy methods which appear on normal JDK * Date and Calendar classes inside the Groovy environment. */ public class DateGroovyMethods { /** * Support the subscript operator for a Date. * * @param self a Date * @param field a Calendar field, e.g. MONTH * @return the value for the given field, e.g. FEBRUARY * @see java.util.Calendar * @since 1.5.5 */ public static int getAt(Date self, int field) { Calendar cal = Calendar.getInstance(); cal.setTime(self); return cal.get(field); } /** * Convert a Date to a Calendar. * * @param self a Date * @return a Calendar corresponding to the given Date * @since 1.7.6 */ public static Calendar toCalendar(Date self) { Calendar cal = Calendar.getInstance(); cal.setTime(self); return cal; } /** * Support the subscript operator for a Calendar. * * @param self a Calendar * @param field a Calendar field, e.g. MONTH * @return the value for the given field, e.g. FEBRUARY * @see java.util.Calendar * @since 1.7.3 */ public static int getAt(Calendar self, int field) { return self.get(field); } /** * Support the subscript operator for mutating a Calendar. * Example usage: *

           * import static java.util.Calendar.*
           * def cal = Calendar.instance
           * cal[DAY_OF_WEEK] = MONDAY
           * cal[MONTH] = MARCH
           * println cal.time // A Monday in March
           * 
      * * @param self A Calendar * @param field A Calendar field, e.g. MONTH * @param value The value for the given field, e.g. FEBRUARY * @see java.util.Calendar#set(int, int) * @since 1.7.3 */ public static void putAt(Calendar self, int field, int value) { self.set(field, value); } /** * Support the subscript operator for mutating a Date. * * @param self A Date * @param field A Calendar field, e.g. MONTH * @param value The value for the given field, e.g. FEBRUARY * @see #putAt(java.util.Calendar, int, int) * @see java.util.Calendar#set(int, int) * @since 1.7.3 */ public static void putAt(Date self, int field, int value) { Calendar cal = Calendar.getInstance(); cal.setTime(self); putAt(cal, field, value); self.setTime(cal.getTimeInMillis()); } /** * Support mutating a Calendar with a Map. *

      * The map values are the normal values provided as the * second parameter to java.util.Calendar#set(int, int). * The keys can either be the normal fields values provided as * the first parameter to that method or one of the following Strings: * * * * * * * *
      yearCalendar.YEAR
      monthCalendar.MONTH
      dateCalendar.DATE
      hourOfDayCalendar.HOUR_OF_DAY
      minuteCalendar.MINUTE
      secondCalendar.SECOND
      * Example usage: *

           * import static java.util.Calendar.*
           * def cal = Calendar.instance
           * def m = [:]
           * m[YEAR] = 2010
           * m[MONTH] = DECEMBER
           * m[DATE] = 25
           * cal.set(m)
           * println cal.time // Christmas 2010
           *
           * cal.set(year:2011, month:DECEMBER, date:25)
           * println cal.time // Christmas 2010
           * 
      * * @param self A Calendar * @param updates A Map of Calendar keys and values * @see java.util.Calendar#set(int, int) * @see java.util.Calendar#set(int, int, int, int, int, int) * @since 1.7.3 */ public static void set(Calendar self, Map updates) { for (Map.Entry entry : updates.entrySet()) { Object key = entry.getKey(); if (key instanceof String) key = CAL_MAP.get(key); if (key instanceof Integer) self.set((Integer) key, entry.getValue()); } } /** * Support creating a new Date having similar properties to * an existing Date (which remains unaltered) but with * some fields updated according to a Map of changes. *

      * Example usage: *

           * import static java.util.Calendar.YEAR
           * def now = Calendar.instance
           * def nextYear = now[YEAR] + 1
           * def oneYearFromNow = now.updated(year: nextYear)
           * println now.time
           * println oneYearFromNow.time
           * 
      * * @param self A Calendar * @param updates A Map of Calendar keys and values * @return The newly created Calendar * @see java.util.Calendar#set(int, int) * @see java.util.Calendar#set(int, int, int, int, int, int) * @see #set(java.util.Calendar, java.util.Map) * @since 1.7.3 */ public static Calendar updated(Calendar self, Map updates) { Calendar result = (Calendar) self.clone(); for (Map.Entry entry : updates.entrySet()) { Object key = entry.getKey(); if (key instanceof String) key = CAL_MAP.get(key); if (key instanceof Integer) result.set((Integer) key, entry.getValue()); } return result; } /** * Support mutating a Date with a Map. *

      * Example usage: *

           * import static java.util.Calendar.YEAR
           * def date = new Date()
           * def nextYear = date[YEAR] + 1
           * date.set(year: nextYear)
           * println date
           * 
      * * @param self A Date * @param updates A Map of Calendar keys and values * @see java.util.Calendar#set(int, int) * @see #set(java.util.Calendar, java.util.Map) * @since 1.7.3 */ public static void set(Date self, Map updates) { Calendar cal = Calendar.getInstance(); cal.setTime(self); set(cal, updates); self.setTime(cal.getTimeInMillis()); } /** * Support creating a new Date having similar properties to * an existing Date (which remains unaltered) but with * some fields updated according to a Map of changes. *

      * Example usage: *

           * import static java.util.Calendar.YEAR
           * def today = new Date()
           * def nextYear = today[YEAR] + 1
           * def oneYearFromNow = today.updated(year: nextYear)
           * println today
           * println oneYearFromNow
           * 
      * * @param self A Date * @param updates A Map of Calendar keys and values * @return The newly created Date * @see java.util.Calendar#set(int, int) * @see #set(java.util.Date, java.util.Map) * @see #set(java.util.Calendar, java.util.Map) * @see #updated(java.util.Calendar, java.util.Map) * @since 1.7.3 */ public static Date updated(Date self, Map updates) { Calendar cal = Calendar.getInstance(); cal.setTime(self); set(cal, updates); return cal.getTime(); } private static final Map CAL_MAP = new HashMap(); static { CAL_MAP.put("year", Calendar.YEAR); CAL_MAP.put("month", Calendar.MONTH); CAL_MAP.put("date", Calendar.DATE); CAL_MAP.put("hourOfDay", Calendar.HOUR_OF_DAY); CAL_MAP.put("minute", Calendar.MINUTE); CAL_MAP.put("second", Calendar.SECOND); } /** * Increment a Date by one day. * * @param self a Date * @return the next days date * @since 1.0 */ public static Date next(Date self) { return plus(self, 1); } /** * Increment a java.sql.Date by one day. * * @param self a java.sql.Date * @return the next days date * @since 1.0 */ public static java.sql.Date next(java.sql.Date self) { return new java.sql.Date(next((Date) self).getTime()); } /** * Decrement a Date by one day. * * @param self a Date * @return the previous days date * @since 1.0 */ public static Date previous(Date self) { return minus(self, 1); } /** * Decrement a java.sql.Date by one day. * * @param self a java.sql.Date * @return the previous days date * @since 1.0 */ public static java.sql.Date previous(java.sql.Date self) { return new java.sql.Date(previous((Date) self).getTime()); } /** * Add a number of days to this date and returns the new date. * * @param self a Date * @param days the number of days to increase * @return the new date * @since 1.0 */ public static Date plus(Date self, int days) { Calendar calendar = (Calendar) Calendar.getInstance().clone(); calendar.setTime(self); calendar.add(Calendar.DAY_OF_YEAR, days); return calendar.getTime(); } /** * Add a number of days to this date and returns the new date. * * @param self a java.sql.Date * @param days the number of days to increase * @return the new date * @since 1.0 */ public static java.sql.Date plus(java.sql.Date self, int days) { return new java.sql.Date(plus((Date) self, days).getTime()); } /** * Add number of days to this Timestamp and returns the new Timestamp object. * * @param self a Timestamp * @param days the number of days to increase * @return the new Timestamp */ public static Timestamp plus(Timestamp self, int days) { Calendar calendar = (Calendar) Calendar.getInstance().clone(); calendar.setTime(self); calendar.add(Calendar.DAY_OF_YEAR, days); Timestamp ts = new Timestamp(calendar.getTime().getTime()); ts.setNanos(self.getNanos()); return ts; } /** * Subtract a number of days from this date and returns the new date. * * @param self a Date * @param days the number of days to subtract * @return the new date * @since 1.0 */ public static Date minus(Date self, int days) { return plus(self, -days); } /** * Subtract a number of days from this date and returns the new date. * * @param self a java.sql.Date * @param days the number of days to subtract * @return the new date * @since 1.0 */ public static java.sql.Date minus(java.sql.Date self, int days) { return new java.sql.Date(minus((Date) self, days).getTime()); } /** * Subtract a number of days from this Timestamp and returns the new Timestamp object. * * @param self a Timestamp * @param days the number of days to subtract * @return the new Timestamp */ public static Timestamp minus(Timestamp self, int days) { return plus(self, -days); } /** * Subtract another date from this one and return the number of days of the difference. *

      * Date self = Date then + (Date self - Date then) *

      * IOW, if self is before then the result is a negative value. * * @param self a Calendar * @param then another Calendar * @return number of days * @since 1.6.0 */ public static int minus(Calendar self, Calendar then) { Calendar a = self; Calendar b = then; boolean swap = a.before(b); if (swap) { Calendar t = a; a = b; b = t; } int days = 0; b = (Calendar) b.clone(); while (a.get(Calendar.YEAR) > b.get(Calendar.YEAR)) { days += 1 + (b.getActualMaximum(Calendar.DAY_OF_YEAR) - b.get(Calendar.DAY_OF_YEAR)); b.set(Calendar.DAY_OF_YEAR, 1); b.add(Calendar.YEAR, 1); } days += a.get(Calendar.DAY_OF_YEAR) - b.get(Calendar.DAY_OF_YEAR); if (swap) days = -days; return days; } /** * Subtract another Date from this one and return the number of days of the difference. *

      * Date self = Date then + (Date self - Date then) *

      * IOW, if self is before then the result is a negative value. * * @param self a Date * @param then another Date * @return number of days * @since 1.6.0 */ public static int minus(Date self, Date then) { Calendar a = (Calendar) Calendar.getInstance().clone(); a.setTime(self); Calendar b = (Calendar) Calendar.getInstance().clone(); b.setTime(then); return minus(a, b); } /** *

      Create a String representation of this date according to the given * format pattern.

      *

      *

      For example, if the system timezone is GMT, * new Date(0).format('MM/dd/yy') would return the string * "01/01/70". See documentation for {@link java.text.SimpleDateFormat} * for format pattern use.

      *

      *

      Note that a new DateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self a Date * @param format the format pattern to use according to {@link java.text.SimpleDateFormat} * @return a string representation of this date. * @see java.text.SimpleDateFormat * @since 1.5.7 */ public static String format(Date self, String format) { return new SimpleDateFormat(format).format(self); } /** *

      Create a String representation of this date according to the given * format pattern and timezone.

      *

      *

      For example: * * def d = new Date(0) * def tz = TimeZone.getTimeZone('GMT') * println d.format('dd/MMM/yyyy', tz) * would return the string * "01/Jan/1970". See documentation for {@link java.text.SimpleDateFormat} * for format pattern use.

      *

      *

      Note that a new DateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self a Date * @param format the format pattern to use according to {@link java.text.SimpleDateFormat} * @param tz the TimeZone to use * @return a string representation of this date. * @see java.text.SimpleDateFormat * @since 1.8.3 */ public static String format(Date self, String format, TimeZone tz) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(tz); return sdf.format(self); } /** *

      Return a string representation of the 'day' portion of this date * according to the locale-specific {@link java.text.DateFormat#SHORT} default format. * For an "en_UK" system locale, this would be dd/MM/yy.

      *

      *

      Note that a new DateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self a Date * @return a string representation of this date * @see java.text.DateFormat#getDateInstance(int) * @see java.text.DateFormat#SHORT * @since 1.5.7 */ public static String getDateString(Date self) { return DateFormat.getDateInstance(DateFormat.SHORT).format(self); } /** *

      Return a string representation of the time portion of this date * according to the locale-specific {@link java.text.DateFormat#MEDIUM} default format. * For an "en_UK" system locale, this would be HH:MM:ss.

      *

      *

      Note that a new DateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self a Date * @return a string representing the time portion of this date * @see java.text.DateFormat#getTimeInstance(int) * @see java.text.DateFormat#MEDIUM * @since 1.5.7 */ public static String getTimeString(Date self) { return DateFormat.getTimeInstance(DateFormat.MEDIUM).format(self); } /** *

      Return a string representation of the date and time time portion of * this Date instance, according to the locale-specific format used by * {@link java.text.DateFormat}. This method uses the {@link java.text.DateFormat#SHORT} * preset for the day portion and {@link java.text.DateFormat#MEDIUM} for the time * portion of the output string.

      *

      *

      Note that a new DateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self a Date * @return a string representation of this date and time * @see java.text.DateFormat#getDateTimeInstance(int, int) * @since 1.5.7 */ public static String getDateTimeString(Date self) { return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(self); } /** * Common code for {@link #clearTime(java.util.Calendar)} and {@link #clearTime(java.util.Date)} * and {@link #clearTime(java.sql.Date)} * * @param self a Calendar to adjust */ private static void clearTimeCommon(final Calendar self) { self.set(Calendar.HOUR_OF_DAY, 0); self.clear(Calendar.MINUTE); self.clear(Calendar.SECOND); self.clear(Calendar.MILLISECOND); } /** * Clears the time portion of this Date instance; Util where it makes sense to * compare month/day/year only portions of a Date * * @param self a Date * @return the Date but with the time portion cleared * @since 1.6.7 */ public static Date clearTime(final Date self) { Calendar calendar = Calendar.getInstance(); calendar.setTime(self); clearTimeCommon(calendar); self.setTime(calendar.getTime().getTime()); return self; } /** * Clears the time portion of this java.sql.Date instance; useful utility * where it makes sense to compare month/day/year only portions of a Date * * @param self a java.sql.Date * @return the java.sql.Date but with the time portion cleared * @since 1.6.7 */ public static java.sql.Date clearTime(final java.sql.Date self) { Calendar calendar = Calendar.getInstance(); calendar.setTime(self); clearTimeCommon(calendar); self.setTime(calendar.getTime().getTime()); return self; } /** * Clears the time portion of this Calendar instance; useful utility * where it makes sense to compare month/day/year only portions of a Calendar. * * @param self a Calendar * @return the Calendar but with the time portion cleared * @since 1.6.7 */ public static Calendar clearTime(final Calendar self) { clearTimeCommon(self); return self; } /** *

      Shortcut for {@link java.text.SimpleDateFormat} to output a String representation * of this calendar instance. This method respects the Calendar's assigned * {@link java.util.TimeZone}, whereas calling cal.time.format('HH:mm:ss') * would use the system timezone.

      *

      Note that Calendar equivalents of date.getDateString() * and variants do not exist because those methods are Locale-dependent. * Although a Calendar may be assigned a {@link java.util.Locale}, that information is * lost and therefore cannot be used to control the default date/time formats * provided by these methods. Instead, the system Locale would always be * used. The alternative is to simply call * {@link java.text.DateFormat#getDateInstance(int, java.util.Locale)} and pass the same Locale * that was used for the Calendar.

      * * @param self this calendar * @param pattern format pattern * @return String representation of this calendar with the given format. * @see java.text.DateFormat#setTimeZone(java.util.TimeZone) * @see java.text.SimpleDateFormat#format(java.util.Date) * @see #format(java.util.Date, String) * @since 1.6.0 */ public static String format(Calendar self, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setTimeZone(self.getTimeZone()); return sdf.format(self.getTime()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/MetaClassHelper.java0000644001501200150120000012127211707612046025366 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import groovy.lang.GString; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.reflection.ParameterTypes; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.wrappers.Wrapper; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * @author John Wilson * @author Jochen Theodorou */ public class MetaClassHelper { public static final Object[] EMPTY_ARRAY = {}; public static final Class[] EMPTY_TYPE_ARRAY = {}; public static final Object[] ARRAY_WITH_NULL = {null}; protected static final Logger LOG = Logger.getLogger(MetaClassHelper.class.getName()); private static final int MAX_ARG_LEN = 12; private static final int OBJECT_SHIFT = 23, INTERFACE_SHIFT = 0, PRIMITIVE_SHIFT = 21, VARGS_SHIFT = 44; /* dist binary layout: * 0-20: interface * 21-22: primitive dist * 23-43: object dist * 44-48: vargs penalty */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; public static boolean accessibleToConstructor(final Class at, final Constructor constructor) { boolean accessible = false; final int modifiers = constructor.getModifiers(); if (Modifier.isPublic(modifiers)) { accessible = true; } else if (Modifier.isPrivate(modifiers)) { accessible = at.getName().equals(constructor.getName()); } else if (Modifier.isProtected(modifiers)) { Boolean isAccessible = checkCompatiblePackages(at, constructor); if (isAccessible != null) { accessible = isAccessible; } else { boolean flag = false; Class clazz = at; while (!flag && clazz != null) { if (clazz.equals(constructor.getDeclaringClass())) { flag = true; break; } if (clazz.equals(Object.class)) { break; } clazz = clazz.getSuperclass(); } accessible = flag; } } else { Boolean isAccessible = checkCompatiblePackages(at, constructor); if (isAccessible != null) { accessible = isAccessible; } } return accessible; } private static Boolean checkCompatiblePackages(Class at, Constructor constructor) { if (at.getPackage() == null && constructor.getDeclaringClass().getPackage() == null) { return Boolean.TRUE; } if (at.getPackage() == null && constructor.getDeclaringClass().getPackage() != null) { return Boolean.FALSE; } if (at.getPackage() != null && constructor.getDeclaringClass().getPackage() == null) { return Boolean.FALSE; } if (at.getPackage().equals(constructor.getDeclaringClass().getPackage())) { return Boolean.TRUE; } return null; } public static Object[] asWrapperArray(Object parameters, Class componentType) { Object[] ret = null; if (componentType == boolean.class) { boolean[] array = (boolean[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == char.class) { char[] array = (char[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == byte.class) { byte[] array = (byte[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == int.class) { int[] array = (int[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == short.class) { short[] array = (short[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == long.class) { long[] array = (long[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == double.class) { double[] array = (double[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } else if (componentType == float.class) { float[] array = (float[]) parameters; ret = new Object[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = array[i]; } } return ret; } /** * @param list the original list * @param parameterType the resulting array type * @return the constructed array */ public static Object asPrimitiveArray(List list, Class parameterType) { Class arrayType = parameterType.getComponentType(); Object objArray = Array.newInstance(arrayType, list.size()); for (int i = 0; i < list.size(); i++) { Object obj = list.get(i); if (arrayType.isPrimitive()) { if (obj instanceof Integer) { Array.setInt(objArray, i, (Integer) obj); } else if (obj instanceof Double) { Array.setDouble(objArray, i, (Double) obj); } else if (obj instanceof Boolean) { Array.setBoolean(objArray, i, (Boolean) obj); } else if (obj instanceof Long) { Array.setLong(objArray, i, (Long) obj); } else if (obj instanceof Float) { Array.setFloat(objArray, i, (Float) obj); } else if (obj instanceof Character) { Array.setChar(objArray, i, (Character) obj); } else if (obj instanceof Byte) { Array.setByte(objArray, i, (Byte) obj); } else if (obj instanceof Short) { Array.setShort(objArray, i, (Short) obj); } } else { Array.set(objArray, i, obj); } } return objArray; } private static final Class[] PRIMITIVES = { byte.class, Byte.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, BigInteger.class, float.class, Float.class, double.class, Double.class, BigDecimal.class, Number.class, Object.class }; private static final int[][] PRIMITIVE_DISTANCE_TABLE = { // byte Byte short Short int Integer long Long BigInteger float Float double Double BigDecimal, Number, Object /* byte*/{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,}, /*Byte*/{1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,}, /*short*/{14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,}, /*Short*/{14, 15, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,}, /*int*/{14, 15, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,}, /*Integer*/{14, 15, 12, 13, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,}, /*long*/{14, 15, 12, 13, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,}, /*Long*/{14, 15, 12, 13, 10, 11, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9,}, /*BigInteger*/{9, 10, 7, 8, 5, 6, 3, 4, 0, 14, 15, 12, 13, 11, 1, 2,}, /*float*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 0, 1, 2, 3, 4, 5, 6,}, /*Float*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 1, 0, 2, 3, 4, 5, 6,}, /*double*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 5, 6, 0, 1, 2, 3, 4,}, /*Double*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 5, 6, 1, 0, 2, 3, 4,}, /*BigDecimal*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 5, 6, 3, 4, 0, 1, 2,}, /*Number*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 5, 6, 3, 4, 2, 0, 1,}, /*Object*/{14, 15, 12, 13, 10, 11, 8, 9, 7, 5, 6, 3, 4, 2, 1, 0,}, }; private static int getPrimitiveIndex(Class c) { for (byte i = 0; i < PRIMITIVES.length; i++) { if (PRIMITIVES[i] == c) return i; } return -1; } private static int getPrimitiveDistance(Class from, Class to) { // we know here that from!=to, so a distance of 0 is never valid // get primitive type indexes int fromIndex = getPrimitiveIndex(from); int toIndex = getPrimitiveIndex(to); if (fromIndex == -1 || toIndex == -1) return -1; return PRIMITIVE_DISTANCE_TABLE[toIndex][fromIndex]; } private static int getMaximumInterfaceDistance(Class c, Class interfaceClass) { // -1 means a mismatch if (c == null) return -1; // 0 means a direct match if (c == interfaceClass) return 0; Class[] interfaces = c.getInterfaces(); int max = -1; for (Class anInterface : interfaces) { int sub = getMaximumInterfaceDistance(anInterface, interfaceClass); // we need to keep the -1 to track the mismatch, a +1 // by any means could let it look like a direct match // we want to add one, because there is an interface between // the interface we search for and the interface we are in. if (sub != -1) sub++; // we are interested in the longest path only max = Math.max(max, sub); } // we do not add one for super classes, only for interfaces int superClassMax = getMaximumInterfaceDistance(c.getSuperclass(), interfaceClass); return Math.max(max, superClassMax); } private static long calculateParameterDistance(Class argument, CachedClass parameter) { /** * note: when shifting with 32 bit, you should only shift on a long. If you do * that with an int, then i==(i<<32), which means you loose the shift * information */ if (parameter.getTheClass() == argument) return 0; if (parameter.isInterface()) { return getMaximumInterfaceDistance(argument, parameter.getTheClass()) << INTERFACE_SHIFT; } long objectDistance = 0; if (argument != null) { long pd = getPrimitiveDistance(parameter.getTheClass(), argument); if (pd != -1) return pd << PRIMITIVE_SHIFT; // add one to dist to be sure interfaces are preferred objectDistance += PRIMITIVES.length + 1; // GROOVY-5114 : if we have to choose between two methods // foo(Object[]) and foo(Object) and that the argument is an array type // then the array version should be preferred if (argument.isArray() && !parameter.isArray) { objectDistance+=4; } Class clazz = ReflectionCache.autoboxType(argument); while (clazz != null) { if (clazz == parameter.getTheClass()) break; if (clazz == GString.class && parameter.getTheClass() == String.class) { objectDistance += 2; break; } clazz = clazz.getSuperclass(); objectDistance += 3; } } else { // choose the distance to Object if a parameter is null // this will mean that Object is preferred over a more // specific type Class clazz = parameter.getTheClass(); if (clazz.isPrimitive()) { objectDistance += 2; } else { while (clazz != Object.class) { clazz = clazz.getSuperclass(); objectDistance += 2; } } } return objectDistance << OBJECT_SHIFT; } public static long calculateParameterDistance(Class[] arguments, ParameterTypes pt) { CachedClass[] parameters = pt.getParameterTypes(); if (parameters.length == 0) return 0; long ret = 0; int noVargsLength = parameters.length - 1; // if the number of parameters does not match we have // a vargs usage // // case A: arguments.lengthparameters.length // // In this case all arguments with a index bigger than // paramMinus1 are part of the vargs, so a // distance calculation needs to be done against // parameters[noVargsLength].getComponentType() // // VArgs penalty: 2l+arguments.length-parameters.length // // case C: arguments.length==parameters.length && // isAssignableFrom( parameters[noVargsLength], // arguments[noVargsLength] ) // // In this case we have no vargs, so calculate directly // // VArgs penalty: 0l // // case D: arguments.length==parameters.length && // !isAssignableFrom( parameters[noVargsLength], // arguments[noVargsLength] ) // // In this case we have a vargs case again, we need // to calculate arguments[noVargsLength] against // parameters[noVargsLength].getComponentType // // VArgs penalty: 2l // // This gives: VArgs_penalty(C) case B * def foo(a,b,Object[] c) {2} -> case A * assert foo(new Object(),new Object()) == 2 * --> A preferred over B * * A vs C : * def foo(Object[] a) {1} -> case B * def foo(a,b) {2} -> case C * assert foo(new Object(),new Object()) == 2 * --> C preferred over A * * A vs D : * def foo(Object[] a) {1} -> case D * def foo(a,Object[] b) {2} -> case A * assert foo(new Object()) == 2 * --> A preferred over D * * This gives C case B * def foo(a,b) {2} -> case C * assert foo(new Object(),new Object()) == 2 * --> C preferred over B, matches C case B * def foo(a,Object[] b) {2} -> case D * assert foo(new Object(),new Object()) == 2 * --> D preferred over B * * This gives C parameters.length) { // case B // we give our a vargs penalty for each exceeding argument and iterate // by using parameters[noVargsLength].getComponentType() ret += (2l + arguments.length - parameters.length) << VARGS_SHIFT; // penalty for vargs CachedClass vargsType = ReflectionCache.getCachedClass(parameters[noVargsLength].getTheClass().getComponentType()); for (int i = noVargsLength; i < arguments.length; i++) { ret += calculateParameterDistance(arguments[i], vargsType); } } else { // case A // we give a penalty for vargs, since we have no direct // match for the last argument ret += 1l << VARGS_SHIFT; } return ret; } /** * This is the complement to the java.beans.Introspector.decapitalize(String) method. * We handle names that begin with an initial lowerCase followed by upperCase specially * (which is to make no change). * See GROOVY-3211. * * @param property the property name to capitalize * @return the name capitalized, except when we don't */ public static String capitalize(final String property) { final String rest = property.substring(1); // Funky rule so that names like 'pNAME' will still work. if (Character.isLowerCase(property.charAt(0)) && (rest.length() > 0) && Character.isUpperCase(rest.charAt(0))) { return property; } return property.substring(0, 1).toUpperCase() + rest; } /** * @param methods the methods to choose from * @return the method with 1 parameter which takes the most general type of * object (e.g. Object) */ public static Object chooseEmptyMethodParams(FastArray methods) { Object vargsMethod = null; final int len = methods.size(); final Object[] data = methods.getArray(); for (int i = 0; i != len; ++i) { Object method = data[i]; final ParameterTypes pt = (ParameterTypes) method; CachedClass[] paramTypes = pt.getParameterTypes(); int paramLength = paramTypes.length; if (paramLength == 0) { return method; } else if (paramLength == 1 && pt.isVargsMethod(EMPTY_ARRAY)) { vargsMethod = method; } } return vargsMethod; } /** * @param methods the methods to choose from * @return the method with 1 parameter which takes the most general type of * object (e.g. Object) ignoring primitive types */ public static Object chooseMostGeneralMethodWith1NullParam(FastArray methods) { // let's look for methods with 1 argument which matches the type of the // arguments CachedClass closestClass = null; CachedClass closestVargsClass = null; Object answer = null; int closestDist = -1; final int len = methods.size(); for (int i = 0; i != len; ++i) { final Object[] data = methods.getArray(); Object method = data[i]; final ParameterTypes pt = (ParameterTypes) method; CachedClass[] paramTypes = pt.getParameterTypes(); int paramLength = paramTypes.length; if (paramLength == 0 || paramLength > 2) continue; CachedClass theType = paramTypes[0]; if (theType.isPrimitive) continue; if (paramLength == 2) { if (!pt.isVargsMethod(ARRAY_WITH_NULL)) continue; if (closestClass == null) { closestVargsClass = paramTypes[1]; closestClass = theType; answer = method; } else if (closestClass.getTheClass() == theType.getTheClass()) { if (closestVargsClass == null) continue; CachedClass newVargsClass = paramTypes[1]; if (isAssignableFrom(newVargsClass.getTheClass(), closestVargsClass.getTheClass())) { closestVargsClass = newVargsClass; answer = method; } } else if (isAssignableFrom(theType.getTheClass(), closestClass.getTheClass())) { closestVargsClass = paramTypes[1]; closestClass = theType; answer = method; } } else { if (closestClass == null || isAssignableFrom(theType.getTheClass(), closestClass.getTheClass())) { closestVargsClass = null; closestClass = theType; answer = method; closestDist = -1; } else { // closestClass and theType are not in a subtype relation, we need // to check the distance to Object if (closestDist == -1) closestDist = closestClass.getSuperClassDistance(); int newDist = theType.getSuperClassDistance(); if (newDist < closestDist) { closestDist = newDist; closestVargsClass = null; closestClass = theType; answer = method; } } } } return answer; } // private static int calculateSimplifiedClassDistanceToObject(Class clazz) { int objectDistance = 0; while (clazz != null) { clazz = clazz.getSuperclass(); objectDistance++; } return objectDistance; } /** * @param list a list of MetaMethods * @param method the MetaMethod of interest * @return true if a method of the same matching prototype was found in the * list */ public static boolean containsMatchingMethod(List list, MetaMethod method) { for (Object aList : list) { MetaMethod aMethod = (MetaMethod) aList; CachedClass[] params1 = aMethod.getParameterTypes(); CachedClass[] params2 = method.getParameterTypes(); if (params1.length == params2.length) { boolean matches = true; for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) { matches = false; break; } } if (matches) { return true; } } } return false; } /** * param instance array to the type array * * @param args the arguments * @return the types of the arguments */ public static Class[] convertToTypeArray(Object[] args) { if (args == null) return null; int s = args.length; Class[] ans = new Class[s]; for (int i = 0; i < s; i++) { Object o = args[i]; if (o == null) { ans[i] = null; } else if (o instanceof Wrapper) { ans[i] = ((Wrapper) o).getType(); } else { ans[i] = o.getClass(); } } return ans; } public static Object makeCommonArray(Object[] arguments, int offset, Class fallback) { // arguments.length>0 && !=null Class baseClass = null; for (int i = offset; i < arguments.length; i++) { if (arguments[i] == null) continue; Class argClass = arguments[i].getClass(); if (baseClass == null) { baseClass = argClass; } else { for (; baseClass != Object.class; baseClass = baseClass.getSuperclass()) { if (baseClass.isAssignableFrom(argClass)) break; } } } if (baseClass == null) { // all arguments were null baseClass = fallback; } /* * If no specific super class has been found and type fallback is an interface, check if all arg classes * implement it. If yes, then that interface is the common type across arguments. */ if (baseClass == Object.class && fallback.isInterface()) { int tmpCount = 0; for (int i = offset; i < arguments.length; i++) { if (arguments[i] != null) { Class argClass, tmpClass; Set intfs = new HashSet(); tmpClass = argClass = arguments[i].getClass(); for (; tmpClass != Object.class; tmpClass = tmpClass.getSuperclass()) { intfs.addAll(Arrays.asList(tmpClass.getInterfaces())); } if (intfs.contains(fallback)) { tmpCount++; } } } // all arg classes implement interface fallback, so use that as the array component type if (tmpCount == arguments.length - offset) { baseClass = fallback; } } Object result = makeArray(null, baseClass, arguments.length - offset); System.arraycopy(arguments, offset, result, 0, arguments.length - offset); return result; } public static Object makeArray(Object obj, Class secondary, int length) { Class baseClass = secondary; if (obj != null) { baseClass = obj.getClass(); } /*if (GString.class.isAssignableFrom(baseClass)) { baseClass = GString.class; }*/ return Array.newInstance(baseClass, length); } public static GroovyRuntimeException createExceptionText(String init, MetaMethod method, Object object, Object[] args, Throwable reason, boolean setReason) { return new GroovyRuntimeException( init + method + " on: " + object + " with arguments: " + InvokerHelper.toString(args) + " reason: " + reason, setReason ? reason : null); } protected static String getClassName(Object object) { if (object == null) return null; return (object instanceof Class) ? ((Class) object).getName() : object.getClass().getName(); } /** * Returns a callable object for the given method name on the object. * The object acts like a Closure in that it can be called, like a closure * and passed around - though really its a method pointer, not a closure per se. * * @param object the object containing the method * @param methodName the method of interest * @return the resulting closure-like method pointer */ public static Closure getMethodPointer(Object object, String methodName) { return new MethodClosure(object, methodName); } public static boolean isAssignableFrom(Class classToTransformTo, Class classToTransformFrom) { if (classToTransformTo == classToTransformFrom) return true; if (classToTransformFrom == null) return true; if (classToTransformTo == Object.class) return true; classToTransformTo = ReflectionCache.autoboxType(classToTransformTo); classToTransformFrom = ReflectionCache.autoboxType(classToTransformFrom); if (classToTransformTo == classToTransformFrom) return true; // note: there is no coercion for boolean and char. Range matters, precision doesn't if (classToTransformTo == Integer.class) { if (classToTransformFrom == Integer.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == BigInteger.class) return true; } else if (classToTransformTo == Double.class) { if (classToTransformFrom == Double.class || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Float.class || classToTransformFrom == BigDecimal.class || classToTransformFrom == BigInteger.class) return true; } else if (classToTransformTo == BigDecimal.class) { if (classToTransformFrom == Double.class || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Float.class || classToTransformFrom == BigDecimal.class || classToTransformFrom == BigInteger.class) return true; } else if (classToTransformTo == BigInteger.class) { if (classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == BigInteger.class) return true; } else if (classToTransformTo == Long.class) { if (classToTransformFrom == Long.class || classToTransformFrom == Integer.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class) return true; } else if (classToTransformTo == Float.class) { if (classToTransformFrom == Float.class || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class) return true; } else if (classToTransformTo == Short.class) { if (classToTransformFrom == Short.class || classToTransformFrom == Byte.class) return true; } else if (classToTransformTo == String.class) { if (classToTransformFrom == String.class || GString.class.isAssignableFrom(classToTransformFrom)) { return true; } } return ReflectionCache.isAssignableFrom(classToTransformTo, classToTransformFrom); } public static boolean isGenericSetMethod(MetaMethod method) { return (method.getName().equals("set")) && method.getParameterTypes().length == 2; } protected static boolean isSuperclass(Class clazz, Class superclass) { while (clazz != null) { if (clazz == superclass) return true; clazz = clazz.getSuperclass(); } return false; } public static boolean parametersAreCompatible(Class[] arguments, Class[] parameters) { if (arguments.length != parameters.length) return false; for (int i = 0; i < arguments.length; i++) { if (!isAssignableFrom(parameters[i], arguments[i])) return false; } return true; } public static void logMethodCall(Object object, String methodName, Object[] arguments) { String className = getClassName(object); String logname = "methodCalls." + className + "." + methodName; Logger objLog = Logger.getLogger(logname); if (!objLog.isLoggable(Level.FINER)) return; StringBuffer msg = new StringBuffer(methodName); msg.append("("); if (arguments != null) { for (int i = 0; i < arguments.length;) { msg.append(normalizedValue(arguments[i])); if (++i < arguments.length) { msg.append(","); } } } msg.append(")"); objLog.logp(Level.FINER, className, msg.toString(), "called from MetaClass.invokeMethod"); } protected static String normalizedValue(Object argument) { String value; try { value = argument.toString(); if (value.length() > MAX_ARG_LEN) { value = value.substring(0, MAX_ARG_LEN - 2) + ".."; } if (argument instanceof String) { value = "\'" + value + "\'"; } } catch (Exception e) { value = shortName(argument); } return value; } protected static String shortName(Object object) { if (object == null || object.getClass() == null) return "unknownClass"; String name = getClassName(object); if (name == null) return "unknownClassName"; // *very* defensive... int lastDotPos = name.lastIndexOf('.'); if (lastDotPos < 0 || lastDotPos >= name.length() - 1) return name; return name.substring(lastDotPos + 1); } public static Class[] wrap(Class[] classes) { Class[] wrappedArguments = new Class[classes.length]; for (int i = 0; i < wrappedArguments.length; i++) { Class c = classes[i]; if (c == null) continue; if (c.isPrimitive()) { if (c == Integer.TYPE) { c = Integer.class; } else if (c == Byte.TYPE) { c = Byte.class; } else if (c == Long.TYPE) { c = Long.class; } else if (c == Double.TYPE) { c = Double.class; } else if (c == Float.TYPE) { c = Float.class; } } else if (isSuperclass(c, GString.class)) { c = String.class; } wrappedArguments[i] = c; } return wrappedArguments; } public static boolean sameClasses(Class[] params, Object[] arguments, boolean weakNullCheck) { if (params.length != arguments.length) return false; for (int i = params.length - 1; i >= 0; i--) { Object arg = arguments[i]; if (arg == null) { if (!weakNullCheck) return false; } else { if (params[i] != arg.getClass() && (!(arg instanceof Wrapper) || params[i] != ((Wrapper) arg).getType())) return false; } } return true; } public static boolean sameClasses(Class[] params, Object[] arguments) { if (params.length != arguments.length) return false; for (int i = params.length - 1; i >= 0; i--) { Object arg = arguments[i]; if (arg == null) { if (params[i] != null) return false; } else { if (params[i] != arg.getClass() && !(arg instanceof Wrapper && params[i] == ((Wrapper) arg).getType())) return false; } } return true; } public static boolean sameClasses(Class[] params) { if (params.length != 0) return false; return true; } public static boolean sameClasses(Class[] params, Object arg1) { if (params.length != 1) return false; if (arg1 == null || (params[0] != arg1.getClass() && (!(arg1 instanceof Wrapper) || params[0] != ((Wrapper) arg1).getType()))) return false; return true; } public static boolean sameClasses(Class[] params, Object arg1, Object arg2) { if (params.length != 2) return false; if (arg1 == null || (params[0] != arg1.getClass() && (!(arg1 instanceof Wrapper) || params[0] != ((Wrapper) arg1).getType()))) return false; if (arg2 == null || (params[1] != arg2.getClass() && (!(arg2 instanceof Wrapper) || params[1] != ((Wrapper) arg2).getType()))) return false; return true; } public static boolean sameClasses(Class[] params, Object arg1, Object arg2, Object arg3) { if (params.length != 3) return false; if (arg1 == null || (params[0] != arg1.getClass() && (!(arg1 instanceof Wrapper) || params[0] != ((Wrapper) arg1).getType()))) return false; if (arg2 == null || (params[1] != arg2.getClass() && (!(arg2 instanceof Wrapper) || params[1] != ((Wrapper) arg2).getType()))) return false; if (arg3 == null || (params[2] != arg3.getClass() && (!(arg3 instanceof Wrapper) || params[2] != ((Wrapper) arg3).getType()))) return false; return true; } public static boolean sameClasses(Class[] params, Object arg1, Object arg2, Object arg3, Object arg4) { if (params.length != 4) return false; if (arg1 == null || (params[0] != arg1.getClass() && (!(arg1 instanceof Wrapper) || params[0] != ((Wrapper) arg1).getType()))) return false; if (arg2 == null || (params[1] != arg2.getClass() && (!(arg2 instanceof Wrapper) || params[1] != ((Wrapper) arg2).getType()))) return false; if (arg3 == null || (params[2] != arg3.getClass() && (!(arg3 instanceof Wrapper) || params[2] != ((Wrapper) arg3).getType()))) return false; if (arg4 == null || (params[3] != arg4.getClass() && (!(arg4 instanceof Wrapper) || params[3] != ((Wrapper) arg4).getType()))) return false; return true; } public static boolean sameClass(Class[] params, Object arg) { return !(arg == null || (params[0] != arg.getClass() && (!(arg instanceof Wrapper) || params[0] != ((Wrapper) arg).getType()))); } public static Class[] castArgumentsToClassArray(Object[] argTypes) { if (argTypes == null) return EMPTY_CLASS_ARRAY; Class[] classes = new Class[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { Object argType = argTypes[i]; if (argType instanceof Class) { classes[i] = (Class) argType; } else if (argType == null) { classes[i] = null; } else { // throw new IllegalArgumentException("Arguments to method [respondsTo] must be of type java.lang.Class!"); classes[i] = argType.getClass(); } } return classes; } public static void unwrap(Object[] arguments) { // // Temp code to ignore wrapped parameters // The New MOP will deal with these properly // for (int i = 0; i != arguments.length; i++) { if (arguments[i] instanceof Wrapper) { arguments[i] = ((Wrapper) arguments[i]).unwrap(); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/SqlGroovyMethods.java0000644001501200150120000001016111627206700025632 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GroovyRuntimeException; import groovy.sql.GroovyResultSet; import groovy.sql.GroovyRowResult; import groovy.sql.ResultSetMetaDataWrapper; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; /** * This class defines all the new SQL-related groovy methods which enhance * the normal JDK SQL classes when inside the Groovy environment. * Static methods are used with the first parameter the destination class. * * @author Paul King * @author John Hurst */ public class SqlGroovyMethods { /** * Returns a GroovyRowResult given a ResultSet. * * @param rs a ResultSet * @return the resulting GroovyRowResult * @throws java.sql.SQLException if a database error occurs * @since 1.6.0 */ public static GroovyRowResult toRowResult(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); Map lhm = new LinkedHashMap(metadata.getColumnCount(), 1); for (int i = 1; i <= metadata.getColumnCount(); i++) { lhm.put(metadata.getColumnLabel(i), rs.getObject(i)); } return new GroovyRowResult(lhm); } /** * Return a java.sql.Timestamp given a java.util.Date. * * @param d a date * @return the date wrapped as a Timestamp * @since 1.6.6 */ public static Timestamp toTimestamp(Date d) { return new Timestamp(d.getTime()); } /** * Coerce a GroovyResultSet to a boolean value. * A GroovyResultSet is coerced to false if there are no more rows to iterate over, * and to true otherwise. * * @param grs the GroovyResultSet * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(GroovyResultSet grs) { //TODO: check why this asBoolean() method is needed for SqlTest to pass with custom boolean coercion in place return true; } /** * Return an Iterator given a ResultSetMetaData. * * Enables Groovy collection method syntactic sugar on ResultSetMetaData. * * @param resultSetMetaData the ResultSetMetaData to iterate over * @return an iterator for the ResultSetMetaData * @since 1.7 */ public static Iterator iterator(ResultSetMetaData resultSetMetaData) { return new ResultSetMetaDataIterator(resultSetMetaData); } private static class ResultSetMetaDataIterator implements Iterator { private ResultSetMetaData target; private int index = 1; public ResultSetMetaDataIterator(ResultSetMetaData target) { this.target = target; } public boolean hasNext() { try { return index <= target.getColumnCount(); } catch (SQLException ex) { throw new GroovyRuntimeException("Unable to obtain column count from ResultSetMetaData", ex); } } public ResultSetMetaDataWrapper next() { return new ResultSetMetaDataWrapper(target, index++); } public void remove() { throw new UnsupportedOperationException("Cannot remove from ResultSetMetaData"); } } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/0000755001501200150120000000000011715031256024165 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/BigDecimalMath.java0000644001501200150120000000543011627206700027624 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; import java.math.BigDecimal; import java.math.MathContext; /** * BigDecimal NumberMath operations * * @author Steve Goetze */ public final class BigDecimalMath extends NumberMath { // This is an arbitrary value, picked as a reasonable choice for a precision // for typical user math when a non-terminating result would otherwise occur. public static final int DIVISION_EXTRA_PRECISION = 10; //This is an arbitrary value, picked as a reasonable choice for a rounding point //for typical user math. public static final int DIVISION_MIN_SCALE = 10; public static final BigDecimalMath INSTANCE = new BigDecimalMath(); private BigDecimalMath() { } protected Number absImpl(Number number) { return toBigDecimal(number).abs(); } public Number addImpl(Number left, Number right) { return toBigDecimal(left).add(toBigDecimal(right)); } public Number subtractImpl(Number left, Number right) { return toBigDecimal(left).subtract(toBigDecimal(right)); } public Number multiplyImpl(Number left, Number right) { return toBigDecimal(left).multiply(toBigDecimal(right)); } public Number divideImpl(Number left, Number right) { BigDecimal bigLeft = toBigDecimal(left); BigDecimal bigRight = toBigDecimal(right); try { return bigLeft.divide(bigRight); } catch (ArithmeticException e) { // set a DEFAULT precision if otherwise non-terminating int precision = Math.max(bigLeft.precision(), bigRight.precision()) + DIVISION_EXTRA_PRECISION; BigDecimal result = bigLeft.divide(bigRight, new MathContext(precision)); int scale = Math.max(Math.max(bigLeft.scale(), bigRight.scale()), DIVISION_MIN_SCALE); if (result.scale() > scale) result = result.setScale(scale, BigDecimal.ROUND_HALF_UP); return result; } } public int compareToImpl(Number left, Number right) { return toBigDecimal(left).compareTo(toBigDecimal(right)); } protected Number unaryMinusImpl(Number left) { return toBigDecimal(left).negate(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/NumberMath.java0000644001501200150120000002416511627206700027102 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; import java.math.BigDecimal; import java.math.BigInteger; /** * Stateless objects used to perform math on the various Number subclasses. * Instances are required so that polymorphic calls work properly, but each * subclass creates a singleton instance to minimize garbage. All methods * must be thread-safe. * * The design goals of this class are as follows: *
        *
      1. Support a 'least surprising' math model to scripting language users. This * means that exact, or decimal math should be used for default calculations. This * scheme assumes that by default, groovy literals with decimal points are instantiated * as BigDecimal objects rather than binary floating points (Float, Double). *
      2. Do not force the appearance of exactness on a number that is by definition not * guaranteed to be exact. In particular this means that if an operand in a NumberMath * operation is a binary floating point number, ensure that the result remains a binary floating point * number (i.e. never automatically promote a binary floating point number to a BigDecimal). * This has the effect of preserving the expectations of binary floating point users and helps performance. *
      3. Provide an implementation that is as close as practical to the Java 1.5 BigDecimal math model * which implements precision based floating point decimal math (ANSI X3.274-1996 and * ANSI X3.274-1996/AM 1-2000 (section 7.4). *
      * * @author Steve Goetze */ public abstract class NumberMath { public static Number abs(Number number) { return getMath(number).absImpl(number); } public static Number add(Number left, Number right) { return getMath(left, right).addImpl(left,right); } public static Number subtract(Number left, Number right) { return getMath(left,right).subtractImpl(left,right); } public static Number multiply(Number left, Number right) { return getMath(left,right).multiplyImpl(left,right); } public static Number divide(Number left, Number right) { return getMath(left,right).divideImpl(left,right); } public static int compareTo(Number left, Number right) { return getMath(left,right).compareToImpl(left, right); } public static Number or(Number left, Number right) { return getMath(left,right).orImpl(left, right); } public static Number and(Number left, Number right) { return getMath(left,right).andImpl(left, right); } public static Number xor(Number left, Number right) { return getMath(left,right).xorImpl(left, right); } public static Number intdiv(Number left, Number right) { return getMath(left,right).intdivImpl(left,right); } public static Number mod(Number left, Number right) { return getMath(left,right).modImpl(left, right); } /** * For this operation, consider the operands independently. Throw an exception if the right operand * (shift distance) is not an integral type. For the left operand (shift value) also require an integral * type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the * shift operators. */ public static Number leftShift(Number left, Number right) { if (isFloatingPoint(right) || isBigDecimal(right)) { throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied"); } return getMath(left).leftShiftImpl(left,right); } /** * For this operation, consider the operands independently. Throw an exception if the right operand * (shift distance) is not an integral type. For the left operand (shift value) also require an integral * type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the * shift operators. */ public static Number rightShift(Number left, Number right) { if (isFloatingPoint(right) || isBigDecimal(right)) { throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied"); } return getMath(left).rightShiftImpl(left,right); } /** * For this operation, consider the operands independently. Throw an exception if the right operand * (shift distance) is not an integral type. For the left operand (shift value) also require an integral * type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the * shift operators. */ public static Number rightShiftUnsigned(Number left, Number right) { if (isFloatingPoint(right) || isBigDecimal(right)) { throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied"); } return getMath(left).rightShiftUnsignedImpl(left,right); } public static Number unaryMinus(Number left) { return getMath(left).unaryMinusImpl(left); } public static boolean isFloatingPoint(Number number) { return number instanceof Double || number instanceof Float; } public static boolean isInteger(Number number) { return number instanceof Integer; } public static boolean isLong(Number number) { return number instanceof Long; } public static boolean isBigDecimal(Number number) { return number instanceof BigDecimal; } public static boolean isBigInteger(Number number) { return number instanceof BigInteger; } public static BigDecimal toBigDecimal(Number n) { return (n instanceof BigDecimal ? (BigDecimal) n : new BigDecimal(n.toString())); } public static BigInteger toBigInteger(Number n) { return (n instanceof BigInteger ? (BigInteger) n : new BigInteger(n.toString())); } /** * Determine which NumberMath instance to use, given the supplied operands. This method implements * the type promotion rules discussed in the documentation. Note that by the time this method is * called, any Byte, Character or Short operands will have been promoted to Integer. For reference, * here is the promotion matrix: * bD bI D F L I * bD bD bD D D bD bD * bI bD bI D D bI bI * D D D D D D D * F D D D D D D * L bD bI D D L L * I bD bI D D L I * * Note that for division, if either operand isFloatingPoint, the result will be floating. Otherwise, * the result is BigDecimal */ public static NumberMath getMath(Number left, Number right) { if (isFloatingPoint(left) || isFloatingPoint(right)) { return FloatingPointMath.INSTANCE; } if (isBigDecimal(left) || isBigDecimal(right)) { return BigDecimalMath.INSTANCE; } if (isBigInteger(left) || isBigInteger(right)) { return BigIntegerMath.INSTANCE; } if (isLong(left) || isLong(right)){ return LongMath.INSTANCE; } return IntegerMath.INSTANCE; } private static NumberMath getMath(Number number) { if (isLong(number)) { return LongMath.INSTANCE; } if (isFloatingPoint(number)) { return FloatingPointMath.INSTANCE; } if (isBigDecimal(number)) { return BigDecimalMath.INSTANCE; } if (isBigInteger(number)) { return BigIntegerMath.INSTANCE; } return IntegerMath.INSTANCE; } //Subclasses implement according to the type promotion hierarchy rules protected abstract Number absImpl(Number number); public abstract Number addImpl(Number left, Number right); public abstract Number subtractImpl(Number left, Number right); public abstract Number multiplyImpl(Number left, Number right); public abstract Number divideImpl(Number left, Number right); public abstract int compareToImpl(Number left, Number right); protected abstract Number unaryMinusImpl(Number left); protected Number orImpl(Number left, Number right) { throw createUnsupportedException("or()", left); } protected Number andImpl(Number left, Number right) { throw createUnsupportedException("and()", left); } protected Number xorImpl(Number left, Number right) { throw createUnsupportedException("xor()", left); } protected Number modImpl(Number left, Number right) { throw createUnsupportedException("mod()", left); } protected Number intdivImpl(Number left, Number right) { throw createUnsupportedException("intdiv()", left); } protected Number leftShiftImpl(Number left, Number right) { throw createUnsupportedException("leftShift()", left); } protected Number rightShiftImpl(Number left, Number right) { throw createUnsupportedException("rightShift()", left); } protected Number rightShiftUnsignedImpl(Number left, Number right) { throw createUnsupportedException("rightShiftUnsigned()", left); } protected UnsupportedOperationException createUnsupportedException(String operation, Number left) { return new UnsupportedOperationException("Cannot use " + operation + " on this number type: " + left.getClass().getName() + " with value: " + left); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.java0000644001501200150120000007635211715031256032222 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; import groovy.lang.GString; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; /** * Class providing various type conversions, coercions and boxing/unboxing operations. * * @author Guillaume Laforge */ public class DefaultTypeTransformation { protected static final Object[] EMPTY_ARGUMENTS = {}; protected static final BigInteger ONE_NEG = new BigInteger("-1"); // -------------------------------------------------------- // unboxing methods // -------------------------------------------------------- public static byte byteUnbox(Object value) { Number n = castToNumber(value, byte.class); return n.byteValue(); } public static char charUnbox(Object value) { return castToChar(value); } public static short shortUnbox(Object value) { Number n = castToNumber(value, short.class); return n.shortValue(); } public static int intUnbox(Object value) { Number n = castToNumber(value, int.class); return n.intValue(); } public static boolean booleanUnbox(Object value) { return castToBoolean(value); } public static long longUnbox(Object value) { Number n = castToNumber(value, long.class); return n.longValue(); } public static float floatUnbox(Object value) { Number n = castToNumber(value, float.class); return n.floatValue(); } public static double doubleUnbox(Object value) { Number n = castToNumber(value, double.class); return n.doubleValue(); } // -------------------------------------------------------- // boxing methods // -------------------------------------------------------- public static Object box(boolean value) { return value ? Boolean.TRUE : Boolean.FALSE; } public static Object box(byte value) { return Byte.valueOf(value); } public static Object box(char value) { return Character.valueOf(value); } public static Object box(short value) { return Short.valueOf(value); } public static Object box(int value) { return Integer.valueOf(value); } public static Object box(long value) { return Long.valueOf(value); } public static Object box(float value) { return Float.valueOf(value); } public static Object box(double value) { return Double.valueOf(value); } public static Number castToNumber(Object object) { // default to Number class in exception details, else use the specified Number subtype. return castToNumber(object, Number.class); } public static Number castToNumber(Object object, Class type) { if (object instanceof Number) return (Number) object; if (object instanceof Character) { return Integer.valueOf(((Character) object).charValue()); } if (object instanceof GString) { String c = ((GString) object).toString(); if (c.length() == 1) { return Integer.valueOf(c.charAt(0)); } else { throw new GroovyCastException(c, type); } } if (object instanceof String) { String c = (String) object; if (c.length() == 1) { return Integer.valueOf(c.charAt(0)); } else { throw new GroovyCastException(c, type); } } throw new GroovyCastException(object, type); } /** * Method used for coercing an object to a boolean value, * thanks to an asBoolean() method added on types. * * @param object to coerce to a boolean value * @return a boolean value */ public static boolean castToBoolean(Object object) { // null is always false if (object == null) { return false; } // equality check is enough and faster than instanceof check, no need to check superclasses since Boolean is final if (object.getClass() == Boolean.class) { return ((Boolean)object).booleanValue(); } // if the object is not null and no Boolean, try to call an asBoolean() method on the object return (Boolean)InvokerHelper.invokeMethod(object, "asBoolean", InvokerHelper.EMPTY_ARGS); } public static char castToChar(Object object) { if (object instanceof Character) { return ((Character) object).charValue(); } else if (object instanceof Number) { Number value = (Number) object; return (char) value.intValue(); } else { String text = object.toString(); if (text.length() == 1) { return text.charAt(0); } else { throw new GroovyCastException(text,char.class); } } } public static Object castToType(Object object, Class type) { if (object == null) { return null; } if (type == Object.class) return object; final Class aClass = object.getClass(); if (type == aClass) return object; // TODO we should move these methods to groovy method, like g$asType() so that // we can use operator overloading to customize on a per-type basis if (ReflectionCache.isArray(type)) { return asArray(object, type); } if (ReflectionCache.isAssignableFrom(type, aClass)) { return object; } if (Collection.class.isAssignableFrom(type)) { int modifiers = type.getModifiers(); Collection answer; if (object instanceof Collection && type.isAssignableFrom(HashSet.class) && (type == HashSet.class || Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) { return new HashSet((Collection)object); } if (aClass.isArray()) { if (type.isAssignableFrom(ArrayList.class) && (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) { answer = new ArrayList(); } else if (type.isAssignableFrom(HashSet.class) && (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) { answer = new HashSet(); } else { // let's call the collections constructor // passing in the list wrapper try { answer = (Collection) type.newInstance(); } catch (Exception e) { throw new GroovyCastException("Could not instantiate instance of: " + type.getName() + ". Reason: " + e); } } // we cannot just wrap in a List as we support primitive type arrays int length = Array.getLength(object); for (int i = 0; i < length; i++) { Object element = Array.get(object, i); answer.add(element); } return answer; } } if (type == String.class) { return object.toString(); } else if (type == Character.class) { return box(castToChar(object)); } else if (type == Boolean.class) { return box(castToBoolean(object)); } else if (type == Class.class) { return castToClass(object); } else if (Number.class.isAssignableFrom(type)) { Number n = castToNumber(object, type); if (type == Byte.class) { return new Byte(n.byteValue()); } else if (type == Character.class) { return new Character((char) n.intValue()); } else if (type == Short.class) { return new Short(n.shortValue()); } else if (type == Integer.class) { return Integer.valueOf(n.intValue()); } else if (type == Long.class) { return new Long(n.longValue()); } else if (type == Float.class) { return new Float(n.floatValue()); } else if (type == Double.class) { Double answer = new Double(n.doubleValue()); //throw a runtime exception if conversion would be out-of-range for the type. if (!(n instanceof Double) && (answer.doubleValue() == Double.NEGATIVE_INFINITY || answer.doubleValue() == Double.POSITIVE_INFINITY)) { throw new GroovyRuntimeException("Automatic coercion of " + n.getClass().getName() + " value " + n + " to double failed. Value is out of range."); } return answer; } else if (type == BigDecimal.class) { if (n instanceof Float || n instanceof Double) { return new BigDecimal(n.doubleValue()); } return new BigDecimal(n.toString()); } else if (type == BigInteger.class) { if (object instanceof Float || object instanceof Double) { BigDecimal bd = new BigDecimal(n.doubleValue()); return bd.toBigInteger(); } else if (object instanceof BigDecimal) { return ((BigDecimal) object).toBigInteger(); } else { return new BigInteger(n.toString()); } } } else if (type.isPrimitive()) { if (type == boolean.class) { return box(booleanUnbox(object)); } else if (type == byte.class) { return box(byteUnbox(object)); } else if (type == char.class) { return box(charUnbox(object)); } else if (type == short.class) { return box(shortUnbox(object)); } else if (type == int.class) { return box(intUnbox(object)); } else if (type == long.class) { return box(longUnbox(object)); } else if (type == float.class) { return box(floatUnbox(object)); } else if (type == double.class) { Double answer = new Double(doubleUnbox(object)); //throw a runtime exception if conversion would be out-of-range for the type. if (!(object instanceof Double) && (answer.doubleValue() == Double.NEGATIVE_INFINITY || answer.doubleValue() == Double.POSITIVE_INFINITY)) { throw new GroovyRuntimeException("Automatic coercion of " + aClass.getName() + " value " + object + " to double failed. Value is out of range."); } return answer; } } else if (object instanceof String && type.isEnum()) { return Enum.valueOf(type, (String) object); } else if (object instanceof GString && type.isEnum()) { return Enum.valueOf(type, object.toString()); } Object[] args = null; if (object instanceof Collection) { // let's try invoke the constructor with the list as arguments // such as for creating a Dimension, Point, Color etc. Collection collection = (Collection) object; args = collection.toArray(); } else if (object instanceof Object[]) { args = (Object[]) object; } else if (object instanceof Map) { // emulate named params constructor args = new Object[1]; args[0] = object; } Exception nested = null; if (args != null) { try { return InvokerHelper.invokeConstructorOf(type, args); } catch (InvokerInvocationException iie){ throw iie; } catch (GroovyRuntimeException e) { if(e.getMessage().contains("Could not find matching constructor for")) { try { return InvokerHelper.invokeConstructorOf(type, object); } catch (InvokerInvocationException iie){ throw iie; } catch (Exception ex) { // let's ignore exception and return the original object // as the caller has more context to be able to throw a more // meaningful exception (but stash to get message later) nested = e; } } else { nested = e; } } catch (Exception e) { // let's ignore exception and return the original object // as the caller has more context to be able to throw a more // meaningful exception (but stash to get message later) nested = e; } } GroovyCastException gce; if (nested != null) { gce = new GroovyCastException(object, type, nested); } else { gce = new GroovyCastException(object, type); } throw gce; } private static Class castToClass(Object object) { try { return Class.forName(object.toString()); } catch (Exception e) { throw new GroovyCastException(object, Class.class, e); } } public static Object asArray(Object object, Class type) { if (type.isAssignableFrom(object.getClass())) { return object; } Collection list = asCollection(object); int size = list.size(); Class elementType = type.getComponentType(); Object array = Array.newInstance(elementType, size); int idx = 0; if (boolean.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setBoolean(array, idx, booleanUnbox(element)); } } else if (byte.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setByte(array, idx, byteUnbox(element)); } } else if (char.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setChar(array, idx, charUnbox(element)); } } else if (double.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setDouble(array, idx, doubleUnbox(element)); } } else if (float.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setFloat(array, idx, floatUnbox(element)); } } else if (int.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setInt(array, idx, intUnbox(element)); } } else if (long.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setLong(array, idx, longUnbox(element)); } } else if (short.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setShort(array, idx, shortUnbox(element)); } } else { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Object coercedElement = castToType(element, elementType); Array.set(array, idx, coercedElement); } } return array; } public static Collection asCollection(T[] value) { return arrayAsCollection(value); } public static Collection asCollection(Object value) { if (value == null) { return Collections.EMPTY_LIST; } else if (value instanceof Collection) { return (Collection) value; } else if (value instanceof Map) { Map map = (Map) value; return map.entrySet(); } else if (value.getClass().isArray()) { return arrayAsCollection(value); } else if (value instanceof MethodClosure) { MethodClosure method = (MethodClosure) value; IteratorClosureAdapter adapter = new IteratorClosureAdapter(method.getDelegate()); method.call(adapter); return adapter.asList(); } else if (value instanceof String) { return DefaultGroovyMethods.toList((String) value); } else if (value instanceof GString) { return DefaultGroovyMethods.toList(value.toString()); } else if (value instanceof File) { try { return DefaultGroovyMethods.readLines((File) value); } catch (IOException e) { throw new GroovyRuntimeException("Error reading file: " + value, e); } } else if (isEnumSubclass(value)) { Object[] values = (Object[])InvokerHelper.invokeMethod(value, "values", new Object[0]); return Arrays.asList(values); } else { // let's assume it's a collection of 1 return Collections.singletonList(value); } } public static Collection arrayAsCollection(Object value) { if (value.getClass().getComponentType().isPrimitive()) { return primitiveArrayToList(value); } return arrayAsCollection((Object[]) value); } public static Collection arrayAsCollection(T[] value) { return Arrays.asList((T[]) value); } /** * Determines whether the value object is a Class object representing a * subclass of java.lang.Enum. Uses class name check to avoid breaking on * pre-Java 5 JREs. * * @param value an object * @return true if the object is an Enum */ public static boolean isEnumSubclass(Object value) { if (value instanceof Class) { Class superclass = ((Class)value).getSuperclass(); while (superclass != null) { if (superclass.getName().equals("java.lang.Enum")) { return true; } superclass = superclass.getSuperclass(); } } return false; } /** * Allows conversion of arrays into a mutable List * * @param array an array * @return the array as a List */ public static List primitiveArrayToList(Object array) { int size = Array.getLength(array); List list = new ArrayList(size); for (int i = 0; i < size; i++) { Object item = Array.get(array, i); if (item != null && item.getClass().isArray() && item.getClass().getComponentType().isPrimitive()) { item = primitiveArrayToList(item); } list.add(item); } return list; } public static Object[] primitiveArrayBox(Object array) { int size = Array.getLength(array); Object[] ret = (Object[]) Array.newInstance(ReflectionCache.autoboxType(array.getClass().getComponentType()), size); for (int i = 0; i < size; i++) { ret[i]=Array.get(array, i); } return ret; } /** * Compares the two objects handling nulls gracefully and performing numeric type coercion if required */ public static int compareTo(Object left, Object right) { return compareToWithEqualityCheck(left, right, false); } private static int compareToWithEqualityCheck(Object left, Object right, boolean equalityCheckOnly) { if (left == right) { return 0; } if (left == null) { return -1; } else if (right == null) { return 1; } if (left instanceof Comparable) { if (left instanceof Number) { if (isValidCharacterString(right)) { return DefaultGroovyMethods.compareTo((Number) left, (Character) box(castToChar(right))); } if (right instanceof Character || right instanceof Number) { return DefaultGroovyMethods.compareTo((Number) left, castToNumber(right)); } } else if (left instanceof Character) { if (isValidCharacterString(right)) { return DefaultGroovyMethods.compareTo((Character)left,(Character)box(castToChar(right))); } if (right instanceof Number) { return DefaultGroovyMethods.compareTo((Character)left,(Number)right); } } else if (right instanceof Number) { if (isValidCharacterString(left)) { return DefaultGroovyMethods.compareTo((Character)box(castToChar(left)),(Number) right); } } else if (left instanceof String && right instanceof Character) { return ((String) left).compareTo(right.toString()); } else if (left instanceof String && right instanceof GString) { return ((String) left).compareTo(right.toString()); } if (!equalityCheckOnly || left.getClass().isAssignableFrom(right.getClass()) || (right.getClass() != Object.class && right.getClass().isAssignableFrom(left.getClass())) //GROOVY-4046 || (left instanceof GString && right instanceof String)) { Comparable comparable = (Comparable) left; return comparable.compareTo(right); } } if (equalityCheckOnly) { return -1; // anything other than 0 } throw new GroovyRuntimeException("Cannot compare " + left.getClass().getName() + " with value '" + left + "' and " + right.getClass().getName() + " with value '" + right + "'"); } public static boolean compareEqual(Object left, Object right) { if (left == right) return true; if (left == null || right == null) return false; if (left instanceof Comparable) { return compareToWithEqualityCheck(left, right, true) == 0; } // handle arrays on both sides as special case for efficiency Class leftClass = left.getClass(); Class rightClass = right.getClass(); if (leftClass.isArray() && rightClass.isArray()) { return compareArrayEqual(left, right); } if (leftClass.isArray() && leftClass.getComponentType().isPrimitive()) { left = primitiveArrayToList(left); } if (rightClass.isArray() && rightClass.getComponentType().isPrimitive()) { right = primitiveArrayToList(right); } if (left instanceof Object[] && right instanceof List) { return DefaultGroovyMethods.equals((Object[]) left, (List) right); } if (left instanceof List && right instanceof Object[]) { return DefaultGroovyMethods.equals((List) left, (Object[]) right); } if (left instanceof List && right instanceof List) { return DefaultGroovyMethods.equals((List) left, (List) right); } if (left instanceof Map.Entry && right instanceof Map.Entry) { Object k1 = ((Map.Entry)left).getKey(); Object k2 = ((Map.Entry)right).getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = ((Map.Entry)left).getValue(); Object v2 = ((Map.Entry)right).getValue(); if (v1 == v2 || (v1 != null && DefaultTypeTransformation.compareEqual(v1, v2))) return true; } return false; } return ((Boolean) InvokerHelper.invokeMethod(left, "equals", right)).booleanValue(); } public static boolean compareArrayEqual(Object left, Object right) { if (left == null) { return right == null; } if (right == null) { return false; } if (Array.getLength(left) != Array.getLength(right)) { return false; } for (int i = 0; i < Array.getLength(left); i++) { Object l = Array.get(left, i); Object r = Array.get(right, i); if (!compareEqual(l, r)) return false; } return true; } /** * @return true if the given value is a valid character string (i.e. has length of 1) */ private static boolean isValidCharacterString(Object value) { if (value instanceof String) { String s = (String) value; if (s.length() == 1) { return true; } } return false; } public static int[] convertToIntArray(Object a) { int[] ans = null; // conservative coding if (a.getClass().getName().equals("[I")) { ans = (int[]) a; } else { Object[] ia = (Object[]) a; ans = new int[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) { continue; } ans[i] = ((Number) ia[i]).intValue(); } } return ans; } public static boolean[] convertToBooleanArray(Object a) { boolean[] ans = null; // conservative coding if (a instanceof boolean[]) { ans = (boolean[]) a; } else { Object[] ia = (Object[]) a; ans = new boolean[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) continue; ans[i] = ((Boolean) ia[i]).booleanValue(); } } return ans; } public static byte[] convertToByteArray(Object a) { byte[] ans = null; // conservative coding if (a instanceof byte[]) { ans = (byte[]) a; } else { Object[] ia = (Object[]) a; ans = new byte[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] != null) { ans[i] = ((Number) ia[i]).byteValue(); } } } return ans; } public static short[] convertToShortArray(Object a) { short[] ans = null; // conservative coding if (a instanceof short[]) { ans = (short[]) a; } else { Object[] ia = (Object[]) a; ans = new short[ia.length]; for (int i = 0; i < ia.length; i++) { ans[i] = ((Number) ia[i]).shortValue(); } } return ans; } public static char[] convertToCharArray(Object a) { char[] ans = null; // conservative coding if (a instanceof char[]) { ans = (char[]) a; } else { Object[] ia = (Object[]) a; ans = new char[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) { continue; } ans[i] = ((Character) ia[i]).charValue(); } } return ans; } public static long[] convertToLongArray(Object a) { long[] ans = null; // conservative coding if (a instanceof long[]) { ans = (long[]) a; } else { Object[] ia = (Object[]) a; ans = new long[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) { continue; } ans[i] = ((Number) ia[i]).longValue(); } } return ans; } public static float[] convertToFloatArray(Object a) { float[] ans = null; // conservative coding if (a instanceof float[]) { ans = (float[]) a; } else { Object[] ia = (Object[]) a; ans = new float[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) { continue; } ans[i] = ((Number) ia[i]).floatValue(); } } return ans; } public static double[] convertToDoubleArray(Object a) { double[] ans = null; // conservative coding if (a instanceof double[]) { ans = (double[]) a; } else { Object[] ia = (Object[]) a; ans = new double[ia.length]; for (int i = 0; i < ia.length; i++) { if (ia[i] == null) { continue; } ans[i] = ((Number) ia[i]).doubleValue(); } } return ans; } public static Object convertToPrimitiveArray(Object a, Class type) { if (type == Byte.TYPE) { return convertToByteArray(a); } if (type == Boolean.TYPE) { return convertToBooleanArray(a); } if (type == Short.TYPE) { return convertToShortArray(a); } if (type == Character.TYPE) { return convertToCharArray(a); } if (type == Integer.TYPE) { return convertToIntArray(a); } if (type == Long.TYPE) { return convertToLongArray(a); } if (type == Float.TYPE) { return convertToFloatArray(a); } if (type == Double.TYPE) { return convertToDoubleArray(a); } else { return a; } } public static Character getCharFromSizeOneString(Object value) { if (value instanceof GString) value = value.toString(); if (value instanceof String) { String s = (String) value; if (s.length() != 1) throw new IllegalArgumentException("String of length 1 expected but got a bigger one"); return new Character(s.charAt(0)); } else { return ((Character) value); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/package.html0000644001501200150120000000041711707612046026453 0ustar miguelmiguel package org.codehaus.groovy.runtime.typehandling*

      Classes used to execute special actions based on the type. This includes mathematical operations and wrapper classes.

      groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/IntegerMath.java0000644001501200150120000000603211627206700027240 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; /** * Integer NumberMath operations * * @author Steve Goetze */ public final class IntegerMath extends NumberMath { public static final IntegerMath INSTANCE = new IntegerMath(); private IntegerMath() {} protected Number absImpl(Number number) { return Integer.valueOf(Math.abs(number.intValue())); } public Number addImpl(Number left, Number right) { return Integer.valueOf(left.intValue() + right.intValue()); } public Number subtractImpl(Number left, Number right) { return Integer.valueOf(left.intValue() - right.intValue()); } public Number multiplyImpl(Number left, Number right) { return Integer.valueOf(left.intValue() * right.intValue()); } public Number divideImpl(Number left, Number right) { return BigDecimalMath.INSTANCE.divideImpl(left, right); } public int compareToImpl(Number left, Number right) { int leftVal = left.intValue(); int rightVal = right.intValue(); return (leftVal> right.intValue()); } protected Number rightShiftUnsignedImpl(Number left, Number right) { return Integer.valueOf(left.intValue() >>> right.intValue()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/NumberMathModificationInfo.java0000644001501200150120000033136111627206700032243 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod; import java.util.Collections; import java.util.HashSet; public class NumberMathModificationInfo { public static final NumberMathModificationInfo instance = new NumberMathModificationInfo(); private final HashSet names = new HashSet(); private NumberMathModificationInfo() { Collections.addAll(names, "plus", "minus", "multiply", "div", "compareTo", "or", "and", "xor", "intdiv", "mod", "leftShift", "rightShift", "rightShiftUnsigned"); } public void checkIfStdMethod(MetaMethod method) { if (method.getClass() != NewInstanceMetaMethod.class) { String name = method.getName(); if (method.getParameterTypes().length != 1) return; if (!method.getParameterTypes()[0].isNumber && method.getParameterTypes()[0].getTheClass() != Object.class) return; if (!names.contains(name)) return; checkNumberOps(name, method.getDeclaringClass().getTheClass()); } } private void checkNumberOps(String name, Class klazz) { if ("plus".equals(name)) { if (klazz == Byte.class) { byte_plus = true; } if (klazz == Short.class) { short_plus = true; } if (klazz == Integer.class) { int_plus = true; } if (klazz == Long.class) { long_plus = true; } if (klazz == Float.class) { float_plus = true; } if (klazz == Double.class) { double_plus = true; } if (klazz == Object.class) { byte_plus = true; short_plus = true; int_plus = true; long_plus = true; float_plus = true; double_plus = true; } } if ("minus".equals(name)) { if (klazz == Byte.class) { byte_minus = true; } if (klazz == Short.class) { short_minus = true; } if (klazz == Integer.class) { int_minus = true; } if (klazz == Long.class) { long_minus = true; } if (klazz == Float.class) { float_minus = true; } if (klazz == Double.class) { double_minus = true; } if (klazz == Object.class) { byte_minus = true; short_minus = true; int_minus = true; long_minus = true; float_minus = true; double_minus = true; } } if ("multiply".equals(name)) { if (klazz == Byte.class) { byte_multiply = true; } if (klazz == Short.class) { short_multiply = true; } if (klazz == Integer.class) { int_multiply = true; } if (klazz == Long.class) { long_multiply = true; } if (klazz == Float.class) { float_multiply = true; } if (klazz == Double.class) { double_multiply = true; } if (klazz == Object.class) { byte_multiply = true; short_multiply = true; int_multiply = true; long_multiply = true; float_multiply = true; double_multiply = true; } } if ("div".equals(name)) { if (klazz == Byte.class) { byte_div = true; } if (klazz == Short.class) { short_div = true; } if (klazz == Integer.class) { int_div = true; } if (klazz == Long.class) { long_div = true; } if (klazz == Float.class) { float_div = true; } if (klazz == Double.class) { double_div = true; } if (klazz == Object.class) { byte_div = true; short_div = true; int_div = true; long_div = true; float_div = true; double_div = true; } } if ("or".equals(name)) { if (klazz == Byte.class) { byte_or = true; } if (klazz == Short.class) { short_or = true; } if (klazz == Integer.class) { int_or = true; } if (klazz == Long.class) { long_or = true; } if (klazz == Float.class) { float_or = true; } if (klazz == Double.class) { double_or = true; } if (klazz == Object.class) { byte_or = true; short_or = true; int_or = true; long_or = true; float_or = true; double_or = true; } } if ("and".equals(name)) { if (klazz == Byte.class) { byte_and = true; } if (klazz == Short.class) { short_and = true; } if (klazz == Integer.class) { int_and = true; } if (klazz == Long.class) { long_and = true; } if (klazz == Float.class) { float_and = true; } if (klazz == Double.class) { double_and = true; } if (klazz == Object.class) { byte_and = true; short_and = true; int_and = true; long_and = true; float_and = true; double_and = true; } } if ("xor".equals(name)) { if (klazz == Byte.class) { byte_xor = true; } if (klazz == Short.class) { short_xor = true; } if (klazz == Integer.class) { int_xor = true; } if (klazz == Long.class) { long_xor = true; } if (klazz == Float.class) { float_xor = true; } if (klazz == Double.class) { double_xor = true; } if (klazz == Object.class) { byte_xor = true; short_xor = true; int_xor = true; long_xor = true; float_xor = true; double_xor = true; } } if ("intdiv".equals(name)) { if (klazz == Byte.class) { byte_intdiv = true; } if (klazz == Short.class) { short_intdiv = true; } if (klazz == Integer.class) { int_intdiv = true; } if (klazz == Long.class) { long_intdiv = true; } if (klazz == Float.class) { float_intdiv = true; } if (klazz == Double.class) { double_intdiv = true; } if (klazz == Object.class) { byte_intdiv = true; short_intdiv = true; int_intdiv = true; long_intdiv = true; float_intdiv = true; double_intdiv = true; } } if ("mod".equals(name)) { if (klazz == Byte.class) { byte_mod = true; } if (klazz == Short.class) { short_mod = true; } if (klazz == Integer.class) { int_mod = true; } if (klazz == Long.class) { long_mod = true; } if (klazz == Float.class) { float_mod = true; } if (klazz == Double.class) { double_mod = true; } if (klazz == Object.class) { byte_mod = true; short_mod = true; int_mod = true; long_mod = true; float_mod = true; double_mod = true; } } if ("leftShift".equals(name)) { if (klazz == Byte.class) { byte_leftShift = true; } if (klazz == Short.class) { short_leftShift = true; } if (klazz == Integer.class) { int_leftShift = true; } if (klazz == Long.class) { long_leftShift = true; } if (klazz == Float.class) { float_leftShift = true; } if (klazz == Double.class) { double_leftShift = true; } if (klazz == Object.class) { byte_leftShift = true; short_leftShift = true; int_leftShift = true; long_leftShift = true; float_leftShift = true; double_leftShift = true; } } if ("rightShift".equals(name)) { if (klazz == Byte.class) { byte_rightShift = true; } if (klazz == Short.class) { short_rightShift = true; } if (klazz == Integer.class) { int_rightShift = true; } if (klazz == Long.class) { long_rightShift = true; } if (klazz == Float.class) { float_rightShift = true; } if (klazz == Double.class) { double_rightShift = true; } if (klazz == Object.class) { byte_rightShift = true; short_rightShift = true; int_rightShift = true; long_rightShift = true; float_rightShift = true; double_rightShift = true; } } if ("rightShiftUnsigned".equals(name)) { if (klazz == Byte.class) { byte_rightShiftUnsigned = true; } if (klazz == Short.class) { short_rightShiftUnsigned = true; } if (klazz == Integer.class) { int_rightShiftUnsigned = true; } if (klazz == Long.class) { long_rightShiftUnsigned = true; } if (klazz == Float.class) { float_rightShiftUnsigned = true; } if (klazz == Double.class) { double_rightShiftUnsigned = true; } if (klazz == Object.class) { byte_rightShiftUnsigned = true; short_rightShiftUnsigned = true; int_rightShiftUnsigned = true; long_rightShiftUnsigned = true; float_rightShiftUnsigned = true; double_rightShiftUnsigned = true; } } } public boolean byte_plus; public boolean short_plus; public boolean int_plus; public boolean long_plus; public boolean float_plus; public boolean double_plus; public boolean byte_minus; public boolean short_minus; public boolean int_minus; public boolean long_minus; public boolean float_minus; public boolean double_minus; public boolean byte_multiply; public boolean short_multiply; public boolean int_multiply; public boolean long_multiply; public boolean float_multiply; public boolean double_multiply; public boolean byte_div; public boolean short_div; public boolean int_div; public boolean long_div; public boolean float_div; public boolean double_div; public boolean byte_or; public boolean short_or; public boolean int_or; public boolean long_or; public boolean float_or; public boolean double_or; public boolean byte_and; public boolean short_and; public boolean int_and; public boolean long_and; public boolean float_and; public boolean double_and; public boolean byte_xor; public boolean short_xor; public boolean int_xor; public boolean long_xor; public boolean float_xor; public boolean double_xor; public boolean byte_intdiv; public boolean short_intdiv; public boolean int_intdiv; public boolean long_intdiv; public boolean float_intdiv; public boolean double_intdiv; public boolean byte_mod; public boolean short_mod; public boolean int_mod; public boolean long_mod; public boolean float_mod; public boolean double_mod; public boolean byte_leftShift; public boolean short_leftShift; public boolean int_leftShift; public boolean long_leftShift; public boolean float_leftShift; public boolean double_leftShift; public boolean byte_rightShift; public boolean short_rightShift; public boolean int_rightShift; public boolean long_rightShift; public boolean float_rightShift; public boolean double_rightShift; public boolean byte_rightShiftUnsigned; public boolean short_rightShiftUnsigned; public boolean int_rightShiftUnsigned; public boolean long_rightShiftUnsigned; public boolean float_rightShiftUnsigned; public boolean double_rightShiftUnsigned; public static int plus(byte op1, byte op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + ((int) op2); } } private static int plusSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(byte op1, short op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + ((int) op2); } } private static int plusSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(byte op1, int op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + op2; } } private static int plusSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static long plus(byte op1, long op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((long) op1) + op2; } } private static long plusSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static double plus(byte op1, float op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(byte op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(byte op1, double op2) { if (instance.byte_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + op2; } } private static double plusSlow(byte op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static int plus(short op1, byte op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + ((int) op2); } } private static int plusSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(short op1, short op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + ((int) op2); } } private static int plusSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(short op1, int op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((int) op1) + op2; } } private static int plusSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static long plus(short op1, long op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((long) op1) + op2; } } private static long plusSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static double plus(short op1, float op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(short op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(short op1, double op2) { if (instance.short_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + op2; } } private static double plusSlow(short op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static int plus(int op1, byte op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return op1 + ((int) op2); } } private static int plusSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(int op1, short op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return op1 + ((int) op2); } } private static int plusSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static int plus(int op1, int op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return op1 + op2; } } private static int plusSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue(); } public static long plus(int op1, long op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return ((long) op1) + op2; } } private static long plusSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static double plus(int op1, float op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(int op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(int op1, double op2) { if (instance.int_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + op2; } } private static double plusSlow(int op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static long plus(long op1, byte op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return op1 + ((long) op2); } } private static long plusSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static long plus(long op1, short op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return op1 + ((long) op2); } } private static long plusSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static long plus(long op1, int op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return op1 + ((long) op2); } } private static long plusSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static long plus(long op1, long op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return op1 + op2; } } private static long plusSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).longValue(); } public static double plus(long op1, float op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(long op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(long op1, double op2) { if (instance.long_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + op2; } } private static double plusSlow(long op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, byte op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(float op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, short op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(float op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, int op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(float op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, long op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(float op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, float op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + ((double) op2); } } private static double plusSlow(float op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(float op1, double op2) { if (instance.float_plus) { return plusSlow(op1, op2); } else { return ((double) op1) + op2; } } private static double plusSlow(float op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, byte op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + ((double) op2); } } private static double plusSlow(double op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, short op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + ((double) op2); } } private static double plusSlow(double op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, int op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + ((double) op2); } } private static double plusSlow(double op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, long op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + ((double) op2); } } private static double plusSlow(double op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, float op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + ((double) op2); } } private static double plusSlow(double op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static double plus(double op1, double op2) { if (instance.double_plus) { return plusSlow(op1, op2); } else { return op1 + op2; } } private static double plusSlow(double op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue(); } public static int minus(byte op1, byte op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - ((int) op2); } } private static int minusSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(byte op1, short op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - ((int) op2); } } private static int minusSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(byte op1, int op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - op2; } } private static int minusSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static long minus(byte op1, long op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((long) op1) - op2; } } private static long minusSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static double minus(byte op1, float op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(byte op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(byte op1, double op2) { if (instance.byte_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - op2; } } private static double minusSlow(byte op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static int minus(short op1, byte op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - ((int) op2); } } private static int minusSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(short op1, short op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - ((int) op2); } } private static int minusSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(short op1, int op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((int) op1) - op2; } } private static int minusSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static long minus(short op1, long op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((long) op1) - op2; } } private static long minusSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static double minus(short op1, float op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(short op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(short op1, double op2) { if (instance.short_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - op2; } } private static double minusSlow(short op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static int minus(int op1, byte op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return op1 - ((int) op2); } } private static int minusSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(int op1, short op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return op1 - ((int) op2); } } private static int minusSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static int minus(int op1, int op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return op1 - op2; } } private static int minusSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue(); } public static long minus(int op1, long op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return ((long) op1) - op2; } } private static long minusSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static double minus(int op1, float op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(int op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(int op1, double op2) { if (instance.int_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - op2; } } private static double minusSlow(int op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static long minus(long op1, byte op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return op1 - ((long) op2); } } private static long minusSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static long minus(long op1, short op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return op1 - ((long) op2); } } private static long minusSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static long minus(long op1, int op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return op1 - ((long) op2); } } private static long minusSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static long minus(long op1, long op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return op1 - op2; } } private static long minusSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue(); } public static double minus(long op1, float op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(long op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(long op1, double op2) { if (instance.long_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - op2; } } private static double minusSlow(long op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, byte op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(float op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, short op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(float op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, int op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(float op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, long op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(float op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, float op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - ((double) op2); } } private static double minusSlow(float op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(float op1, double op2) { if (instance.float_minus) { return minusSlow(op1, op2); } else { return ((double) op1) - op2; } } private static double minusSlow(float op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, byte op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - ((double) op2); } } private static double minusSlow(double op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, short op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - ((double) op2); } } private static double minusSlow(double op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, int op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - ((double) op2); } } private static double minusSlow(double op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, long op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - ((double) op2); } } private static double minusSlow(double op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, float op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - ((double) op2); } } private static double minusSlow(double op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static double minus(double op1, double op2) { if (instance.double_minus) { return minusSlow(op1, op2); } else { return op1 - op2; } } private static double minusSlow(double op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue(); } public static int multiply(byte op1, byte op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * ((int) op2); } } private static int multiplySlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(byte op1, short op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * ((int) op2); } } private static int multiplySlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(byte op1, int op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * op2; } } private static int multiplySlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static long multiply(byte op1, long op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((long) op1) * op2; } } private static long multiplySlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static double multiply(byte op1, float op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(byte op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(byte op1, double op2) { if (instance.byte_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * op2; } } private static double multiplySlow(byte op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static int multiply(short op1, byte op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * ((int) op2); } } private static int multiplySlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(short op1, short op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * ((int) op2); } } private static int multiplySlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(short op1, int op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((int) op1) * op2; } } private static int multiplySlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static long multiply(short op1, long op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((long) op1) * op2; } } private static long multiplySlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static double multiply(short op1, float op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(short op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(short op1, double op2) { if (instance.short_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * op2; } } private static double multiplySlow(short op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static int multiply(int op1, byte op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((int) op2); } } private static int multiplySlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(int op1, short op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((int) op2); } } private static int multiplySlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static int multiply(int op1, int op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return op1 * op2; } } private static int multiplySlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue(); } public static long multiply(int op1, long op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return ((long) op1) * op2; } } private static long multiplySlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static double multiply(int op1, float op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(int op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(int op1, double op2) { if (instance.int_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * op2; } } private static double multiplySlow(int op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static long multiply(long op1, byte op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((long) op2); } } private static long multiplySlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static long multiply(long op1, short op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((long) op2); } } private static long multiplySlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static long multiply(long op1, int op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((long) op2); } } private static long multiplySlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static long multiply(long op1, long op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return op1 * op2; } } private static long multiplySlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).longValue(); } public static double multiply(long op1, float op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(long op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(long op1, double op2) { if (instance.long_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * op2; } } private static double multiplySlow(long op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, byte op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(float op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, short op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(float op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, int op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(float op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, long op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(float op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, float op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * ((double) op2); } } private static double multiplySlow(float op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(float op1, double op2) { if (instance.float_multiply) { return multiplySlow(op1, op2); } else { return ((double) op1) * op2; } } private static double multiplySlow(float op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, byte op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((double) op2); } } private static double multiplySlow(double op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, short op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((double) op2); } } private static double multiplySlow(double op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, int op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((double) op2); } } private static double multiplySlow(double op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, long op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((double) op2); } } private static double multiplySlow(double op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, float op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * ((double) op2); } } private static double multiplySlow(double op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static double multiply(double op1, double op2) { if (instance.double_multiply) { return multiplySlow(op1, op2); } else { return op1 * op2; } } private static double multiplySlow(double op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue(); } public static int div(byte op1, byte op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int divSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(byte op1, short op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int divSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(byte op1, int op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((int) op1) / op2; } } private static int divSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static long div(byte op1, long op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long divSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static double div(byte op1, float op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(byte op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(byte op1, double op2) { if (instance.byte_div) { return divSlow(op1, op2); } else { return ((double) op1) / op2; } } private static double divSlow(byte op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static int div(short op1, byte op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int divSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(short op1, short op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int divSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(short op1, int op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((int) op1) / op2; } } private static int divSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static long div(short op1, long op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long divSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static double div(short op1, float op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(short op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(short op1, double op2) { if (instance.short_div) { return divSlow(op1, op2); } else { return ((double) op1) / op2; } } private static double divSlow(short op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static int div(int op1, byte op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return op1 / ((int) op2); } } private static int divSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(int op1, short op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return op1 / ((int) op2); } } private static int divSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static int div(int op1, int op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return op1 / op2; } } private static int divSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue(); } public static long div(int op1, long op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long divSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static double div(int op1, float op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(int op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(int op1, double op2) { if (instance.int_div) { return divSlow(op1, op2); } else { return ((double) op1) / op2; } } private static double divSlow(int op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static long div(long op1, byte op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long divSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static long div(long op1, short op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long divSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static long div(long op1, int op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long divSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static long div(long op1, long op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return op1 / op2; } } private static long divSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).longValue(); } public static double div(long op1, float op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(long op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(long op1, double op2) { if (instance.long_div) { return divSlow(op1, op2); } else { return ((double) op1) / op2; } } private static double divSlow(long op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, byte op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(float op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, short op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(float op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, int op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(float op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, long op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(float op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, float op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / ((double) op2); } } private static double divSlow(float op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(float op1, double op2) { if (instance.float_div) { return divSlow(op1, op2); } else { return ((double) op1) / op2; } } private static double divSlow(float op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, byte op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / ((double) op2); } } private static double divSlow(double op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, short op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / ((double) op2); } } private static double divSlow(double op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, int op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / ((double) op2); } } private static double divSlow(double op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, long op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / ((double) op2); } } private static double divSlow(double op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, float op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / ((double) op2); } } private static double divSlow(double op1, float op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static double div(double op1, double op2) { if (instance.double_div) { return divSlow(op1, op2); } else { return op1 / op2; } } private static double divSlow(double op1, double op2) { return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue(); } public static int or(byte op1, byte op2) { if (instance.byte_or) { return orSlow(op1, op2); } else { return ((int) op1) | ((int) op2); } } private static int orSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(byte op1, short op2) { if (instance.byte_or) { return orSlow(op1, op2); } else { return ((int) op1) | ((int) op2); } } private static int orSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(byte op1, int op2) { if (instance.byte_or) { return orSlow(op1, op2); } else { return ((int) op1) | op2; } } private static int orSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static long or(byte op1, long op2) { if (instance.byte_or) { return orSlow(op1, op2); } else { return ((long) op1) | op2; } } private static long orSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static int or(short op1, byte op2) { if (instance.short_or) { return orSlow(op1, op2); } else { return ((int) op1) | ((int) op2); } } private static int orSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(short op1, short op2) { if (instance.short_or) { return orSlow(op1, op2); } else { return ((int) op1) | ((int) op2); } } private static int orSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(short op1, int op2) { if (instance.short_or) { return orSlow(op1, op2); } else { return ((int) op1) | op2; } } private static int orSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static long or(short op1, long op2) { if (instance.short_or) { return orSlow(op1, op2); } else { return ((long) op1) | op2; } } private static long orSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static int or(int op1, byte op2) { if (instance.int_or) { return orSlow(op1, op2); } else { return op1 | ((int) op2); } } private static int orSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(int op1, short op2) { if (instance.int_or) { return orSlow(op1, op2); } else { return op1 | ((int) op2); } } private static int orSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static int or(int op1, int op2) { if (instance.int_or) { return orSlow(op1, op2); } else { return op1 | op2; } } private static int orSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue(); } public static long or(int op1, long op2) { if (instance.int_or) { return orSlow(op1, op2); } else { return ((long) op1) | op2; } } private static long orSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static long or(long op1, byte op2) { if (instance.long_or) { return orSlow(op1, op2); } else { return op1 | ((long) op2); } } private static long orSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static long or(long op1, short op2) { if (instance.long_or) { return orSlow(op1, op2); } else { return op1 | ((long) op2); } } private static long orSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static long or(long op1, int op2) { if (instance.long_or) { return orSlow(op1, op2); } else { return op1 | ((long) op2); } } private static long orSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static long or(long op1, long op2) { if (instance.long_or) { return orSlow(op1, op2); } else { return op1 | op2; } } private static long orSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue(); } public static int and(byte op1, byte op2) { if (instance.byte_and) { return andSlow(op1, op2); } else { return ((int) op1) & ((int) op2); } } private static int andSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(byte op1, short op2) { if (instance.byte_and) { return andSlow(op1, op2); } else { return ((int) op1) & ((int) op2); } } private static int andSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(byte op1, int op2) { if (instance.byte_and) { return andSlow(op1, op2); } else { return ((int) op1) & op2; } } private static int andSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static long and(byte op1, long op2) { if (instance.byte_and) { return andSlow(op1, op2); } else { return ((long) op1) & op2; } } private static long andSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static int and(short op1, byte op2) { if (instance.short_and) { return andSlow(op1, op2); } else { return ((int) op1) & ((int) op2); } } private static int andSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(short op1, short op2) { if (instance.short_and) { return andSlow(op1, op2); } else { return ((int) op1) & ((int) op2); } } private static int andSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(short op1, int op2) { if (instance.short_and) { return andSlow(op1, op2); } else { return ((int) op1) & op2; } } private static int andSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static long and(short op1, long op2) { if (instance.short_and) { return andSlow(op1, op2); } else { return ((long) op1) & op2; } } private static long andSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static int and(int op1, byte op2) { if (instance.int_and) { return andSlow(op1, op2); } else { return op1 & ((int) op2); } } private static int andSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(int op1, short op2) { if (instance.int_and) { return andSlow(op1, op2); } else { return op1 & ((int) op2); } } private static int andSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static int and(int op1, int op2) { if (instance.int_and) { return andSlow(op1, op2); } else { return op1 & op2; } } private static int andSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).intValue(); } public static long and(int op1, long op2) { if (instance.int_and) { return andSlow(op1, op2); } else { return ((long) op1) & op2; } } private static long andSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static long and(long op1, byte op2) { if (instance.long_and) { return andSlow(op1, op2); } else { return op1 & ((long) op2); } } private static long andSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static long and(long op1, short op2) { if (instance.long_and) { return andSlow(op1, op2); } else { return op1 & ((long) op2); } } private static long andSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static long and(long op1, int op2) { if (instance.long_and) { return andSlow(op1, op2); } else { return op1 & ((long) op2); } } private static long andSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static long and(long op1, long op2) { if (instance.long_and) { return andSlow(op1, op2); } else { return op1 & op2; } } private static long andSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "and", op2)).longValue(); } public static int xor(byte op1, byte op2) { if (instance.byte_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ ((int) op2); } } private static int xorSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(byte op1, short op2) { if (instance.byte_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ ((int) op2); } } private static int xorSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(byte op1, int op2) { if (instance.byte_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ op2; } } private static int xorSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static long xor(byte op1, long op2) { if (instance.byte_xor) { return xorSlow(op1, op2); } else { return ((long) op1) ^ op2; } } private static long xorSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static int xor(short op1, byte op2) { if (instance.short_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ ((int) op2); } } private static int xorSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(short op1, short op2) { if (instance.short_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ ((int) op2); } } private static int xorSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(short op1, int op2) { if (instance.short_xor) { return xorSlow(op1, op2); } else { return ((int) op1) ^ op2; } } private static int xorSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static long xor(short op1, long op2) { if (instance.short_xor) { return xorSlow(op1, op2); } else { return ((long) op1) ^ op2; } } private static long xorSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static int xor(int op1, byte op2) { if (instance.int_xor) { return xorSlow(op1, op2); } else { return op1 ^ ((int) op2); } } private static int xorSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(int op1, short op2) { if (instance.int_xor) { return xorSlow(op1, op2); } else { return op1 ^ ((int) op2); } } private static int xorSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static int xor(int op1, int op2) { if (instance.int_xor) { return xorSlow(op1, op2); } else { return op1 ^ op2; } } private static int xorSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue(); } public static long xor(int op1, long op2) { if (instance.int_xor) { return xorSlow(op1, op2); } else { return ((long) op1) ^ op2; } } private static long xorSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static long xor(long op1, byte op2) { if (instance.long_xor) { return xorSlow(op1, op2); } else { return op1 ^ ((long) op2); } } private static long xorSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static long xor(long op1, short op2) { if (instance.long_xor) { return xorSlow(op1, op2); } else { return op1 ^ ((long) op2); } } private static long xorSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static long xor(long op1, int op2) { if (instance.long_xor) { return xorSlow(op1, op2); } else { return op1 ^ ((long) op2); } } private static long xorSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static long xor(long op1, long op2) { if (instance.long_xor) { return xorSlow(op1, op2); } else { return op1 ^ op2; } } private static long xorSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).longValue(); } public static int intdiv(byte op1, byte op2) { if (instance.byte_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int intdivSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(byte op1, short op2) { if (instance.byte_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int intdivSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(byte op1, int op2) { if (instance.byte_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / op2; } } private static int intdivSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static long intdiv(byte op1, long op2) { if (instance.byte_intdiv) { return intdivSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long intdivSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static int intdiv(short op1, byte op2) { if (instance.short_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int intdivSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(short op1, short op2) { if (instance.short_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / ((int) op2); } } private static int intdivSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(short op1, int op2) { if (instance.short_intdiv) { return intdivSlow(op1, op2); } else { return ((int) op1) / op2; } } private static int intdivSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static long intdiv(short op1, long op2) { if (instance.short_intdiv) { return intdivSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long intdivSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static int intdiv(int op1, byte op2) { if (instance.int_intdiv) { return intdivSlow(op1, op2); } else { return op1 / ((int) op2); } } private static int intdivSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(int op1, short op2) { if (instance.int_intdiv) { return intdivSlow(op1, op2); } else { return op1 / ((int) op2); } } private static int intdivSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static int intdiv(int op1, int op2) { if (instance.int_intdiv) { return intdivSlow(op1, op2); } else { return op1 / op2; } } private static int intdivSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).intValue(); } public static long intdiv(int op1, long op2) { if (instance.int_intdiv) { return intdivSlow(op1, op2); } else { return ((long) op1) / op2; } } private static long intdivSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static long intdiv(long op1, byte op2) { if (instance.long_intdiv) { return intdivSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long intdivSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static long intdiv(long op1, short op2) { if (instance.long_intdiv) { return intdivSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long intdivSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static long intdiv(long op1, int op2) { if (instance.long_intdiv) { return intdivSlow(op1, op2); } else { return op1 / ((long) op2); } } private static long intdivSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static long intdiv(long op1, long op2) { if (instance.long_intdiv) { return intdivSlow(op1, op2); } else { return op1 / op2; } } private static long intdivSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue(); } public static int mod(byte op1, byte op2) { if (instance.byte_mod) { return modSlow(op1, op2); } else { return ((int) op1) % ((int) op2); } } private static int modSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(byte op1, short op2) { if (instance.byte_mod) { return modSlow(op1, op2); } else { return ((int) op1) % ((int) op2); } } private static int modSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(byte op1, int op2) { if (instance.byte_mod) { return modSlow(op1, op2); } else { return ((int) op1) % op2; } } private static int modSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static long mod(byte op1, long op2) { if (instance.byte_mod) { return modSlow(op1, op2); } else { return ((long) op1) % op2; } } private static long modSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static int mod(short op1, byte op2) { if (instance.short_mod) { return modSlow(op1, op2); } else { return ((int) op1) % ((int) op2); } } private static int modSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(short op1, short op2) { if (instance.short_mod) { return modSlow(op1, op2); } else { return ((int) op1) % ((int) op2); } } private static int modSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(short op1, int op2) { if (instance.short_mod) { return modSlow(op1, op2); } else { return ((int) op1) % op2; } } private static int modSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static long mod(short op1, long op2) { if (instance.short_mod) { return modSlow(op1, op2); } else { return ((long) op1) % op2; } } private static long modSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static int mod(int op1, byte op2) { if (instance.int_mod) { return modSlow(op1, op2); } else { return op1 % ((int) op2); } } private static int modSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(int op1, short op2) { if (instance.int_mod) { return modSlow(op1, op2); } else { return op1 % ((int) op2); } } private static int modSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static int mod(int op1, int op2) { if (instance.int_mod) { return modSlow(op1, op2); } else { return op1 % op2; } } private static int modSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue(); } public static long mod(int op1, long op2) { if (instance.int_mod) { return modSlow(op1, op2); } else { return ((long) op1) % op2; } } private static long modSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static long mod(long op1, byte op2) { if (instance.long_mod) { return modSlow(op1, op2); } else { return op1 % ((long) op2); } } private static long modSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static long mod(long op1, short op2) { if (instance.long_mod) { return modSlow(op1, op2); } else { return op1 % ((long) op2); } } private static long modSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static long mod(long op1, int op2) { if (instance.long_mod) { return modSlow(op1, op2); } else { return op1 % ((long) op2); } } private static long modSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static long mod(long op1, long op2) { if (instance.long_mod) { return modSlow(op1, op2); } else { return op1 % op2; } } private static long modSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).longValue(); } public static int leftShift(byte op1, byte op2) { if (instance.byte_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << ((int) op2); } } private static int leftShiftSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(byte op1, short op2) { if (instance.byte_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << ((int) op2); } } private static int leftShiftSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(byte op1, int op2) { if (instance.byte_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << op2; } } private static int leftShiftSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static long leftShift(byte op1, long op2) { if (instance.byte_leftShift) { return leftShiftSlow(op1, op2); } else { return ((long) op1) << op2; } } private static long leftShiftSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static int leftShift(short op1, byte op2) { if (instance.short_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << ((int) op2); } } private static int leftShiftSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(short op1, short op2) { if (instance.short_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << ((int) op2); } } private static int leftShiftSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(short op1, int op2) { if (instance.short_leftShift) { return leftShiftSlow(op1, op2); } else { return ((int) op1) << op2; } } private static int leftShiftSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static long leftShift(short op1, long op2) { if (instance.short_leftShift) { return leftShiftSlow(op1, op2); } else { return ((long) op1) << op2; } } private static long leftShiftSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static int leftShift(int op1, byte op2) { if (instance.int_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << ((int) op2); } } private static int leftShiftSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(int op1, short op2) { if (instance.int_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << ((int) op2); } } private static int leftShiftSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static int leftShift(int op1, int op2) { if (instance.int_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << op2; } } private static int leftShiftSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).intValue(); } public static long leftShift(int op1, long op2) { if (instance.int_leftShift) { return leftShiftSlow(op1, op2); } else { return ((long) op1) << op2; } } private static long leftShiftSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static long leftShift(long op1, byte op2) { if (instance.long_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << ((long) op2); } } private static long leftShiftSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static long leftShift(long op1, short op2) { if (instance.long_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << ((long) op2); } } private static long leftShiftSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static long leftShift(long op1, int op2) { if (instance.long_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << ((long) op2); } } private static long leftShiftSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static long leftShift(long op1, long op2) { if (instance.long_leftShift) { return leftShiftSlow(op1, op2); } else { return op1 << op2; } } private static long leftShiftSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue(); } public static int rightShift(byte op1, byte op2) { if (instance.byte_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> ((int) op2); } } private static int rightShiftSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(byte op1, short op2) { if (instance.byte_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> ((int) op2); } } private static int rightShiftSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(byte op1, int op2) { if (instance.byte_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> op2; } } private static int rightShiftSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static long rightShift(byte op1, long op2) { if (instance.byte_rightShift) { return rightShiftSlow(op1, op2); } else { return ((long) op1) >> op2; } } private static long rightShiftSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static int rightShift(short op1, byte op2) { if (instance.short_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> ((int) op2); } } private static int rightShiftSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(short op1, short op2) { if (instance.short_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> ((int) op2); } } private static int rightShiftSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(short op1, int op2) { if (instance.short_rightShift) { return rightShiftSlow(op1, op2); } else { return ((int) op1) >> op2; } } private static int rightShiftSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static long rightShift(short op1, long op2) { if (instance.short_rightShift) { return rightShiftSlow(op1, op2); } else { return ((long) op1) >> op2; } } private static long rightShiftSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static int rightShift(int op1, byte op2) { if (instance.int_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> ((int) op2); } } private static int rightShiftSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(int op1, short op2) { if (instance.int_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> ((int) op2); } } private static int rightShiftSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static int rightShift(int op1, int op2) { if (instance.int_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> op2; } } private static int rightShiftSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).intValue(); } public static long rightShift(int op1, long op2) { if (instance.int_rightShift) { return rightShiftSlow(op1, op2); } else { return ((long) op1) >> op2; } } private static long rightShiftSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static long rightShift(long op1, byte op2) { if (instance.long_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> ((long) op2); } } private static long rightShiftSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static long rightShift(long op1, short op2) { if (instance.long_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> ((long) op2); } } private static long rightShiftSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static long rightShift(long op1, int op2) { if (instance.long_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> ((long) op2); } } private static long rightShiftSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static long rightShift(long op1, long op2) { if (instance.long_rightShift) { return rightShiftSlow(op1, op2); } else { return op1 >> op2; } } private static long rightShiftSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue(); } public static int rightShiftUnsigned(byte op1, byte op2) { if (instance.byte_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> ((int) op2); } } private static int rightShiftUnsignedSlow(byte op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(byte op1, short op2) { if (instance.byte_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> ((int) op2); } } private static int rightShiftUnsignedSlow(byte op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(byte op1, int op2) { if (instance.byte_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> op2; } } private static int rightShiftUnsignedSlow(byte op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static long rightShiftUnsigned(byte op1, long op2) { if (instance.byte_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((long) op1) >>> op2; } } private static long rightShiftUnsignedSlow(byte op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static int rightShiftUnsigned(short op1, byte op2) { if (instance.short_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> ((int) op2); } } private static int rightShiftUnsignedSlow(short op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(short op1, short op2) { if (instance.short_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> ((int) op2); } } private static int rightShiftUnsignedSlow(short op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(short op1, int op2) { if (instance.short_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((int) op1) >>> op2; } } private static int rightShiftUnsignedSlow(short op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static long rightShiftUnsigned(short op1, long op2) { if (instance.short_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((long) op1) >>> op2; } } private static long rightShiftUnsignedSlow(short op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static int rightShiftUnsigned(int op1, byte op2) { if (instance.int_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> ((int) op2); } } private static int rightShiftUnsignedSlow(int op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(int op1, short op2) { if (instance.int_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> ((int) op2); } } private static int rightShiftUnsignedSlow(int op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static int rightShiftUnsigned(int op1, int op2) { if (instance.int_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> op2; } } private static int rightShiftUnsignedSlow(int op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).intValue(); } public static long rightShiftUnsigned(int op1, long op2) { if (instance.int_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return ((long) op1) >>> op2; } } private static long rightShiftUnsignedSlow(int op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static long rightShiftUnsigned(long op1, byte op2) { if (instance.long_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> ((long) op2); } } private static long rightShiftUnsignedSlow(long op1, byte op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static long rightShiftUnsigned(long op1, short op2) { if (instance.long_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> ((long) op2); } } private static long rightShiftUnsignedSlow(long op1, short op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static long rightShiftUnsigned(long op1, int op2) { if (instance.long_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> ((long) op2); } } private static long rightShiftUnsignedSlow(long op1, int op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } public static long rightShiftUnsigned(long op1, long op2) { if (instance.long_rightShiftUnsigned) { return rightShiftUnsignedSlow(op1, op2); } else { return op1 >>> op2; } } private static long rightShiftUnsignedSlow(long op1, long op2) { return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/GroovyCastException.java0000644001501200150120000000565711707612046031027 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; public class GroovyCastException extends ClassCastException { /** * @param objectToCast object we tried to cast * @param classToCastTo class we tried to cast to * @param cause not kept but we pass on message from this Exception if any */ public GroovyCastException(Object objectToCast, Class classToCastTo, Exception cause) { super(makeMessage(objectToCast,classToCastTo) + " due to: " + cause.getClass().getName() + (cause.getMessage() == null ? "" : ": " + cause.getMessage())); } /** * @param objectToCast object we tried to cast * @param classToCastTo class we tried to cast to */ public GroovyCastException(Object objectToCast, Class classToCastTo) { super(makeMessage(objectToCast,classToCastTo)); } /** * @param message custom Exception message */ public GroovyCastException(String message) { super(message); } private static String makeMessage(Object objectToCast, Class classToCastTo) { String classToCastFrom; Object msgObject = objectToCast; if (objectToCast!=null) { classToCastFrom = objectToCast.getClass().getName(); } else { msgObject = "null"; classToCastFrom = "null"; } String msg = "Cannot cast object '" + msgObject + "' " + "with class '" + classToCastFrom + "' " + "to class '" + classToCastTo.getName() + "'"; if (objectToCast==null){ msg += getWrapper(classToCastTo); } return msg; } private static String getWrapper(Class cls) { Class ncls = cls; if (cls==byte.class) {ncls=Byte.class;} else if (cls==short.class) {ncls=Short.class;} else if (cls==char.class) {ncls=Character.class;} else if (cls==int.class) {ncls=Integer.class;} else if (cls==long.class) {ncls=Long.class;} else if (cls==float.class) {ncls=Float.class;} else if (cls==double.class) {ncls=Double.class;} if (cls!=null && ncls!=cls) { String msg = ". Try '" + ncls.getName() + "' instead"; return msg; } return ""; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/BigIntegerMath.java0000644001501200150120000000471111627206700027664 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; /** * BigInteger NumberMath operations * * @author Steve Goetze */ public final class BigIntegerMath extends NumberMath { public static final BigIntegerMath INSTANCE = new BigIntegerMath(); private BigIntegerMath() {} protected Number absImpl(Number number) { return toBigInteger(number).abs(); } public Number addImpl(Number left, Number right) { return toBigInteger(left).add(toBigInteger(right)); } public Number subtractImpl(Number left, Number right) { return toBigInteger(left).subtract(toBigInteger(right)); } public Number multiplyImpl(Number left, Number right) { return toBigInteger(left).multiply(toBigInteger(right)); } public Number divideImpl(Number left, Number right) { return BigDecimalMath.INSTANCE.divideImpl(left, right); } public int compareToImpl(Number left, Number right) { return toBigInteger(left).compareTo(toBigInteger(right)); } protected Number intdivImpl(Number left, Number right) { return toBigInteger(left).divide(toBigInteger(right)); } protected Number modImpl(Number left, Number right) { return toBigInteger(left).mod(toBigInteger(right)); } protected Number unaryMinusImpl(Number left) { return toBigInteger(left).negate(); } protected Number bitwiseNegateImpl(Number left) { return toBigInteger(left).not(); } protected Number orImpl(Number left, Number right) { return toBigInteger(left).or(toBigInteger(right)); } protected Number andImpl(Number left, Number right) { return toBigInteger(left).and(toBigInteger(right)); } protected Number xorImpl(Number left, Number right) { return toBigInteger(left).xor(toBigInteger(right)); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/FloatingPointMath.java0000644001501200150120000000371711627206700030427 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; /** * FloatingPoint (Double and Float) NumberMath operations * * @author Steve Goetze */ public final class FloatingPointMath extends NumberMath { public static final FloatingPointMath INSTANCE = new FloatingPointMath(); private FloatingPointMath() {} protected Number absImpl(Number number) { return new Double(Math.abs(number.doubleValue())); } public Number addImpl(Number left, Number right) { return new Double(left.doubleValue() + right.doubleValue()); } public Number subtractImpl(Number left, Number right) { return new Double(left.doubleValue() - right.doubleValue()); } public Number multiplyImpl(Number left, Number right) { return new Double(left.doubleValue() * right.doubleValue()); } public Number divideImpl(Number left, Number right) { return new Double(left.doubleValue() / right.doubleValue()); } public int compareToImpl(Number left, Number right) { return Double.compare(left.doubleValue(), right.doubleValue()); } protected Number modImpl(Number left, Number right) { return new Double(left.doubleValue() % right.doubleValue()); } protected Number unaryMinusImpl(Number left) { return new Double(-left.doubleValue()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/typehandling/LongMath.java0000644001501200150120000000623111707612046026546 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.typehandling; /** * Long NumberMath operations * * @author Steve Goetze */ public final class LongMath extends NumberMath { public static final LongMath INSTANCE = new LongMath(); private LongMath() {} protected Number absImpl(Number number) { return Long.valueOf(Math.abs(number.longValue())); } public Number addImpl(Number left, Number right) { return Long.valueOf(left.longValue() + right.longValue()); } public Number subtractImpl(Number left, Number right) { return Long.valueOf(left.longValue() - right.longValue()); } public Number multiplyImpl(Number left, Number right) { return Long.valueOf(left.longValue() * right.longValue()); } public Number divideImpl(Number left, Number right) { return BigDecimalMath.INSTANCE.divideImpl(left, right); } public int compareToImpl(Number left, Number right) { long leftVal = left.longValue(); long rightVal = right.longValue(); return (leftVal> right.longValue()); } protected Number rightShiftUnsignedImpl(Number left, Number right) { return Long.valueOf(left.longValue() >>> right.longValue()); } protected Number bitAndImpl(Number left, Number right) { return Long.valueOf(left.longValue() & right.longValue()); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/IteratorClosureAdapter.java0000644001501200150120000000306611627206700026776 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import groovy.lang.MetaClass; import java.util.ArrayList; import java.util.List; /** * A closure which stores calls in a List so that method calls * can be iterated over in a 'yield' style way * * @author James Strachan * @version $Revision$ */ public class IteratorClosureAdapter extends Closure { private final List list = new ArrayList(); private MetaClass metaClass = InvokerHelper.getMetaClass(getClass()); public IteratorClosureAdapter(Object delegate) { super(delegate); } public MetaClass getMetaClass() { return metaClass; } public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } public List asList() { return list; } protected Object doCall(T argument) { list.add(argument); return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java0000644001501200150120000002364711713765714026651 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.StringWriterIOException; import groovy.lang.Writable; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * This class defines all the encoding/decoding groovy methods which enhance * the normal JDK classes when inside the Groovy environment. * Static methods are used with the first parameter the destination class. */ public class EncodingGroovyMethods { private static final char[] T_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); private static final String CHUNK_SEPARATOR = "\r\n"; /** * Produce a Writable object which writes the Base64 encoding of the byte array. * Calling toString() on the result returns the encoding as a String. For more * information on Base64 encoding and chunking see RFC 4648. * * @param data Byte array to be encoded * @param chunked whether or not the Base64 encoded data should be MIME chunked * @return object which will write the Base64 encoding of the byte array * @since 1.5.1 */ public static Writable encodeBase64(Byte[] data, final boolean chunked) { return encodeBase64(DefaultTypeTransformation.convertToByteArray(data), chunked); } /** * Produce a Writable object which writes the Base64 encoding of the byte array. * Calling toString() on the result returns the encoding as a String. For more * information on Base64 encoding and chunking see RFC 4648. * * @param data Byte array to be encoded * @return object which will write the Base64 encoding of the byte array * @since 1.0 */ public static Writable encodeBase64(Byte[] data) { return encodeBase64(DefaultTypeTransformation.convertToByteArray(data), false); } /** * Produce a Writable object which writes the Base64 encoding of the byte array. * Calling toString() on the result returns the encoding as a String. For more * information on Base64 encoding and chunking see RFC 4648. * * @param data byte array to be encoded * @param chunked whether or not the Base64 encoded data should be MIME chunked * @return object which will write the Base64 encoding of the byte array * @since 1.5.7 */ public static Writable encodeBase64(final byte[] data, final boolean chunked) { return new Writable() { public Writer writeTo(final Writer writer) throws IOException { int charCount = 0; final int dLimit = (data.length / 3) * 3; for (int dIndex = 0; dIndex != dLimit; dIndex += 3) { int d = ((data[dIndex] & 0XFF) << 16) | ((data[dIndex + 1] & 0XFF) << 8) | (data[dIndex + 2] & 0XFF); writer.write(T_TABLE[d >> 18]); writer.write(T_TABLE[(d >> 12) & 0X3F]); writer.write(T_TABLE[(d >> 6) & 0X3F]); writer.write(T_TABLE[d & 0X3F]); if (chunked && ++charCount == 19) { writer.write(CHUNK_SEPARATOR); charCount = 0; } } if (dLimit != data.length) { int d = (data[dLimit] & 0XFF) << 16; if (dLimit + 1 != data.length) { d |= (data[dLimit + 1] & 0XFF) << 8; } writer.write(T_TABLE[d >> 18]); writer.write(T_TABLE[(d >> 12) & 0X3F]); writer.write((dLimit + 1 < data.length) ? T_TABLE[(d >> 6) & 0X3F] : '='); writer.write('='); if (chunked && charCount != 0) { writer.write(CHUNK_SEPARATOR); } } return writer; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new StringWriterIOException(e); } return buffer.toString(); } }; } /** * Produce a Writable object which writes the Base64 encoding of the byte array. * Calling toString() on the result returns the encoding as a String. For more * information on Base64 encoding and chunking see RFC 4648. * * @param data byte array to be encoded * @return object which will write the Base64 encoding of the byte array * @since 1.0 */ public static Writable encodeBase64(final byte[] data) { return encodeBase64(data, false); } /** * Decode the String from Base64 into a byte array. * * @param value the string to be decoded * @return the decoded bytes as an array * @since 1.0 */ public static byte[] decodeBase64(String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift-- != 4) { buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift--; done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } } /** * Produces a Writable that writes the hex encoding of the Byte[]. Calling * toString() on this Writable returns the hex encoding as a String. The hex * encoding includes two characters for each byte and all letters are lower case. * * @param data byte array to be encoded * @return object which will write the hex encoding of the byte array * @see Integer#toHexString(int) */ public static Writable encodeHex(final Byte[] data) { return encodeHex(DefaultTypeTransformation.convertToByteArray(data)); } /** * Produces a Writable that writes the hex encoding of the byte[]. Calling * toString() on this Writable returns the hex encoding as a String. The hex * encoding includes two characters for each byte and all letters are lower case. * * @param data byte array to be encoded * @return object which will write the hex encoding of the byte array * @see Integer#toHexString(int) */ public static Writable encodeHex(final byte[] data) { return new Writable() { public Writer writeTo(Writer out) throws IOException { for (int i = 0; i < data.length; i++) { // convert byte into unsigned hex string String hexString = Integer.toHexString(data[i] & 0xFF); // add leading zero if the length of the string is one if (hexString.length() < 2) { out.write("0"); } // write hex string to writer out.write(hexString); } return out; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new StringWriterIOException(e); } return buffer.toString(); } }; } /** * Decodes a hex string to a byte array. The hex string can contain either upper * case or lower case letters. * * @param value string to be decoded * @return decoded byte array * @throws NumberFormatException If the string contains an odd number of characters * or if the characters are not valid hexadecimal values. */ public static byte[] decodeHex(final String value) { // if string length is odd then throw exception if (value.length() % 2 != 0) { throw new NumberFormatException("odd number of characters in hex string"); } byte[] bytes = new byte[value.length() / 2]; for (int i = 0; i < value.length(); i += 2) { bytes[i / 2] = (byte) Integer.parseInt(value.substring(i, i + 2), 16); } return bytes; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/StringBufferWriter.java0000644001501200150120000000567011707612046026152 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.io.IOException; import java.io.Writer; /** * This class codes around a silly limiation of StringWriter which doesn't allow a StringBuffer * to be passed in as a constructor for some bizarre reason. * So we replicate the behaviour of StringWriter here but allow a StringBuffer to be passed in. * * @author James Strachan * @version $Revision$ */ public class StringBufferWriter extends Writer { private StringBuffer buffer; /** * Create a new string writer which will append the text to the given StringBuffer */ public StringBufferWriter(StringBuffer buffer) { this.buffer = buffer; } /** * Write a single character. */ public void write(int c) { buffer.append((char) c); } /** * Write a portion of an array of characters. * * @param text Array of characters * @param offset Offset from which to start writing characters * @param length Number of characters to write */ public void write(char text[], int offset, int length) { if ((offset < 0) || (offset > text.length) || (length < 0) || ((offset + length) > text.length) || ((offset + length) < 0)) { throw new IndexOutOfBoundsException(); } else if (length == 0) { return; } buffer.append(text, offset, length); } /** * Write a string. */ public void write(String text) { buffer.append(text); } /** * Write a portion of a string. * * @param text the text to be written * @param offset offset from which to start writing characters * @param length Number of characters to write */ public void write(String text, int offset, int length) { buffer.append(text.substring(offset, offset + length)); } /** * Return the buffer's current value as a string. */ public String toString() { return buffer.toString(); } /** * Flush the stream. */ public void flush() { } /** * Closing a StringWriter has no effect. The methods in this * class can be called after the stream has been closed without generating * an IOException. */ public void close() throws IOException { } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/0000755001501200150120000000000011715031256023277 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PojoMetaClassSite.java0000644001501200150120000000363011707612074027501 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; /** * POJO call site * meta class - cached * method - not cached * * @author Alex Tkachman */ public class PojoMetaClassSite extends MetaClassSite{ private final ClassInfo classInfo; private final int version; public PojoMetaClassSite(CallSite site, MetaClass metaClass) { super(site, metaClass); classInfo = ClassInfo.getClassInfo(metaClass.getTheClass()); version = classInfo.getVersion(); } public Object call(Object receiver, Object[] args) throws Throwable { if(checkCall(receiver)) { try{ return metaClass.invokeMethod(receiver, name, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } protected final boolean checkCall(Object receiver) { return receiver!=null && receiver.getClass() == metaClass.getTheClass() && version == classInfo.getVersion(); // metaClass is still valid } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/ClassMetaClassGetPropertySite.java0000644001501200150120000000346211627206700032043 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; class ClassMetaClassGetPropertySite extends AbstractCallSite { final MetaClass metaClass; private final Class aClass; private final ClassInfo classInfo; private final int version; public ClassMetaClassGetPropertySite(CallSite parent, Class aClass) { super(parent); this.aClass = aClass; classInfo = ClassInfo.getClassInfo(aClass); version = classInfo.getVersion(); metaClass = classInfo.getMetaClass(); } public final CallSite acceptGetProperty(Object receiver) { if (receiver != aClass || version != classInfo.getVersion()) // metaClass is invalid return createGetPropertySite(receiver); else return this; } public final Object getProperty(Object receiver) throws Throwable{ try { return metaClass.getProperty(aClass, name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/DummyCallSite.java0000644001501200150120000000150311627206700026655 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; public class DummyCallSite extends AbstractCallSite { public DummyCallSite(CallSiteArray array, int index, String name) { super(array, index,name); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite.java0000644001501200150120000002725311707612046027657 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * POGO call site * meta class - cached * method - cached */ public class PogoMetaMethodSite extends MetaMethodSite { public PogoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public Object invoke(Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); try { return metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } public Object callCurrent(GroovyObject receiver, Object[] args) throws Throwable { if(checkCall(receiver, args)) { try { return invoke(receiver,args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallCurrent(this, receiver, args); } } public Object call(Object receiver, Object[] args) throws Throwable { if(checkCall(receiver, args)) { try { return invoke(receiver,args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } protected boolean checkCall(Object receiver, Object[] args) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params, args); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } protected boolean checkCall(Object receiver) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } protected boolean checkCall(Object receiver, Object arg1) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } protected boolean checkCall(Object receiver, Object arg1, Object arg2) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } protected boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2, arg3); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } protected boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) { try { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((GroovyObject)receiver).getMetaClass() == metaClass // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2, arg3, arg4); } catch (NullPointerException e) { if (receiver == null) return false; throw e; } catch (ClassCastException e) { if (!(receiver instanceof GroovyObject)) return false; throw e; } } public static CallSite createPogoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.getClass() == CachedMethod.class) return createCachedMethodSite (site, metaClass, (CachedMethod) metaMethod, params, args); return createNonAwareCallSite(site, metaClass, metaMethod, params, args); } private static CallSite createNonAwareCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(metaMethod,args)) return new PogoMetaMethodSiteNoUnwrap(site, metaClass, metaMethod, params); else { return new PogoMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, metaMethod, params); } } } return new PogoMetaMethodSite(site, metaClass, metaMethod, params); } public static CallSite createCachedMethodSite(CallSite site, MetaClassImpl metaClass, CachedMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(metaMethod,args)) return new PogoCachedMethodSiteNoUnwrap(site, metaClass, metaMethod, params); else { return metaMethod.createPogoMetaMethodSite(site, metaClass, params); } } } return new PogoCachedMethodSite(site, metaClass, metaMethod, params); } public static class PogoCachedMethodSite extends PogoMetaMethodSite { final Method reflect; public PogoCachedMethodSite(CallSite site, MetaClassImpl metaClass, CachedMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); reflect = metaMethod.setAccessible(); } public Object invoke(Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); args = metaMethod.coerceArgumentsToClasses(args); try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } public static class PogoCachedMethodSiteNoUnwrap extends PogoCachedMethodSite { public PogoCachedMethodSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, CachedMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { args = metaMethod.coerceArgumentsToClasses(args); try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } public static class PogoCachedMethodSiteNoUnwrapNoCoerce extends PogoCachedMethodSite { public PogoCachedMethodSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, CachedMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } /** * Call site where we know there is no need to unwrap arguments */ public static class PogoMetaMethodSiteNoUnwrap extends PogoMetaMethodSite { public PogoMetaMethodSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } /** * Call site where we know there is no need neither unwrap nor coerce arguments */ public static class PogoMetaMethodSiteNoUnwrapNoCoerce extends PogoMetaMethodSite { public PogoMetaMethodSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/AbstractCallSite.java0000644001501200150120000003021611707612046027333 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.*; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.reflection.ParameterTypes; import org.codehaus.groovy.runtime.ArrayUtil; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.wrappers.Wrapper; import java.lang.reflect.Method; /** * Base class for all call sites * * @author Alex Tkachman */ public class AbstractCallSite implements CallSite { protected final int index; protected final String name; protected final CallSiteArray array; public AbstractCallSite(CallSiteArray array, int index, String name) { this.name = name; this.index = index; this.array = array; } public AbstractCallSite(CallSite prev) { this.name = prev.getName(); this.index = prev.getIndex(); this.array = prev.getArray(); } public int getIndex() { return index; } public CallSiteArray getArray() { return array; } public String getName() { return name; } public final Object callSafe(Object receiver, Object[] args) throws Throwable { if (receiver == null) return null; return call(receiver, args); } public final Object callSafe(Object receiver) throws Throwable { if (receiver == null) return null; return call(receiver); } public final Object callSafe(Object receiver, Object arg1) throws Throwable { if (receiver == null) return null; return call(receiver, arg1); } public final Object callSafe(Object receiver, Object arg1, Object arg2) throws Throwable { if (receiver == null) return null; return call(receiver, arg1, arg2); } public final Object callSafe(Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable { if (receiver == null) return null; return call(receiver, arg1, arg2, arg3); } public Object callSafe(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { if (receiver == null) return null; return call(receiver, arg1, arg2, arg3, arg4); } public Object call(Object receiver, Object[] args) throws Throwable { return CallSiteArray.defaultCall(this, receiver, args); } public Object call(Object receiver) throws Throwable { return call(receiver, CallSiteArray.NOPARAM); } public Object call(Object receiver, Object arg1) throws Throwable { return call(receiver, ArrayUtil.createArray(arg1)); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { return call(receiver, ArrayUtil.createArray(arg1, arg2)); } public Object call(Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable { return call(receiver, ArrayUtil.createArray(arg1, arg2, arg3)); } public Object call(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { return call(receiver, ArrayUtil.createArray(arg1, arg2, arg3, arg4)); } public Object callCurrent(GroovyObject receiver, Object[] args) throws Throwable { return CallSiteArray.defaultCallCurrent(this, receiver, args); } public Object callCurrent(GroovyObject receiver) throws Throwable { return callCurrent(receiver, CallSiteArray.NOPARAM); } public Object callCurrent(GroovyObject receiver, Object arg1) throws Throwable { return callCurrent(receiver, ArrayUtil.createArray(arg1)); } public Object callCurrent(GroovyObject receiver, Object arg1, Object arg2) throws Throwable { return callCurrent(receiver, ArrayUtil.createArray(arg1, arg2)); } public Object callCurrent(GroovyObject receiver, Object arg1, Object arg2, Object arg3) throws Throwable { return callCurrent(receiver, ArrayUtil.createArray(arg1, arg2, arg3)); } public Object callCurrent(GroovyObject receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { return callCurrent(receiver, ArrayUtil.createArray(arg1, arg2, arg3, arg4)); } public Object callStatic(Class receiver, Object[] args) throws Throwable { return CallSiteArray.defaultCallStatic(this, receiver, args); } public Object callStatic(Class receiver) throws Throwable { return callStatic(receiver, CallSiteArray.NOPARAM); } public Object callStatic(Class receiver, Object arg1) throws Throwable { return callStatic(receiver, ArrayUtil.createArray(arg1)); } public Object callStatic(Class receiver, Object arg1, Object arg2) throws Throwable { return callStatic(receiver, ArrayUtil.createArray(arg1, arg2)); } public Object callStatic(Class receiver, Object arg1, Object arg2, Object arg3) throws Throwable { return callStatic(receiver, ArrayUtil.createArray(arg1, arg2, arg3)); } public Object callStatic(Class receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { return callStatic(receiver, ArrayUtil.createArray(arg1, arg2, arg3, arg4)); } public Object callConstructor(Object receiver, Object[] args) throws Throwable { return CallSiteArray.defaultCallConstructor(this, receiver, args); } public Object callConstructor(Object receiver) throws Throwable { return callConstructor(receiver, CallSiteArray.NOPARAM); } public Object callConstructor(Object receiver, Object arg1) throws Throwable { return callConstructor(receiver, ArrayUtil.createArray(arg1)); } public Object callConstructor(Object receiver, Object arg1, Object arg2) throws Throwable { return callConstructor(receiver, ArrayUtil.createArray(arg1, arg2)); } public Object callConstructor(Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable { return callConstructor(receiver, ArrayUtil.createArray(arg1, arg2, arg3)); } public Object callConstructor(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { return callConstructor(receiver, ArrayUtil.createArray(arg1, arg2, arg3, arg4)); } static boolean noCoerce(ParameterTypes metaMethod, Object[] args) { final CachedClass[] paramClasses = metaMethod.getParameterTypes(); if (paramClasses.length != args.length) return false; for (int i = 0; i < paramClasses.length; i++) { CachedClass paramClass = paramClasses[i]; if (args[i] != null && !paramClass.isDirectlyAssignable(args[i])) return true; } return false; } static boolean noWrappers(Object[] args) { for (int i = 0; i != args.length; ++i) if (args[i] instanceof Wrapper) return false; return true; } public Object callGetProperty(Object receiver) throws Throwable { return acceptGetProperty(receiver).getProperty(receiver); } public Object callGroovyObjectGetProperty(Object receiver) throws Throwable { return acceptGroovyObjectGetProperty(receiver).getProperty(receiver); } public CallSite acceptGetProperty(Object receiver) { return createGetPropertySite(receiver); } public CallSite acceptGroovyObjectGetProperty(Object receiver) { return createGroovyObjectGetPropertySite(receiver); } protected final CallSite createGetPropertySite(Object receiver) { if (receiver == null) { return new NullCallSite(this); } else if (receiver instanceof GroovyObject) { return createGroovyObjectGetPropertySite(receiver); } else if (receiver instanceof Class) { return createClassMetaClassGetPropertySite((Class) receiver); } return createPojoMetaClassGetPropertySite(receiver); } protected final CallSite createGroovyObjectGetPropertySite(Object receiver) { Class aClass = receiver.getClass(); try { final Method method = aClass.getMethod("getProperty", String.class); if (method != null && method.isSynthetic() && ((GroovyObject) receiver).getMetaClass() instanceof MetaClassImpl) return createPogoMetaClassGetPropertySite((GroovyObject) receiver); } catch (NoSuchMethodException e) { // fall threw } if (receiver instanceof Class) { return createClassMetaClassGetPropertySite((Class) receiver); } else { return createPogoGetPropertySite(aClass); } } public Object getProperty(Object receiver) throws Throwable { throw new UnsupportedOperationException(); } private CallSite createPojoMetaClassGetPropertySite(Object receiver) { final MetaClass metaClass = InvokerHelper.getMetaClass(receiver); CallSite site; if (metaClass.getClass() != MetaClassImpl.class || GroovyCategorySupport.hasCategoryInCurrentThread()) { site = new PojoMetaClassGetPropertySite(this); } else { final MetaProperty effective = ((MetaClassImpl) metaClass).getEffectiveGetMetaProperty(receiver.getClass(), receiver, name, false); if (effective != null) { if (effective instanceof CachedField) site = new GetEffectivePojoFieldSite(this, (MetaClassImpl) metaClass, (CachedField) effective); else site = new GetEffectivePojoPropertySite(this, (MetaClassImpl) metaClass, effective); } else { site = new PojoMetaClassGetPropertySite(this); } } array.array[index] = site; return site; } private CallSite createClassMetaClassGetPropertySite(Class aClass) { CallSite site = new ClassMetaClassGetPropertySite(this, aClass); array.array[index] = site; return site; } private CallSite createPogoMetaClassGetPropertySite(GroovyObject receiver) { MetaClass metaClass = receiver.getMetaClass(); CallSite site; if (metaClass.getClass() != MetaClassImpl.class || GroovyCategorySupport.hasCategoryInCurrentThread()) { site = new PogoMetaClassGetPropertySite(this, metaClass); } else { final MetaProperty effective = ((MetaClassImpl) metaClass).getEffectiveGetMetaProperty(metaClass.getClass(), receiver, name, false); if (effective != null) { if (effective instanceof CachedField) site = new GetEffectivePogoFieldSite(this, metaClass, (CachedField) effective); else site = new GetEffectivePogoPropertySite(this, metaClass, effective); } else { site = new PogoMetaClassGetPropertySite(this, metaClass); } } array.array[index] = site; return site; } private CallSite createPogoGetPropertySite(Class aClass) { CallSite site = new PogoGetPropertySite(this, aClass); array.array[index] = site; return site; } public final Object callGetPropertySafe(Object receiver) throws Throwable { if (receiver == null) return null; else return callGetProperty(receiver); } public final Object callGroovyObjectGetPropertySafe(Object receiver) throws Throwable { if (receiver == null) return null; else return callGroovyObjectGetProperty(receiver); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/GroovySunClassLoader.java0000644001501200150120000000540611713765676030261 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.codehaus.groovy.reflection.SunClassLoader; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; import java.security.PrivilegedAction; public class GroovySunClassLoader extends SunClassLoader { public static final SunClassLoader sunVM; static { sunVM = AccessController.doPrivileged(new PrivilegedAction() { public SunClassLoader run() { try { if (SunClassLoader.sunVM != null) { return new GroovySunClassLoader(); } } catch (Throwable t) {// } return null; } }); } protected GroovySunClassLoader () throws Throwable { super(); loadAbstract (); loadFromRes("org.codehaus.groovy.runtime.callsite.MetaClassSite"); loadFromRes("org.codehaus.groovy.runtime.callsite.MetaMethodSite"); loadFromRes("org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite"); loadFromRes("org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite"); loadFromRes("org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite"); } private void loadAbstract() throws IOException { final InputStream asStream = GroovySunClassLoader.class.getClass().getClassLoader().getResourceAsStream(resName("org.codehaus.groovy.runtime.callsite.AbstractCallSite")); ClassReader reader = new ClassReader(asStream); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS) { public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, "sun/reflect/GroovyMagic", interfaces); } }; reader.accept(cw, ClassWriter.COMPUTE_MAXS); asStream.close(); define(cw.toByteArray(), "org.codehaus.groovy.runtime.callsite.AbstractCallSite"); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePojoPropertySite.java0000644001501200150120000000510611627206700031726 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import groovy.lang.MetaProperty; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; public class GetEffectivePojoPropertySite extends AbstractCallSite { private final MetaClassImpl metaClass; private final MetaProperty effective; private final int version; public GetEffectivePojoPropertySite(CallSite site, MetaClassImpl metaClass, MetaProperty effective) { super(site); this.metaClass = metaClass; this.effective = effective; version = metaClass.getVersion(); } // public final Object callGetProperty (Object receiver) throws Throwable { // if (GroovyCategorySupport.hasCategoryInCurrentThread() || receiver.getClass() != metaClass.getTheClass()) { // return createGetPropertySite(receiver).getProperty(receiver); // } else { // try { // return effective.getProperty(receiver); // } catch (GroovyRuntimeException gre) { // throw ScriptBytecodeAdapter.unwrap(gre); // } // } // } public final CallSite acceptGetProperty(Object receiver) { // if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || receiver.getClass() != metaClass.getTheClass() || version != metaClass.getVersion()) { // metaClass is invalid return createGetPropertySite(receiver); } else { return this; } } public final Object getProperty(Object receiver) throws Throwable { try { return effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassGetPropertySite.java0000644001501200150120000000355411627206700031704 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import groovy.lang.GroovyObject; public class PogoMetaClassGetPropertySite extends AbstractCallSite { private final MetaClass metaClass; public PogoMetaClassGetPropertySite(CallSite parent, MetaClass metaClass) { super(parent); this.metaClass = metaClass; } public final CallSite acceptGetProperty(Object receiver) { if (!(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) return createGetPropertySite(receiver); else return this; } public final CallSite acceptGroovyObjectGetProperty(Object receiver) { if (!(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) return createGroovyObjectGetPropertySite(receiver); else return this; } public final Object getProperty(Object receiver) throws Throwable { try { return metaClass.getProperty(receiver, name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PogoMetaClassSite.java0000644001501200150120000000646011627206700027476 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import groovy.lang.MissingMethodException; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed; /** * * @author Alex Tkachman */ public class PogoMetaClassSite extends MetaClassSite { public PogoMetaClassSite(CallSite site, MetaClass metaClass) { super(site, metaClass); } public final Object call(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver)) { try { try { return metaClass.invokeMethod(receiver, name, args); } catch (MissingMethodException e) { if (e instanceof MissingMethodExecutionFailed) { throw (MissingMethodException)e.getCause(); } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) { // in case there's nothing else, invoke the object's own invokeMethod() return ((GroovyObject)receiver).invokeMethod(name, args); } else { throw e; } } } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } protected final boolean checkCall(Object receiver) { return receiver instanceof GroovyObject && ((GroovyObject)receiver).getMetaClass() == metaClass; } public final Object callCurrent(GroovyObject receiver, Object[] args) throws Throwable { if (checkCall(receiver)) { try { try { return metaClass.invokeMethod(receiver, name, args); } catch (MissingMethodException e) { if (e instanceof MissingMethodExecutionFailed) { throw (MissingMethodException)e.getCause(); } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) { // in case there's nothing else, invoke the object's own invokeMethod() return ((GroovyObject)receiver).invokeMethod(name, args); } else { throw e; } } } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallCurrent(this, receiver, args); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/CallSiteAwareMetaMethod.java0000644001501200150120000000170211627206700030572 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; public abstract class CallSiteAwareMetaMethod extends MetaMethod{ public abstract CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args); } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.java0000644001501200150120000003031611707612046027517 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import groovy.lang.GroovyRuntimeException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class CallSiteGenerator { private static final String GRE = BytecodeHelper.getClassInternalName(ClassHelper.make(GroovyRuntimeException.class)); private CallSiteGenerator () {} private static MethodVisitor writeMethod(ClassWriter cw, String name, int argumentCount, final String superClass, CachedMethod cachedMethod, String receiverType, String parameterDescription, boolean useArray) { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "call" + name, "(L" + receiverType + ";" + parameterDescription + ")Ljava/lang/Object;", null, null); mv.visitCode(); final Label tryStart = new Label(); mv.visitLabel(tryStart); // call for checking if method is still valid for (int i = 0; i < argumentCount; ++i) mv.visitVarInsn(Opcodes.ALOAD, i); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, superClass, "checkCall", "(Ljava/lang/Object;" + parameterDescription + ")Z"); Label l0 = new Label(); mv.visitJumpInsn(Opcodes.IFEQ, l0); // valid method branch Class callClass = cachedMethod.getDeclaringClass().getTheClass(); boolean useInterface = callClass.isInterface(); String type = BytecodeHelper.getClassInternalName(callClass.getName()); String descriptor = BytecodeHelper.getMethodDescriptor(cachedMethod.getReturnType(), cachedMethod.getNativeParameterTypes()); // prepare call int invokeMethodCode = Opcodes.INVOKEVIRTUAL; if (cachedMethod.isStatic()) { invokeMethodCode = Opcodes.INVOKESTATIC; } else { mv.visitVarInsn(Opcodes.ALOAD, 1); BytecodeHelper.doCast(mv, callClass); if (useInterface) invokeMethodCode = Opcodes.INVOKEINTERFACE; } Method method = cachedMethod.setAccessible(); Class[] parameters = method.getParameterTypes(); int size = parameters.length; for (int i = 0; i < size; i++) { if (useArray) { // unpack argument from Object[] mv.visitVarInsn(Opcodes.ALOAD, 2); BytecodeHelper.pushConstant(mv, i); mv.visitInsn(Opcodes.AALOAD); } else { mv.visitVarInsn(Opcodes.ALOAD, i+2); } // cast argument to parameter class, inclusive unboxing // for methods with primitive types BytecodeHelper.doCast(mv, parameters[i]); } // make call mv.visitMethodInsn(invokeMethodCode, type, cachedMethod.getName(), descriptor); // produce result BytecodeHelper.box(mv, cachedMethod.getReturnType()); if (cachedMethod.getReturnType() == void.class) { mv.visitInsn(Opcodes.ACONST_NULL); } // return mv.visitInsn(Opcodes.ARETURN); // fall back after method change mv.visitLabel(l0); for (int i = 0; i < argumentCount; ++i) mv.visitVarInsn(Opcodes.ALOAD, i); if (!useArray) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/ArrayUtil", "createArray", "(" + parameterDescription + ")[Ljava/lang/Object;"); } mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/callsite/CallSiteArray", "defaultCall" + name, "(Lorg/codehaus/groovy/runtime/callsite/CallSite;L" + receiverType + ";[Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(Opcodes.ARETURN); // exception unwrapping for stackless exceptions final Label tryEnd = new Label(); mv.visitLabel(tryEnd); final Label catchStart = new Label(); mv.visitLabel(catchStart); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/ScriptBytecodeAdapter", "unwrap", "(Lgroovy/lang/GroovyRuntimeException;)Ljava/lang/Throwable;"); mv.visitInsn(Opcodes.ATHROW); mv.visitTryCatchBlock(tryStart, tryEnd, catchStart, GRE); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } public static void genCallWithFixedParams(ClassWriter cw, String name, final String superClass, CachedMethod cachedMethod, String receiverType ) { if (cachedMethod.getParamsCount() > 4) return; StringBuilder pdescb = new StringBuilder(); final int pc = cachedMethod.getParamsCount(); for (int i = 0; i != pc; ++i) pdescb.append("Ljava/lang/Object;"); writeMethod(cw,name,pc+2,superClass,cachedMethod,receiverType,pdescb.toString(),false); } public static void genCallXxxWithArray(ClassWriter cw, final String name, final String superClass, CachedMethod cachedMethod, String receiverType) { writeMethod(cw,name,3,superClass,cachedMethod,receiverType,"[Ljava/lang/Object;",true); } private static void genConstructor(ClassWriter cw, final String superClass, String internalName) { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "(Lorg/codehaus/groovy/runtime/callsite/CallSite;Lgroovy/lang/MetaClassImpl;Lgroovy/lang/MetaMethod;[Ljava/lang/Class;Ljava/lang/reflect/Constructor;)V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitVarInsn(Opcodes.ALOAD, 3); mv.visitVarInsn(Opcodes.ALOAD, 4); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass, "", "(Lorg/codehaus/groovy/runtime/callsite/CallSite;Lgroovy/lang/MetaClassImpl;Lgroovy/lang/MetaMethod;[Ljava/lang/Class;)V"); mv.visitVarInsn(Opcodes.ALOAD, 5); mv.visitFieldInsn(Opcodes.PUTSTATIC, internalName, "__constructor__", "Ljava/lang/reflect/Constructor;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } public static byte[] genPogoMetaMethodSite(CachedMethod cachedMethod, ClassWriter cw, String name) { String internalName = name.replace('.', '/'); cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, internalName, null, "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", null); cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "__constructor__", "Ljava/lang/reflect/Constructor;", null, null); genConstructor(cw, "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", internalName); genCallXxxWithArray(cw, "Current", "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", cachedMethod, "groovy/lang/GroovyObject"); genCallXxxWithArray(cw, "", "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", cachedMethod, "java/lang/Object"); genCallWithFixedParams(cw, "Current", "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", cachedMethod, "groovy/lang/GroovyObject"); genCallWithFixedParams(cw, "", "org/codehaus/groovy/runtime/callsite/PogoMetaMethodSite", cachedMethod, "java/lang/Object"); cw.visitEnd(); return cw.toByteArray(); } public static byte[] genPojoMetaMethodSite(CachedMethod cachedMethod, ClassWriter cw, String name) { String internalName = name.replace('.', '/'); cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, internalName, null, "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", null); cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "__constructor__", "Ljava/lang/reflect/Constructor;", null, null); genConstructor(cw, "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", internalName); genCallXxxWithArray(cw, "", "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", cachedMethod, "java/lang/Object"); genCallWithFixedParams(cw, "", "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", cachedMethod, "java/lang/Object"); cw.visitEnd(); return cw.toByteArray(); } public static byte[] genStaticMetaMethodSite(CachedMethod cachedMethod, ClassWriter cw, String name) { String internalName = name.replace('.', '/'); cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, internalName, null, "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", null); cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "__constructor__", "Ljava/lang/reflect/Constructor;", null, null); genConstructor(cw, "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", internalName); genCallXxxWithArray(cw, "", "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", cachedMethod, "java/lang/Object"); genCallXxxWithArray(cw, "Static", "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", cachedMethod, "java/lang/Class"); genCallWithFixedParams(cw, "", "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", cachedMethod, "java/lang/Object"); genCallWithFixedParams(cw, "Static", "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", cachedMethod, "java/lang/Class"); cw.visitEnd(); return cw.toByteArray(); } public static Constructor compilePogoMethod(CachedMethod cachedMethod) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final CachedClass declClass = cachedMethod.getDeclaringClass(); final CallSiteClassLoader callSiteLoader = declClass.getCallSiteLoader(); final String name = callSiteLoader.createClassName(cachedMethod.setAccessible()); final byte[] bytes = genPogoMetaMethodSite(cachedMethod, cw, name); return callSiteLoader.defineClassAndGetConstructor(name, bytes); } public static Constructor compilePojoMethod(CachedMethod cachedMethod) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final CachedClass declClass = cachedMethod.getDeclaringClass(); final CallSiteClassLoader callSiteLoader = declClass.getCallSiteLoader(); final String name = callSiteLoader.createClassName(cachedMethod.setAccessible()); final byte[] bytes = genPojoMetaMethodSite(cachedMethod, cw, name); return callSiteLoader.defineClassAndGetConstructor(name, bytes); } public static Constructor compileStaticMethod(CachedMethod cachedMethod) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final CachedClass declClass = cachedMethod.getDeclaringClass(); final CallSiteClassLoader callSiteLoader = declClass.getCallSiteLoader(); final String name = callSiteLoader.createClassName(cachedMethod.setAccessible()); final byte[] bytes = genStaticMetaMethodSite(cachedMethod, cw, name); return callSiteLoader.defineClassAndGetConstructor(name, bytes); } public static boolean isCompilable (CachedMethod method) { return GroovySunClassLoader.sunVM != null || Modifier.isPublic(method.cachedClass.getModifiers()) && method.isPublic() && publicParams(method); } private static boolean publicParams(CachedMethod method) { for (Class nativeParamType : method.getNativeParameterTypes()) { if (!Modifier.isPublic(nativeParamType.getModifiers())) return false; } return true; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/MetaMethodSite.java0000644001501200150120000000217311627206700027021 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.MetaClass; import groovy.lang.MetaMethod; /** * Call site which caches meta method * * @author Alex Tkachman */ public abstract class MetaMethodSite extends MetaClassSite { final MetaMethod metaMethod; protected final Class [] params; public MetaMethodSite(CallSite site, MetaClass metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass); this.metaMethod = metaMethod; this.params = params; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PogoInterceptableSite.java0000644001501200150120000000367211627206700030405 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; /** * Call site for GroovyInterceptable * * @author Alex Tkachman */ public class PogoInterceptableSite extends AbstractCallSite { public PogoInterceptableSite(CallSite site) { super(site); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return ((GroovyObject)receiver).invokeMethod(name, InvokerHelper.asUnwrappedArray(args)); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } public final Object call(Object receiver, Object[] args) throws Throwable { if(receiver instanceof GroovyObject) { try { return ((GroovyObject) receiver).invokeMethod(name, InvokerHelper.asUnwrappedArray(args)); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } public Object callCurrent (GroovyObject receiver, Object [] args) throws Throwable { return call(receiver, args); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PojoMetaClassGetPropertySite.java0000644001501200150120000000307711627206700031707 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; public class PojoMetaClassGetPropertySite extends AbstractCallSite { public PojoMetaClassGetPropertySite(CallSite parent) { super(parent); } public final CallSite acceptGetProperty(Object receiver) { return this; } public final Object getProperty(Object receiver) throws Throwable { try { return InvokerHelper.getProperty(receiver, name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } public Object callGetProperty(Object receiver) throws Throwable { try { return InvokerHelper.getProperty(receiver, name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite.java0000644001501200150120000002516611707612046027663 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.NullObject; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * POJO call site * meta class - cached * method - cached * * @author Alex Tkachman */ public class PojoMetaMethodSite extends MetaMethodSite { protected final int version; public PojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); version = metaClass.getVersion(); } public Object invoke(Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); return metaMethod.doMethodInvoke(receiver, args); } public Object call(Object receiver, Object[] args) throws Throwable { if(checkCall(receiver, args)) return invoke(receiver,args); else return CallSiteArray.defaultCall(this, receiver, args); } protected final boolean checkPojoMetaClass() { return !GroovyCategorySupport.hasCategoryInCurrentThread() && ((MetaClassImpl)metaClass).getVersion() == version; } protected final boolean checkCall(Object receiver, Object[] args) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params, args); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject(), args); throw e; } } protected final boolean checkCall(Object receiver) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject()); throw e; } } protected final boolean checkCall(Object receiver, Object arg1) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params, arg1); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject(), arg1); throw e; } } protected final boolean checkCall(Object receiver, Object arg1, Object arg2) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params, arg1, arg2); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject(), arg1, arg2); throw e; } } protected final boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params, arg1, arg2, arg3); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject(), arg1, arg2, arg3); throw e; } } protected final boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) { try { return receiver.getClass() == metaClass.getTheClass() // meta class match receiver && checkPojoMetaClass() && MetaClassHelper.sameClasses(params, arg1, arg2, arg3, arg4); } catch (NullPointerException e) { if (receiver == null) return checkCall(NullObject.getNullObject(), arg1, arg2, arg3, arg4); throw e; } } public static CallSite createPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (metaMethod instanceof CallSiteAwareMetaMethod) { return ((CallSiteAwareMetaMethod)metaMethod).createPojoCallSite(site, metaClass, metaMethod, params, receiver, args); } if (metaMethod.getClass() == CachedMethod.class) return createCachedMethodSite (site, metaClass, (CachedMethod) metaMethod, params, args); return createNonAwareCallSite(site, metaClass, metaMethod, params, args); } public static CallSite createCachedMethodSite(CallSite site, MetaClassImpl metaClass, CachedMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(metaMethod,args)) return new PojoCachedMethodSiteNoUnwrap(site, metaClass, metaMethod, params); else return metaMethod.createPojoMetaMethodSite(site, metaClass, params); } } return new PojoCachedMethodSite(site, metaClass, metaMethod, params); } public static CallSite createNonAwareCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(metaMethod,args)) return new PojoMetaMethodSiteNoUnwrap(site, metaClass, metaMethod, params); else return new PojoMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, metaMethod, params); } } return new PojoMetaMethodSite(site, metaClass, metaMethod, params); } public static class PojoCachedMethodSite extends PojoMetaMethodSite { final Method reflect; public PojoCachedMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); reflect = ((CachedMethod)metaMethod).setAccessible(); } public Object invoke(Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); args = metaMethod.coerceArgumentsToClasses(args); try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } public static class PojoCachedMethodSiteNoUnwrap extends PojoCachedMethodSite { public PojoCachedMethodSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { args = metaMethod.coerceArgumentsToClasses(args); try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } public static class PojoCachedMethodSiteNoUnwrapNoCoerce extends PojoCachedMethodSite { public PojoCachedMethodSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return reflect.invoke(receiver, args); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof GroovyRuntimeException) { throw ScriptBytecodeAdapter.unwrap ((GroovyRuntimeException) cause); } else { throw cause; } } } } /** * Call site where we know there is no need to unwrap arguments */ public static class PojoMetaMethodSiteNoUnwrap extends PojoMetaMethodSite { public PojoMetaMethodSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } /** * Call site where we know there is no need neither unwrap nor coerce arguments */ public static class PojoMetaMethodSiteNoUnwrapNoCoerce extends PojoMetaMethodSite { public PojoMetaMethodSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/MetaClassSite.java0000644001501200150120000000176711627206700026656 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.MetaClass; /** * Call site which holds reference to meta class * * @author Alex Tkachman */ public abstract class MetaClassSite extends AbstractCallSite { protected final MetaClass metaClass; public MetaClassSite(CallSite site, MetaClass metaClass) { super(site); this.metaClass = metaClass; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/CallSiteClassLoader.java0000644001501200150120000000376211627206700027767 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.reflection.ClassLoaderForClassArtifacts; import java.util.Set; import java.util.HashSet; import java.util.Collections; public class CallSiteClassLoader extends ClassLoaderForClassArtifacts { private static final Set KNOWN_CLASSES = new HashSet(); static { Collections.addAll(KNOWN_CLASSES , "org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite" , "org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite" , "org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite" , "org.codehaus.groovy.runtime.callsite.CallSite" , "org.codehaus.groovy.runtime.callsite.CallSiteArray" , "groovy.lang.MetaMethod" , "groovy.lang.MetaClassImpl" ); } public CallSiteClassLoader(Class klazz) { super(klazz); } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (KNOWN_CLASSES.contains(name)) return getClass().getClassLoader().loadClass(name); else { try { return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { return getClass().getClassLoader().loadClass(name); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite.java0000644001501200150120000001444611627206700030177 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.reflection.CachedMethod; /** * POJO call site * meta class - cached * method - cached * * @author Alex Tkachman */ public class StaticMetaMethodSite extends MetaMethodSite { private final int version; public StaticMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); version = metaClass.getVersion (); } public Object invoke(Object receiver, Object[] args) throws Throwable { MetaClassHelper.unwrap(args); try { return metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } protected final boolean checkCall(Object receiver, Object[] args) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, args); } protected final boolean checkCall(Object receiver) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params); } protected final boolean checkCall(Object receiver, Object arg1) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1); } protected final boolean checkCall(Object receiver, Object arg1, Object arg2) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2); } protected final boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2, arg3); } protected final boolean checkCall(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, arg1, arg2, arg3, arg4); } public Object call(Object receiver, Object[] args) throws Throwable { if(checkCall(receiver, args)) { try { return invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } public Object callStatic(Class receiver, Object[] args) throws Throwable { if(checkCall(receiver, args)) return invoke(receiver, args); else return CallSiteArray.defaultCallStatic(this, receiver, args); } public static CallSite createStaticMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object[] args) { if (metaMethod.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(metaMethod,args)) return new StaticMetaMethodSiteNoUnwrap(site, metaClass, metaMethod, params); else if (metaMethod.getClass() == CachedMethod.class) return ((CachedMethod)metaMethod).createStaticMetaMethodSite(site, metaClass, params); else return new StaticMetaMethodSiteNoUnwrapNoCoerce (site, metaClass, metaMethod, params); } } return new StaticMetaMethodSite(site, metaClass, metaMethod, params); } /** * Call site where we know there is no need to unwrap arguments */ public static class StaticMetaMethodSiteNoUnwrap extends StaticMetaMethodSite { public StaticMetaMethodSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.doMethodInvoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } /** * Call site where we know there is no need neither unwrap nor coerce arguments */ public static class StaticMetaMethodSiteNoUnwrapNoCoerce extends StaticMetaMethodSite { public StaticMetaMethodSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class params[]) { super(site, metaClass, metaMethod, params); } public final Object invoke(Object receiver, Object[] args) throws Throwable { try { return metaMethod.invoke(receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/ConstructorMetaMethodSite.java0000644001501200150120000000446511627206700031275 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; /** * Call site for invoking static methods * meta class - cached * method - not cached * * @author Alex Tkachman */ public class ConstructorMetaMethodSite extends MetaMethodSite { private final int version; public ConstructorMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod method, Class [] params) { super(site, metaClass, method, params); this.version = metaClass.getVersion(); } public final Object invoke(Object receiver, Object [] args) throws Throwable{ MetaClassHelper.unwrap(args); try { return metaMethod.doMethodInvoke(metaClass.getTheClass(), args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } public final Object callConstructor(Object receiver, Object[] args) throws Throwable { if (receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl)metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, args) ) { MetaClassHelper.unwrap(args); try { return metaMethod.doMethodInvoke(metaClass.getTheClass(), args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallConstructor(this, receiver, args); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/MetaClassConstructorSite.java0000644001501200150120000000344411627206700031116 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; /** * Call site for constructor * meta class - cached * method - not cached * * @author Alex Tkachman */ public class MetaClassConstructorSite extends MetaClassSite { private final ClassInfo classInfo; private final int version; public MetaClassConstructorSite(CallSite site, MetaClass metaClass) { super(site, metaClass); classInfo = ClassInfo.getClassInfo(metaClass.getTheClass()); version = classInfo.getVersion(); } public Object callConstructor(Object receiver, Object[] args) throws Throwable { try { if (receiver == metaClass.getTheClass() && version == classInfo.getVersion()) // metaClass still be valid return metaClass.invokeConstructor(args); else return CallSiteArray.defaultCallConstructor(this, receiver, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.java0000644001501200150120000000662711627206700031734 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import groovy.lang.MetaProperty; import groovy.lang.GroovyObject; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; /** * Created by IntelliJ IDEA. * User: applerestore * Date: May 21, 2008 * Time: 10:37:37 AM * To change this template use File | Settings | File Templates. */ class GetEffectivePogoPropertySite extends AbstractCallSite { private final MetaClass metaClass; private final MetaProperty effective; public GetEffectivePogoPropertySite(CallSite site, MetaClass metaClass, MetaProperty effective) { super(site); this.metaClass = metaClass; this.effective = effective; } public final Object callGetProperty (Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject) receiver).getMetaClass() != metaClass) { return createGetPropertySite(receiver).getProperty(receiver); } else { try { return effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } public final CallSite acceptGetProperty(Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) { return createGetPropertySite(receiver); } else { return this; } } public final Object callGroovyObjectGetProperty (Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject) receiver).getMetaClass() != metaClass) { return createGetPropertySite(receiver).getProperty(receiver); } else { try { return effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } public final CallSite acceptGroovyObjectGetProperty(Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) { return createGroovyObjectGetPropertySite(receiver); } else { return this; } } public final Object getProperty(Object receiver) throws Throwable { try { return effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PogoGetPropertySite.java0000644001501200150120000000323611627206700030104 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; public class PogoGetPropertySite extends AbstractCallSite { private final Class aClass; public PogoGetPropertySite(CallSite parent, Class aClass) { super(parent); this.aClass = aClass; } public CallSite acceptGetProperty(Object receiver) { if (receiver.getClass() != aClass) return createGetPropertySite(receiver); else return this; } public CallSite acceptGroovyObjectGetProperty(Object receiver) { if (receiver.getClass() != aClass) return createGroovyObjectGetPropertySite(receiver); else return this; } public Object getProperty(Object receiver) throws Throwable { try{ return ((GroovyObject)receiver).getProperty(name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/ConstructorMetaClassSite.java0000644001501200150120000000262411627206700031115 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; public class ConstructorMetaClassSite extends MetaClassSite { public ConstructorMetaClassSite(CallSite site, MetaClass metaClass) { super(site, metaClass); } public Object callConstructor(Object receiver, Object[] args) throws Throwable { if (receiver == metaClass.getTheClass()) { try { return metaClass.invokeConstructor(args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallConstructor(this, (Class)receiver, args); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/StaticMetaClassSite.java0000644001501200150120000000452211627206700030016 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; /** * Call site for invoking static methods * meta class - cached * method - not cached * * @author Alex Tkachman */ public class StaticMetaClassSite extends MetaClassSite { private final ClassInfo classInfo; private final int version; public StaticMetaClassSite(CallSite site, MetaClass metaClass) { super(site, metaClass); classInfo = ClassInfo.getClassInfo(metaClass.getTheClass()); version = classInfo.getVersion(); } private boolean checkCall(Object receiver) { return receiver == metaClass.getTheClass() && version == classInfo.getVersion(); // metaClass still be valid } public final Object call(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver)) { try { return metaClass.invokeStaticMethod(receiver, name, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } public final Object callStatic(Class receiver, Object[] args) throws Throwable { if (checkCall(receiver)) { try { return metaClass.invokeStaticMethod(receiver, name, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallStatic(this, receiver, args); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/ConstructorSite.java0000644001501200150120000001436511707612046027330 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import org.codehaus.groovy.reflection.CachedConstructor; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import java.util.Map; public class ConstructorSite extends MetaClassSite { final CachedConstructor constructor; final Class[] params; private final int version; public ConstructorSite(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class params[]) { super(site, metaClass); this.constructor = constructor; this.params = params; this.version = metaClass.getVersion(); } public Object callConstructor(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver, args)) { MetaClassHelper.unwrap(args); try { return constructor.doConstructorInvoke(args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else return CallSiteArray.defaultCallConstructor(this, receiver, args); } protected final boolean checkCall(Object receiver, Object[] args) { return receiver == metaClass.getTheClass() // meta class match receiver && ((MetaClassImpl) metaClass).getVersion() == version // metaClass still be valid && MetaClassHelper.sameClasses(params, args); } public static ConstructorSite createConstructorSite(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class[] params, Object[] args) { if (constructor.correctArguments(args) == args) { if (noWrappers(args)) { if (noCoerce(constructor, args)) return new ConstructorSiteNoUnwrap(site, metaClass, constructor, params); else return new ConstructorSiteNoUnwrapNoCoerce(site, metaClass, constructor, params); } } return new ConstructorSite(site, metaClass, constructor, params); } /** * Call site where we know there is no need to unwrap arguments */ public static class ConstructorSiteNoUnwrap extends ConstructorSite { public ConstructorSiteNoUnwrap(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class params[]) { super(site, metaClass, constructor, params); } public final Object callConstructor(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver, args)) { try { return constructor.doConstructorInvoke(args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else return CallSiteArray.defaultCallConstructor(this, receiver, args); } } /** * Call site where we know there is no need neither unwrap nor coerce arguments */ public static class ConstructorSiteNoUnwrapNoCoerce extends ConstructorSite { public ConstructorSiteNoUnwrapNoCoerce(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class params[]) { super(site, metaClass, constructor, params); } public Object callConstructor(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver, args)) { try { return constructor.invoke(args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else return CallSiteArray.defaultCallConstructor(this, receiver, args); } } public static class NoParamSite extends ConstructorSiteNoUnwrapNoCoerce { private static final Object[] NO_ARGS = new Object[0]; public NoParamSite(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class[] params) { super(site, metaClass, constructor, params); } public final Object callConstructor(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver, args)) { final Object bean = constructor.invoke(NO_ARGS); try { ((MetaClassImpl) metaClass).setProperties(bean, (Map) args[0]); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } return bean; } else return CallSiteArray.defaultCallConstructor(this, receiver, args); } } public static class NoParamSiteInnerClass extends ConstructorSiteNoUnwrapNoCoerce { private static final Object[] NO_ARGS = new Object[0]; public NoParamSiteInnerClass(CallSite site, MetaClassImpl metaClass, CachedConstructor constructor, Class[] params) { super(site, metaClass, constructor, params); } public final Object callConstructor(Object receiver, Object[] args) throws Throwable { if (checkCall(receiver, args)) { final Object[] newArgs = new Object[] {args[0]}; final Object bean = constructor.invoke(newArgs); try { ((MetaClassImpl) metaClass).setProperties(bean, (Map) args[1]); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } return bean; } else return CallSiteArray.defaultCallConstructor(this, receiver, args); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePojoFieldSite.java0000644001501200150120000000405611627206700031130 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaClassImpl; import java.lang.reflect.Field; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.runtime.GroovyCategorySupport; class GetEffectivePojoFieldSite extends AbstractCallSite { private final MetaClassImpl metaClass; private final Field effective; private final int version; public GetEffectivePojoFieldSite(CallSite site, MetaClassImpl metaClass, CachedField effective) { super(site); this.metaClass = metaClass; this.effective = effective.field; version = metaClass.getVersion(); } // public final Object callGetProperty (Object receiver) throws Throwable { // return acceptGetProperty(receiver).getProperty(receiver); // } public final CallSite acceptGetProperty(Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || receiver.getClass() != metaClass.getTheClass() || version != metaClass.getVersion()) { // metaClass is invalid return createGetPropertySite(receiver); } else { return this; } } public final Object getProperty(Object receiver) { try { return effective.get(receiver); } catch (IllegalAccessException e) { throw new GroovyRuntimeException("Cannot get the property '" + name + "'.", e); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/CallSiteArray.java0000644001501200150120000001437411715031256026652 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.MetaClass; import groovy.lang.MetaClassImpl; import groovy.lang.GroovyInterceptable; import groovy.lang.GroovyObject; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.reflection.ClassInfo; public final class CallSiteArray { public final CallSite[] array; public static final Object [] NOPARAM = new Object[0]; public final Class owner; public CallSiteArray(Class owner, String [] names) { this.owner = owner; array = new CallSite[names.length]; for (int i = 0; i < array.length; i++) { array[i] = new AbstractCallSite(this, i, names[i]); } } public static Object defaultCall(CallSite callSite, Object receiver, Object[] args) throws Throwable { return createCallSite(callSite, receiver, args).call(receiver, args); } public static Object defaultCallCurrent(CallSite callSite, GroovyObject receiver, Object[] args) throws Throwable { return createCallCurrentSite(callSite, receiver, args, callSite.getArray().owner).callCurrent(receiver, args); } public static Object defaultCallStatic(CallSite callSite, Class receiver, Object[] args) throws Throwable { return createCallStaticSite(callSite, receiver, args).callStatic(receiver,args); } public static Object defaultCallConstructor(CallSite callSite, Object receiver, Object[] args) throws Throwable { return createCallConstructorSite(callSite, (Class) receiver, args).callConstructor(receiver, args); } private static CallSite createCallStaticSite(CallSite callSite, Class receiver, Object[] args) { CallSite site; MetaClass metaClass = InvokerHelper.getMetaClass(receiver); if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createStaticSite(callSite, args); } else site = new StaticMetaClassSite(callSite, metaClass); replaceCallSite(callSite, site); return site; } private static CallSite createCallConstructorSite(CallSite callSite, Class receiver, Object[] args) { MetaClass metaClass = InvokerHelper.getMetaClass(receiver); CallSite site; if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createConstructorSite(callSite, args); } else site = new MetaClassConstructorSite(callSite, metaClass); replaceCallSite(callSite, site); return site; } private static CallSite createCallCurrentSite(CallSite callSite, GroovyObject receiver, Object[] args, Class sender) { CallSite site; if (receiver instanceof GroovyInterceptable) site = new PogoInterceptableSite(callSite); else { MetaClass metaClass = receiver.getMetaClass(); if (receiver.getClass() != metaClass.getTheClass() && !metaClass.getTheClass().isInterface()) { site = new PogoInterceptableSite(callSite); } else if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createPogoCallCurrentSite(callSite, sender, args); } else site = new PogoMetaClassSite(callSite, metaClass); } replaceCallSite(callSite, site); return site; } // for MetaClassImpl we try to pick meta method, // otherwise or if method doesn't exist we make call via POJO meta class private static CallSite createPojoSite(CallSite callSite, Object receiver, Object[] args) { final Class klazz = receiver.getClass(); MetaClass metaClass = InvokerHelper.getMetaClass(receiver); if (!GroovyCategorySupport.hasCategoryInCurrentThread() && metaClass instanceof MetaClassImpl) { final MetaClassImpl mci = (MetaClassImpl) metaClass; final ClassInfo info = mci.getTheCachedClass().classInfo; if (info.hasPerInstanceMetaClasses()) { return new PerInstancePojoMetaClassSite(callSite, info); } else { return mci.createPojoCallSite(callSite, receiver, args); } } ClassInfo info = ClassInfo.getClassInfo(klazz); if (info.hasPerInstanceMetaClasses()) return new PerInstancePojoMetaClassSite(callSite, info); else return new PojoMetaClassSite(callSite, metaClass); } private static CallSite createPogoSite(CallSite callSite, Object receiver, Object[] args) { if (receiver instanceof GroovyInterceptable) return new PogoInterceptableSite(callSite); MetaClass metaClass = ((GroovyObject)receiver).getMetaClass(); if (metaClass instanceof MetaClassImpl) { return ((MetaClassImpl)metaClass).createPogoCallSite(callSite, args); } return new PogoMetaClassSite(callSite, metaClass); } private static CallSite createCallSite(CallSite callSite, Object receiver, Object[] args) { CallSite site; if (receiver == null) return new NullCallSite(callSite); if (receiver instanceof Class) site = createCallStaticSite(callSite, (Class) receiver, args); else if (receiver instanceof GroovyObject) { site = createPogoSite(callSite, receiver, args); } else { site = createPojoSite(callSite, receiver, args); } replaceCallSite(callSite, site); return site; } private static void replaceCallSite(CallSite oldSite, CallSite newSite) { oldSite.getArray().array [oldSite.getIndex()] = newSite; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/NullCallSite.java0000644001501200150120000000351511627206700026501 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.NullObject; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; public final class NullCallSite extends AbstractCallSite { public NullCallSite(CallSite callSite) { super(callSite); } public Object call(Object receiver, Object[] args) throws Throwable { if (receiver == null) { try{ return CallSiteArray.defaultCall(this, NullObject.getNullObject(), args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } public Object getProperty(Object receiver) throws Throwable { if (receiver == null) { try{ return InvokerHelper.getProperty(NullObject.getNullObject(), name); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return acceptGetProperty(receiver).getProperty(receiver); } } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/GetEffectivePogoFieldSite.java0000644001501200150120000000565311627206700031131 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.MetaClass; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import java.lang.reflect.Field; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.runtime.GroovyCategorySupport; public class GetEffectivePogoFieldSite extends AbstractCallSite { private final MetaClass metaClass; private final Field effective; public GetEffectivePogoFieldSite(CallSite site, MetaClass metaClass, CachedField effective) { super(site); this.metaClass = metaClass; this.effective = effective.field; } public final Object callGetProperty (Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject) receiver).getMetaClass() != metaClass) { return createGetPropertySite(receiver).getProperty(receiver); } else { return getProperty(receiver); } } public final CallSite acceptGetProperty(Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) { return createGetPropertySite(receiver); } else { return this; } } public final Object callGroovyObjectGetProperty (Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || ((GroovyObject) receiver).getMetaClass() != metaClass) { return createGroovyObjectGetPropertySite(receiver).getProperty(receiver); } else { return getProperty(receiver); } } public final CallSite acceptGroovyObjectGetProperty(Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != metaClass) { return createGroovyObjectGetPropertySite(receiver); } else { return this; } } public final Object getProperty(Object receiver) { try { return effective.get(receiver); } catch (IllegalAccessException e) { throw new GroovyRuntimeException("Cannot get the property '" + name + "'.", e); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/PerInstancePojoMetaClassSite.java0000644001501200150120000000301311627206700031624 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.reflection.ClassInfo; public class PerInstancePojoMetaClassSite extends AbstractCallSite{ private final ClassInfo info; public PerInstancePojoMetaClassSite(CallSite site, ClassInfo info) { super(site); this.info = info; } public Object call(Object receiver, Object[] args) throws Throwable { if (info.hasPerInstanceMetaClasses()) { try { return InvokerHelper.getMetaClass(receiver).invokeMethod(receiver, name, args); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCall(this, receiver, args); } } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/callsite/CallSite.java0000644001501200150120000000706611707612046025656 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyObject; public interface CallSite { CallSiteArray getArray(); int getIndex(); String getName(); Object getProperty(Object receiver) throws Throwable; Object callGetPropertySafe (Object receiver) throws Throwable; Object callGetProperty (Object receiver) throws Throwable; Object callGroovyObjectGetProperty (Object receiver) throws Throwable; Object callGroovyObjectGetPropertySafe (Object receiver) throws Throwable; Object call (Object receiver, Object[] args) throws Throwable; Object call (Object receiver) throws Throwable; Object call (Object receiver, Object arg1) throws Throwable; Object call (Object receiver, Object arg1, Object arg2) throws Throwable; Object call (Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable; Object call (Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable; Object callSafe (Object receiver, Object[] args) throws Throwable; Object callSafe (Object receiver) throws Throwable; Object callSafe (Object receiver, Object arg1) throws Throwable; Object callSafe (Object receiver, Object arg1, Object arg2) throws Throwable; Object callSafe (Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable; Object callSafe (Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable; Object callCurrent (GroovyObject receiver, Object [] args) throws Throwable; Object callCurrent (GroovyObject receiver) throws Throwable; Object callCurrent (GroovyObject receiver, Object arg1) throws Throwable; Object callCurrent (GroovyObject receiver, Object arg1, Object arg2) throws Throwable; Object callCurrent (GroovyObject receiver, Object arg1, Object arg2, Object arg3) throws Throwable; Object callCurrent (GroovyObject receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable; Object callStatic (Class receiver, Object [] args) throws Throwable; Object callStatic (Class receiver) throws Throwable; Object callStatic (Class receiver, Object arg1) throws Throwable; Object callStatic (Class receiver, Object arg1, Object arg2) throws Throwable; Object callStatic (Class receiver, Object arg1, Object arg2, Object arg3) throws Throwable; Object callStatic (Class receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable; Object callConstructor (Object receiver, Object [] args) throws Throwable; Object callConstructor (Object receiver) throws Throwable; Object callConstructor (Object receiver, Object arg1) throws Throwable; Object callConstructor (Object receiver, Object arg1, Object arg2) throws Throwable; Object callConstructor (Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable; Object callConstructor (Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable; } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ConvertedClosure.java0000644001501200150120000000333611627206700025635 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.io.Serializable; import java.lang.reflect.Method; /** * This class is a general adapter to adapt a closure to any Java interface. *

      * @author Ben Yu * @author Jochen Theodorou * Jul 27, 2006 3:50:51 PM */ public class ConvertedClosure extends ConversionHandler implements Serializable { private String methodName; private static final long serialVersionUID = 1162833713450835227L; /** * to create a ConvertedClosure object. * @param closure the closure object. */ public ConvertedClosure(Closure closure, String method) { super(closure); this.methodName = method; } public ConvertedClosure(Closure closure) { this(closure,null); } public Object invokeCustom(Object proxy, Method method, Object[] args) throws Throwable { if (methodName!=null && !methodName.equals(method.getName())) return null; return ((Closure) getDelegate()).call(args); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ScriptReference.java0000644001501200150120000000243311627206700025427 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Reference; import groovy.lang.Script; /** * Represents a reference to a variable in a script * * @author James Strachan * @version $Revision$ */ public class ScriptReference extends Reference { private Script script; private String variable; public ScriptReference(Script script, String variable) { this.script = script; this.variable = variable; } public Object get() { return script.getBinding().getVariable(variable); } public void set(Object value) { script.getBinding().setVariable(variable, value); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/BytecodeInterface8.java0000644001501200150120000002315711707612046026024 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo; /** * This class contains methods special to optimizations used directly from bytecode in Groovy 1.8 * @author Jochen "blackdrag" Theodorou */ public class BytecodeInterface8 { public static boolean disabledStandardMetaClass() { return DefaultMetaClassInfo.disabledStandardMetaClass(); } // ------------------ int ------------------ /** * @return true if integer has its default MetaClass */ public static boolean isOrigInt(){ return DefaultMetaClassInfo.isOrigInt(); } // ------------------ int[] ------------------ /** * @return true if integer array has its default MetaClass */ public static boolean isOrigIntArray(){ return DefaultMetaClassInfo.isOrigIntArray(); } /** * get value from int[] using normalized index */ public static int intArrayGet(int[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from int[] using normalized index */ public static void intArraySet(int[] a, int i, int v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ byte ------------------ /** * @return true if byte has its default MetaClass */ public static boolean isOrigB(){ return DefaultMetaClassInfo.isOrigByte(); } // ------------------ byte[] ------------------ /** * @return true if byte array has its default MetaClass */ public static boolean isOrigBArray(){ return false; } /** * get value from byte[] using normalized index */ public static byte bArrayGet(byte[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from byte[] using normalized index */ public static void bArraySet(byte[] a, int i, byte v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ short ------------------ /** * @return true if short has its default MetaClass */ public static boolean isOrigS(){ return DefaultMetaClassInfo.isOrigShort(); } // ------------------ short[] ------------------ /** * @return true if short array has its default MetaClass */ public static boolean isOrigSArray(){ return false; } /** * get value from short[] using normalized index */ public static short sArrayGet(short[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from short[] using normalized index */ public static void sArraySet(short[] a, int i, short v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ char ------------------ /** * @return true if char has its default MetaClass */ public static boolean isOrigC(){ return DefaultMetaClassInfo.isOrigChar(); } // ------------------ char[] ------------------ /** * @return true if char array has its default MetaClass */ public static boolean isOrigCArray(){ return false; } /** * get value from char[] using normalized index */ public static char cArrayGet(char[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from char[] using normalized index */ public static void cArraySet(char[] a, int i, char v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ long ------------------ /** * @return true if long has its default MetaClass */ public static boolean isOrigL(){ return DefaultMetaClassInfo.isOrigLong(); } // ------------------ long[] ------------------ /** * @return true if long array has its default MetaClass */ public static boolean isOrigLArray(){ return false; } /** * get value from long[] using normalized index */ public static long lArrayGet(long[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from long[] using normalized index */ public static void lArraySet(long[] a, int i, long v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ boolean ------------------ /** * @return true if boolean has its default MetaClass */ public static boolean isOrigZ(){ return DefaultMetaClassInfo.isOrigBool(); } // ------------------ boolean[] ------------------ /** * @return true if boolean array has its default MetaClass */ public static boolean isOrigZArray(){ return false; } /** * get value from boolean[] using normalized index */ public static boolean zArrayGet(boolean[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from boolean[] using normalized index */ public static void zArraySet(boolean[] a, int i, boolean v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ float ------------------ /** * @return true if float has its default MetaClass */ public static boolean isOrigF(){ return DefaultMetaClassInfo.isOrigFloat(); } // ------------------ float[] ------------------ /** * @return true if float array has its default MetaClass */ public static boolean isOrigFArray(){ return false; } /** * get value from float[] using normalized index */ public static float fArrayGet(float[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from float[] using normalized index */ public static void fArraySet(float[] a, int i, float v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ double ------------------ /** * @return true if double has its default MetaClass */ public static boolean isOrigD(){ return DefaultMetaClassInfo.isOrigDouble(); } // ------------------ double[] ------------------ /** * @return true if double array has its default MetaClass */ public static boolean isOrigDArray(){ return false; } /** * get value from double[] using normalized index */ public static double dArrayGet(double[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from double[] using normalized index */ public static void dArraySet(double[] a, int i, double v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } // ------------------ Object[] ------------------ public static Object objectArrayGet(Object[] a, int i) { try { return a[i]; } catch (Throwable t) { return a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]; } } /** * set value from double[] using normalized index */ public static void objectArraySet(Object[] a, int i, Object v) { try { a[i]=v; } catch (Throwable t) { a[DefaultGroovyMethodsSupport.normaliseIndex(i,a.length)]=v; } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/NullObject.java0000644001501200150120000001006611715031256024406 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.util.Collections; import java.util.Iterator; import groovy.lang.GroovyObjectSupport; public class NullObject extends GroovyObjectSupport { private static final NullObject INSTANCE = new NullObject(); /** * private constructor */ private NullObject() { } /** * get the NullObject reference * * @return the null object */ public static NullObject getNullObject() { return INSTANCE; } /** * Since this is implemented as a singleton, we should avoid the * use of the clone method */ public Object clone() { throw new NullPointerException("Cannot invoke method clone() on null object"); } /** * Tries to get a property on null, which will always fail * * @param property - the property to get * @return a NPE */ public Object getProperty(String property) { throw new NullPointerException("Cannot get property '" + property + "' on null object"); } /** * Tries to set a property on null, which will always fail * * @param property - the proprty to set * @param newValue - the new value of the property */ public void setProperty(String property, Object newValue) { throw new NullPointerException("Cannot set property '" + property + "' on null object"); } /** * Tries to invoke a method on null, which will always fail * * @param name the name of the method to invoke * @param args - arguments to the method * @return a NPE */ public Object invokeMethod(String name, Object args) { throw new NullPointerException("Cannot invoke method " + name + "() on null object"); } /** * null is only equal to null * * @param to - the reference object with which to compare * @return - true if this object is the same as the to argument */ public boolean equals(Object to) { return to == null; } /** * iterator() method to be able to iterate on null. * Note: this part is from Invoker * * @return an iterator for an empty list */ public Iterator iterator() { return Collections.EMPTY_LIST.iterator(); } /** * Allows to add a String to null. * The result is concatenated String of the result of calling * toString() on this object and the String in the parameter. * * @param s - the String to concatenate * @return the concatenated string */ public Object plus(String s) { return getMetaClass().invokeMethod(this, "toString", new Object[]{}) + s; } /** * The method "is" is used to test for equal references. * This method will return true only if the given parameter * is null * * @param other - the object to test * @return true if other is null */ public boolean is(Object other) { return other == null; } /** * Type conversion method for null. * * @param c - the class to convert to * @return always null */ public Object asType(Class c) { return null; } /** * A null object always coerces to false. * * @return false */ public boolean asBoolean() { return false; } public String toString() { return "null"; } public int hashCode() { throw new NullPointerException("Cannot invoke method hashCode() on null object"); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/RegexSupport.java0000644001501200150120000000202511627206700025010 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import java.util.regex.Matcher; /** * Used to store the last regex match. */ public class RegexSupport { private static final ThreadLocal CURRENT_MATCHER = new ThreadLocal(); public static Matcher getLastMatcher() { return (Matcher) CURRENT_MATCHER.get(); } public static void setLastMatcher(Matcher matcher) { CURRENT_MATCHER.set(matcher); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/GroovyCategorySupport.java0000644001501200150120000003056011713765676026750 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.lang.ref.SoftReference; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo; import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * @author sam * @author Paul King * @author Alex Tkachman */ public class GroovyCategorySupport { private static int categoriesInUse = 0; private static AtomicInteger atomicCategoryUsageCounter = new AtomicInteger(); public static class CategoryMethodList extends ArrayList { public final int level; final CategoryMethodList previous; final AtomicInteger usage; public CategoryMethodList(String name, int level, CategoryMethodList previous) { this.level = level; this.previous = previous; if (previous != null) { addAll(previous); usage = previous.usage; } else { usage = getCategoryNameUsage (name); } } public boolean add(CategoryMethod o) { usage.incrementAndGet(); return super.add(o); } } public static class ThreadCategoryInfo extends HashMap{ int level; private Map propertyGetterMap; private Map propertySetterMap; private void newScope () { atomicCategoryUsageCounter.incrementAndGet(); categoriesInUse = atomicCategoryUsageCounter.get(); DefaultMetaClassInfo.setCategoryUsed(true); level++; } private void endScope () { for (Iterator> it = entrySet().iterator(); it.hasNext(); ) { final Map.Entry e = it.next(); final CategoryMethodList list = e.getValue(); if (list.level == level) { final CategoryMethodList prev = list.previous; if (prev == null) { it.remove(); list.usage.addAndGet(-list.size()); } else { e.setValue(prev); list.usage.addAndGet(prev.size()-list.size()); } } } level--; atomicCategoryUsageCounter.getAndDecrement(); categoriesInUse = atomicCategoryUsageCounter.get(); if (categoriesInUse==0) DefaultMetaClassInfo.setCategoryUsed(false); if (level == 0) { THREAD_INFO.remove(); } } private T use(Class categoryClass, Closure closure) { newScope(); try { use(categoryClass); return closure.call(); } finally { endScope(); } } public T use(List categoryClasses, Closure closure) { newScope(); try { for (Class categoryClass : categoryClasses) { use(categoryClass); } return closure.call(); } finally { endScope(); } } private void applyUse(CachedClass cachedClass) { CachedMethod[] methods = cachedClass.getMethods(); for (CachedMethod cachedMethod : methods) { if (cachedMethod.isStatic() && cachedMethod.isPublic()) { CachedClass[] paramTypes = cachedMethod.getParameterTypes(); if (paramTypes.length > 0) { CachedClass metaClass = paramTypes[0]; CategoryMethod mmethod = new CategoryMethod(cachedMethod, metaClass.getTheClass()); final String name = cachedMethod.getName(); CategoryMethodList list = get(name); if (list == null || list.level != level) { list = new CategoryMethodList(name, level, list); put(name, list); } list.add(mmethod); Collections.sort(list); cachePropertyAccessor(mmethod); } } } } private void cachePropertyAccessor(CategoryMethod method) { String name = method.getName(); int parameterLength = method.getParameterTypes().length; if (name.startsWith("get") && name.length() > 3 && parameterLength == 0) { propertyGetterMap = putPropertyAccessor(3, name, propertyGetterMap); } else if (name.startsWith("set") && name.length() > 3 && parameterLength == 1) { propertySetterMap = putPropertyAccessor(3, name, propertySetterMap); } } // Precondition: accessorName.length() > prefixLength private Map putPropertyAccessor(int prefixLength, String accessorName, Map map) { if (map == null) { map = new HashMap(); } String property = accessorName.substring(prefixLength, prefixLength+1).toLowerCase() + accessorName.substring(prefixLength+1); map.put(property, accessorName); return map; } private void use(Class categoryClass) { CachedClass cachedClass = ReflectionCache.getCachedClass(categoryClass); LinkedList classStack = new LinkedList(); for (CachedClass superClass = cachedClass; superClass.getTheClass()!=Object.class; superClass = superClass.getCachedSuperClass()) { classStack.add(superClass); } while (!classStack.isEmpty()) { CachedClass klazz = classStack.removeLast(); applyUse(klazz); } } public CategoryMethodList getCategoryMethods(String name) { return level == 0 ? null : get(name); } String getPropertyCategoryGetterName(String propertyName){ return propertyGetterMap != null ? propertyGetterMap.get(propertyName) : null; } String getPropertyCategorySetterName(String propertyName){ return propertySetterMap != null ? propertySetterMap.get(propertyName) : null; } } private static final MyThreadLocal THREAD_INFO = new MyThreadLocal(); private static class CategoryMethod extends NewInstanceMetaMethod implements Comparable { private final Class metaClass; public CategoryMethod(CachedMethod metaMethod, Class metaClass) { super(metaMethod); this.metaClass = metaClass; } public boolean isCacheable() { return false; } /** * Sort by most specific to least specific. * * @param o the object to compare against */ public int compareTo(Object o) { CategoryMethod thatMethod = (CategoryMethod) o; Class thisClass = metaClass; Class thatClass = thatMethod.metaClass; if (thisClass == thatClass) return 0; if (isChildOfParent(thisClass, thatClass)) return -1; if (isChildOfParent(thatClass, thisClass)) return 1; return 0; } private boolean isChildOfParent(Class candidateChild, Class candidateParent) { Class loop = candidateChild; while(loop != null && loop != Object.class) { loop = loop.getSuperclass(); if (loop == candidateParent) { return true; } } return false; } } public static AtomicInteger getCategoryNameUsage (String name) { return THREAD_INFO.getUsage (name); } /** * Create a scope based on given categoryClass and invoke closure within that scope. * * @param categoryClass the class containing category methods * @param closure the closure during which to make the category class methods available * @return the value returned from the closure */ public static T use(Class categoryClass, Closure closure) { return THREAD_INFO.getInfo().use(categoryClass, closure); } /** * Create a scope based on given categoryClasses and invoke closure within that scope. * * @param categoryClasses the list of classes containing category methods * @param closure the closure during which to make the category class methods available * @return the value returned from the closure */ public static T use(List categoryClasses, Closure closure) { return THREAD_INFO.getInfo().use(categoryClasses, closure); } public static boolean hasCategoryInCurrentThread() { if (categoriesInUse == 0) return false; ThreadCategoryInfo infoNullable = THREAD_INFO.getInfoNullable(); return infoNullable != null && infoNullable.level != 0; } public static boolean hasCategoryInAnyThread() { return atomicCategoryUsageCounter.get() != 0; } /** * This method is used to pull all the new methods out of the local thread context with a particular name. * * @param name the method name of interest * @return the list of methods */ public static CategoryMethodList getCategoryMethods(String name) { final ThreadCategoryInfo categoryInfo = THREAD_INFO.getInfoNullable(); return categoryInfo == null ? null : categoryInfo.getCategoryMethods(name); } public static String getPropertyCategoryGetterName(String propertyName) { final ThreadCategoryInfo categoryInfo = THREAD_INFO.getInfoNullable(); return categoryInfo == null ? null : categoryInfo.getPropertyCategoryGetterName(propertyName); } public static String getPropertyCategorySetterName(String propertyName) { final ThreadCategoryInfo categoryInfo = THREAD_INFO.getInfoNullable(); return categoryInfo == null ? null : categoryInfo.getPropertyCategorySetterName(propertyName); } private static class MyThreadLocal extends ThreadLocal { ConcurrentHashMap usage = new ConcurrentHashMap (); public ThreadCategoryInfo getInfo() { final SoftReference reference = get(); ThreadCategoryInfo tcinfo; if (reference != null) { tcinfo = (ThreadCategoryInfo) reference.get(); if( tcinfo == null ) { tcinfo = new ThreadCategoryInfo(); set(new SoftReference(tcinfo)); } } else { tcinfo = new ThreadCategoryInfo(); set(new SoftReference(tcinfo)); } return tcinfo; } public ThreadCategoryInfo getInfoNullable() { final SoftReference reference = get(); return reference == null ? null : (ThreadCategoryInfo) reference.get(); } public AtomicInteger getUsage (String name) { AtomicInteger u = usage.get(name); if (u != null) { return u; } final AtomicInteger ai = new AtomicInteger(); final AtomicInteger prev = usage.putIfAbsent(name, ai); return prev == null ? ai : prev; } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/GeneratedClosure.java0000644001501200150120000000165311627206700025602 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; /** * Marker interface to identify closures generated by the groovy compiler. * For internal use only! * * @author Jochen Theodorou * @since 1.5 * @see org.codehaus.groovy.runtime.metaclass.ClosureMetaClass */ public interface GeneratedClosure {} groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ComposedClosure.java0000644001501200150120000000620111707612046025452 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.util.List; /** * A wrapper for Closure to support composition. * Normally used only internally through the rightShift() and * leftShift() methods on Closure. *

      * Typical usages: *

       * def twice = { a -> a * 2 }
       * def inc = { b -> b + 1 }
       * def f = { x -> twice(inc(x)) } // longhand
       * def g = inc >> twice
       * def h = twice << inc
       * assert f(10) == 22
       * assert g(10) == 22
       * assert h(10) == 22
       *
       * def s2c = { it.chars[0] }
       * def p = Integer.&toHexString >> s2c >> Character.&toUpperCase
       * assert p(15) == 'F'
       *
       * def multiply = { a, b -> a * b }
       * def identity = { a -> [a, a] }
       * def sq = identity >> multiply
       * assert (1..5).collect{ sq(it) } == [1, 4, 9, 16, 25]
       *
       * def add3 = { a, b, c -> a + b + c }
       * def add2plus10 = add3.curry(10)
       * def multBoth = { a, b, c -> [a*c, b*c] }
       * def twiceBoth = multBoth.rcurry(2)
       * def twiceBothPlus10 = twiceBoth >> add2plus10
       * assert twiceBothPlus10(5, 10) == 40
       * 
      * * @author Paul King */ public final class ComposedClosure extends Closure { private Closure first; private Closure second; public ComposedClosure(Closure first, Closure second) { super((Closure) first.clone()); this.first = (Closure) getOwner(); this.second = (Closure) second.clone(); maximumNumberOfParameters = first.getMaximumNumberOfParameters(); } public void setDelegate(Object delegate) { ((Closure) getOwner()).setDelegate(delegate); second.setDelegate(delegate); } public Object getDelegate() { return ((Closure) getOwner()).getDelegate(); } public void setResolveStrategy(int resolveStrategy) { ((Closure) getOwner()).setResolveStrategy(resolveStrategy); second.setResolveStrategy(resolveStrategy); } public int getResolveStrategy() { return ((Closure) getOwner()).getResolveStrategy(); } public Object clone() { return new ComposedClosure(first, second); } public Class[] getParameterTypes() { return first.getParameterTypes(); } public Object doCall(Object... args) { return call(args); } @Override public V call(Object... args) { Object temp = first.call(args); if (temp instanceof List && second.getParameterTypes().length > 1) temp = ((List) temp).toArray(); return temp instanceof Object[] ? second.call((Object[]) temp) : second.call(temp); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/XmlGroovyMethods.java0000644001501200150120000000347711627206700025647 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.Iterator; /** * This class defines all the new XML-related groovy methods which enhance * the normal JDK XML classes when inside the Groovy environment. * Static methods are used with the first parameter the destination class. * * @author Paul King * @author Jochen Theodorou */ public class XmlGroovyMethods { /** * Makes NodeList iterable by returning a read-only Iterator which traverses * over each Node. * * @param nodeList a NodeList * @return an Iterator for a NodeList * @since 1.0 */ public static Iterator iterator(final NodeList nodeList) { return new Iterator() { private int current /* = 0 */; public boolean hasNext() { return current < nodeList.getLength(); } public Node next() { return nodeList.item(current++); } public void remove() { throw new UnsupportedOperationException("Cannot remove() from a NodeList iterator"); } }; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.java0000644001501200150120000001707111707612046030066 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.EmptyRange; import groovy.lang.Range; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.logging.Logger; /** * Support methods for DefaultGroovyMethods and PluginDefaultMethods. */ public class DefaultGroovyMethodsSupport { private static final Logger LOG = Logger.getLogger(DefaultGroovyMethodsSupport.class.getName()); // helper method for getAt and putAt protected static RangeInfo subListBorders(int size, Range range) { int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), size); int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), size); boolean reverse = range.isReverse(); if (from > to) { // support list[1..-1] int tmp = to; to = from; from = tmp; reverse = !reverse; } return new RangeInfo(from, to + 1, reverse); } // helper method for getAt and putAt protected static RangeInfo subListBorders(int size, EmptyRange range) { int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), size); return new RangeInfo(from, from, false); } /** * This converts a possibly negative index to a real index into the array. * * @param i the unnormalised index * @param size the array size * @return the normalised index */ protected static int normaliseIndex(int i, int size) { int temp = i; if (i < 0) { i += size; } if (i < 0) { throw new ArrayIndexOutOfBoundsException("Negative array index [" + temp + "] too large for array size " + size); } return i; } /** * Close the Closeable. Logging a warning if any problems occur. * * @param c the thing to close */ public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } } /** * Close the Closeable. Ignore any problems that might occur. * * @param c the thing to close */ public static void closeQuietly(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { /* ignore */ } } } protected static class RangeInfo { public final int from; public final int to; public final boolean reverse; public RangeInfo(int from, int to, boolean reverse) { this.from = from; this.to = to; this.reverse = reverse; } } protected static Collection cloneSimilarCollection(Collection orig, int newCapacity) { Collection answer = (Collection) cloneObject(orig); if (answer != null) return answer; // fall back to creation answer = createSimilarCollection(orig, newCapacity); answer.addAll(orig); return answer; } private static Object cloneObject(Object orig) { if (orig instanceof Cloneable) { try { return InvokerHelper.invokeMethod(orig, "clone", new Object[0]); } catch (Exception ex) { // ignore } } return null; } protected static Collection createSimilarOrDefaultCollection(Object object) { if (object instanceof Collection) { return createSimilarCollection((Collection) object); } return new ArrayList(); } protected static Collection createSimilarCollection(Collection collection) { return createSimilarCollection(collection, collection.size()); } protected static Collection createSimilarCollection(Collection orig, int newCapacity) { if (orig instanceof Set) { return createSimilarSet((Set) orig); } if (orig instanceof List) { return createSimilarList((List) orig, newCapacity); } if (orig instanceof Queue) { return new LinkedList(); } return new ArrayList(newCapacity); } protected static List createSimilarList(List orig, int newCapacity) { if (orig instanceof LinkedList) return new LinkedList(); if (orig instanceof Stack) return new Stack(); if (orig instanceof Vector) return new Vector(); return new ArrayList(newCapacity); } protected static Set createSimilarSet(Set orig) { if (orig instanceof SortedSet) { return new TreeSet(((SortedSet)orig).comparator()); } return new LinkedHashSet(); } protected static Map createSimilarMap(Map orig) { if (orig instanceof SortedMap) { return new TreeMap(((SortedMap)orig).comparator()); } if (orig instanceof Properties) { return (Map) new Properties(); } if (orig instanceof Hashtable) { return new Hashtable(); } return new LinkedHashMap(); } protected static Map cloneSimilarMap(Map orig) { Map answer = (Map) cloneObject(orig); if (answer != null) return answer; // fall back to some defaults if (orig instanceof TreeMap) return new TreeMap(orig); if (orig instanceof Properties) { Map map = (Map) new Properties(); map.putAll(orig); return map; } if (orig instanceof Hashtable) return new Hashtable(orig); return new LinkedHashMap(orig); } /** * Determines if all items of this array are of the same type. * * @param cols an array of collections * @return true if the collections are all of the same type */ protected static boolean sameType(Collection[] cols) { List all = new LinkedList(); for (Collection col : cols) { all.addAll(col); } if (all.size() == 0) return true; Object first = all.get(0); //trying to determine the base class of the collections //special case for Numbers Class baseClass; if (first instanceof Number) { baseClass = Number.class; } else if (first == null) { baseClass = NullObject.class; } else { baseClass = first.getClass(); } for (Collection col : cols) { for (Object o : col) { if (!baseClass.isInstance(o)) { return false; } } } return true; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ClassExtender.java0000644001501200150120000000437411627206700025116 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.util.HashMap; import java.util.Map; /** * A helper class used by the runtime to allow Groovy classes to be extended at runtime * * @author James Strachan * @version $Revision$ */ public class ClassExtender { private Map variables; private Map methods; public synchronized Object get(String name) { if (variables != null) { return variables.get(name); } return null; } public synchronized void set(String name, Object value) { if (variables == null) { variables = createMap(); } variables.put(name, value); } public synchronized void remove(String name) { if (variables != null) { variables.remove(name); } } public void call(String name, Object params) { Closure closure = null; synchronized (this) { if (methods != null) { closure = (Closure) methods.get(name); } } if (closure != null) { closure.call(params); } /* else { throw DoesNotUnderstandException(); } */ } public synchronized void addMethod(String name, Closure closure) { if (methods == null) { methods = createMap(); } methods.put(name, methods); } public synchronized void removeMethod(String name) { if (methods != null) { methods.remove(name); } } protected Map createMap() { return new HashMap(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/0000755001501200150120000000000011715031256023453 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/NewStaticMetaMethod.java0000644001501200150120000000325511627206700030174 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.reflection.CachedMethod; import java.lang.reflect.Modifier; /** * A MetaMethod implementation where the underlying method is really a static * helper method on some class. * * This implementation is used to add new static methods to the JDK writing them as normal * static methods with the first parameter being the class on which the method is added. * * @author Guillaume Laforge * @version $Revision$ */ public class NewStaticMetaMethod extends NewMetaMethod { public NewStaticMetaMethod(CachedMethod method) { super(method); } public boolean isStatic() { return true; } public int getModifiers() { return Modifier.PUBLIC | Modifier.STATIC; } public Object invoke(Object object, Object[] arguments) { int size = arguments.length; Object[] newArguments = new Object[size + 1]; System.arraycopy(arguments, 0, newArguments, 1, size); newArguments[0] = null; return super.invoke(null, newArguments); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/DefaultMetaClassInfo.java0000644001501200150120000002336211713765676030343 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; /** * WARNING: This class is for internal use only! * We use this class to store information about if a default MetaClass is * used for certain primitives. * @author Jochen "blackdrag" Theodorou * */ public class DefaultMetaClassInfo { //--------------------------------------------- // boolean //--------------------------------------------- // if original boolean meta class private static boolean origBoolean = true; // if origBoolean and withoutCustomHandle private static boolean origBooleanRes = true; /** * @return true if no meta class creation handle is set and if * the original boolean meta class is used. */ public static boolean isOrigBool() { return origBooleanRes; } /** * sets if the original boolean meta class is used */ public static void setOrigBool(boolean v) { origBoolean = v; origBooleanRes = withoutCustomHandle && origBoolean; } //--------------------------------------------- // byte //--------------------------------------------- // if original Byte meta class private static boolean origByte = true; // if origByte and withoutCustomHandle private static boolean origByteRes = true; /** * @return true if no meta class creation handle is set and if * the original byte meta class is used. */ public static boolean isOrigByte() { return origByteRes; } /** * sets if the original byte meta class is used */ public static void setOrigByte(boolean v) { origByte = v; origByteRes = withoutCustomHandle && origByte; } //--------------------------------------------- // char //--------------------------------------------- // if original char meta class private static boolean origChar = true; // if origChar and withoutCustomHandle private static boolean origCharRes = true; /** * @return true if no meta class creation handle is set and if * the original char meta class is used. */ public static boolean isOrigChar() { return origCharRes; } /** * sets if the original char meta class is used */ public static void setOrigChar(boolean v) { origChar = v; origCharRes = withoutCustomHandle && origChar; } //--------------------------------------------- // short //--------------------------------------------- // if original short meta class private static boolean origShort = true; // if origShort and withoutCustomHandle private static boolean origShortRes = true; /** * @return true if no meta class creation handle is set and if * the original short meta class is used. */ public static boolean isOrigShort() { return origShortRes; } /** * sets if the original short meta class is used */ public static void setOrigShort(boolean v) { origShort = v; origShortRes = withoutCustomHandle && origShort; } //--------------------------------------------- // int //--------------------------------------------- // if original Integer meta class private static boolean origInt = true; // if origInt and withoutCustomHandle private static boolean origIntRes = true; /** * @return true if no meta class creation handle is set and if * the original integer meta class is used. */ public static boolean isOrigInt() { return origIntRes; } /** * sets if the original int meta class is used */ public static void setOrigInt(boolean v) { origInt = v; origIntRes = withoutCustomHandle && origInt; } //--------------------------------------------- // int[] //--------------------------------------------- // if original Integer[] meta class private static boolean origIntArray = true; // if origInt and withoutCustomHandle private static boolean origIntArrayWCH = true; /** * @return true if no meta class creation handle is set and if * the original integer array meta class is used. */ public static boolean isOrigIntArray() { return origIntArrayWCH; } /** * sets if the original int array meta class is used */ public static void setOrigIntArray(boolean v) { origIntArray = v; origIntArrayWCH = withoutCustomHandle && origIntArray; } //--------------------------------------------- // long //--------------------------------------------- // if original long meta class private static boolean origLong = true; // if origLong and withoutCustomHandle private static boolean origLongRes = true; /** * @return true if no meta class creation handle is set and if * the original long meta class is used. */ public static boolean isOrigLong() { return origLongRes; } /** * sets if the original long meta class is used */ public static void setOrigLong(boolean v) { origLong = v; origLongRes = withoutCustomHandle && origLong; } //--------------------------------------------- // float //--------------------------------------------- // if original float meta class private static boolean origFloat = true; // if origFloat and withoutCustomHandle private static boolean origFloatRes = true; /** * @return true if no meta class creation handle is set and if * the original float meta class is used. */ public static boolean isOrigFloat() { return origFloatRes; } /** * sets if the original float meta class is used */ public static void setOrigFloat(boolean v) { origFloat = v; origFloatRes = withoutCustomHandle && origFloat; } //--------------------------------------------- // double //--------------------------------------------- // if original double meta class private static boolean origDouble = true; // if origFloat and withoutCustomHandle private static boolean origDoubleRes = true; /** * @return true if no meta class creation handle is set and if * the original double meta class is used. */ public static boolean isOrigDouble() { return origDoubleRes; } /** * sets if the original double meta class is used */ public static void setOrigDouble(boolean v) { origDouble = v; origDoubleRes = withoutCustomHandle && origDouble; } //--------------------------------------------- // custom meta class creation handle //--------------------------------------------- // if a custom meta class creation handle is set private static boolean withoutCustomHandle = true; /** * sets if the system uses a custom meta class creation handle */ public static void setWithoutCustomMetaclassCreationHandle(boolean mch) { withoutCustomHandle = mch; changeFlags(mch); } //--------------------------------------------- // category handle //--------------------------------------------- private static boolean categoryUsed = false; private static boolean disabledStandardMC = false; public static void setCategoryUsed(boolean b) { categoryUsed = b; disabledStandardMC = b || !withoutCustomHandle; } public static boolean disabledStandardMetaClass() { return disabledStandardMC; } private static void changeFlags(boolean mch) { if (mch) { disabledStandardMC = true; origIntArrayWCH = false; origByteRes = origChar = origBoolean =false; origShortRes = origIntRes = origLong = false; origFloat = origDouble = false; } else { disabledStandardMC = categoryUsed; origByteRes = origByte; origCharRes = origChar; origBooleanRes = origBoolean; origShortRes = origShort; origIntRes = origInt; origLongRes = origLong; origFloatRes = origFloat; origDoubleRes = origDouble; origIntArrayWCH = origIntArray; } } public static void setPrimitiveMeta(Class c, boolean orig) { if (c==Byte.class) { setOrigByte(orig); } else if (c==Character.class) { setOrigChar(orig); } else if (c==Short.class) { setOrigShort(orig); } else if (c==Integer.class) { setOrigInt(orig); } else if (c.getComponentType()==Integer.class) { setOrigIntArray(orig); } else if (c==Long.class) { setOrigLong(orig); } else if (c==Float.class) { setOrigFloat(orig); } else if (c==Double.class) { setOrigDouble(orig); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/NewMetaMethod.java0000644001501200150120000000350211627206700027017 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; /** * Base class for NewInstanceMetaMethod and NewStaticMetaMethod */ public class NewMetaMethod extends ReflectionMetaMethod { protected static final CachedClass[] EMPTY_TYPE_ARRAY = {}; protected CachedClass[] bytecodeParameterTypes ; public NewMetaMethod(CachedMethod method) { super(method); bytecodeParameterTypes = method.getParameterTypes(); int size = bytecodeParameterTypes.length; CachedClass[] logicalParameterTypes; if (size <= 1) { logicalParameterTypes = EMPTY_TYPE_ARRAY; } else { logicalParameterTypes = new CachedClass[--size]; System.arraycopy(bytecodeParameterTypes, 1, logicalParameterTypes, 0, size); } setParametersTypes(logicalParameterTypes); } public CachedClass getDeclaringClass() { return getBytecodeParameterTypes()[0]; } public CachedClass[] getBytecodeParameterTypes() { return bytecodeParameterTypes; } public CachedClass getOwnerClass() { return getBytecodeParameterTypes()[0]; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MixedInMetaClass.java0000644001501200150120000000343511627206700027455 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.lang.ref.WeakReference; import groovy.lang.*; /** * @author Alex Tkachman * */ public class MixedInMetaClass extends OwnedMetaClass { private final WeakReference owner; public MixedInMetaClass(Object instance, Object owner) { super(GroovySystem.getMetaClassRegistry().getMetaClass(instance.getClass())); this.owner = new WeakReference(owner); DefaultGroovyMethods.setMetaClass (instance, this); } protected Object getOwner() { return this.owner.get(); } protected MetaClass getOwnerMetaClass(Object owner) { return InvokerHelper.getMetaClass(owner); } public Object invokeMethod(Class sender, Object receiver, String methodName, Object[] arguments, boolean isCallToSuper, boolean fromInsideClass) { if (isCallToSuper) { return delegate.invokeMethod(sender, receiver, methodName, arguments, true, fromInsideClass); } return super.invokeMethod(sender, receiver, methodName, arguments, false, fromInsideClass); } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaMethod.java0000644001501200150120000000350011627206700031035 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.MixinInMetaClass; import org.codehaus.groovy.reflection.CachedClass; /** * MetaMethod for mixed in classes */ public class MixinInstanceMetaMethod extends MetaMethod{ private final MetaMethod method; private final MixinInMetaClass mixinInMetaClass; public MixinInstanceMetaMethod(MetaMethod method, MixinInMetaClass mixinInMetaClass) { this.method = method; this.mixinInMetaClass = mixinInMetaClass; } public int getModifiers() { return method.getModifiers(); } public String getName() { return method.getName(); } public Class getReturnType() { return method.getReturnType(); } public CachedClass getDeclaringClass() { return mixinInMetaClass.getInstanceClass(); } public Object invoke(Object object, Object[] arguments) { // make sure parameterTypes gets set method.getParameterTypes(); return method.invoke(mixinInMetaClass.getMixinInstance(object), method.correctArguments(arguments)); } protected Class[] getPT() { return method.getNativeParameterTypes(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ReflectorLoader.java0000644001501200150120000001263211707612046027401 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.runtime.Reflector; import java.security.ProtectionDomain; import java.util.HashMap; import java.util.Map; /** * Reflector creation helper. This class is used to define the Refloctor classes. * For each ClassLoader such a loader will be created by MetaClass. * Special about this loader is, that it knows the classes form the * Groovy Runtime. The Reflector class is resolved in different ways: During * the definition of a class Reflector will resolve to the Reflector class of * the runtime, even if there is another Reflector class in the parent loader. * After the new class is defined Reflector will resolve like other Groovy * classes. This loader is able to resolve all Groovy classes even if the * parent does not know them, but the parent serves first (Reflector during a * class definition is different). * * @author Jochen Theodorou * @version $Revision$ */ public class ReflectorLoader extends ClassLoader { private boolean inDefine = false; private final Map loadedClasses = new HashMap(); private final ClassLoader delegatationLoader; private static final String REFLECTOR = Reflector.class.getName(); /** * Tries to find a Groovy class. * * @return the class if found * @throws ClassNotFoundException if not found */ protected Class findClass(String name) throws ClassNotFoundException { if (delegatationLoader==null) return super.findClass(name); return delegatationLoader.loadClass(name); } /** * Loads a class per name. Unlike a normal loadClass this version * behaves different during a class definition. In that case it * checks if the class we want to load is Reflector and returns * class if the check is successful. If it is not during a class * definition it just calls the super class version of loadClass. * * @param name of the class to load * @param resolve is true if the class should be resolved * @see Reflector * @see ClassLoader#loadClass(String, boolean) */ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (inDefine) { if (name.equals(REFLECTOR)) return Reflector.class; } return super.loadClass(name, resolve); } /** * helper method to define Reflector classes. * @param name of the Reflector * @param bytecode the bytecode * @param domain the protection domain * @return the generated class */ public synchronized Class defineClass(String name, byte[] bytecode, ProtectionDomain domain) { inDefine = true; Class c = defineClass(name, bytecode, 0, bytecode.length, domain); loadedClasses.put(name,c); resolveClass(c); inDefine = false; return c; } /** * creates a ReflectorLoader. * @param parent the parent loader. This should never be null! */ public ReflectorLoader(ClassLoader parent) { super(parent); delegatationLoader = getClass().getClassLoader(); } /** * try to load one of the defined Reflector classes by name. * @param name of the Reflector class * @return the Reflector class if defined else null. */ public synchronized Class getLoadedClass(String name) { return (Class)loadedClasses.get(name); } static String getReflectorName(Class theClass) { String className = theClass.getName(); if (className.startsWith("java.")) { String packagePrefix = "gjdk."; String name = packagePrefix + className + "_GroovyReflector"; if (theClass.isArray()) { Class clazz = theClass; name = packagePrefix; int level = 0; while (clazz.isArray()) { clazz = clazz.getComponentType(); level++; } String componentName = clazz.getName(); name = packagePrefix + componentName + "_GroovyReflectorArray"; if (level>1) name += level; } return name; } else { String name = className.replace('$','_') + "_GroovyReflector"; if (theClass.isArray()) { Class clazz = theClass; int level = 0; while (clazz.isArray()) { clazz = clazz.getComponentType(); level++; } String componentName = clazz.getName(); name = componentName.replace('$','_') + "_GroovyReflectorArray"; if (level>1) name += level; } return name; } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/package.html0000644001501200150120000000030211627206700025727 0ustar miguelmiguel package org.codehaus.groovy.runtime.metaclass.*

      Internal classes related to Groovy's metaclass implementation.

      groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MissingPropertyExceptionNoStack.java0000644001501200150120000000174211627206700032642 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MissingPropertyException; public class MissingPropertyExceptionNoStack extends MissingPropertyException { public MissingPropertyExceptionNoStack(String propertyName, Class theClass) { super(propertyName, theClass); } public Throwable fillInStackTrace() { return this; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ClosureMetaMethod.java0000644001501200150120000001606411645141222027706 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.Closure; import groovy.lang.ClosureInvokingMethod; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.GeneratedClosure; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MethodClosure; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; /** * A MetaMethod that accepts a closure in the constructor which is invoked when the MetaMethod is called. * The delegate of the closure is set to the instance that the MetaMethod is invoked on when called. * * @author Graeme Rocher * @since 1.5 */ public class ClosureMetaMethod extends MetaMethod implements ClosureInvokingMethod { private final Closure callable; private final CachedMethod doCall; private final String name; private final CachedClass declaringClass; public ClosureMetaMethod(String name, Closure c, CachedMethod doCall) { this(name, c.getOwner().getClass(), c, doCall); } public ClosureMetaMethod(String name, Class declaringClass, Closure c, CachedMethod doCall) { super (doCall.getNativeParameterTypes()); this.name = name; callable = c; this.doCall = doCall; this.declaringClass = ReflectionCache.getCachedClass(declaringClass); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return Object.class; } public CachedClass getDeclaringClass() { return declaringClass; } public Object invoke(final Object object, Object[] arguments) { Closure cloned = (Closure) callable.clone(); cloned.setDelegate(object); arguments = coerceArgumentsToClasses(arguments); return doCall.invoke(cloned, arguments); } /** * Retrieves the closure that is invoked by this MetaMethod * * @return The closure */ public Closure getClosure() { return callable; } public static List createMethodList(final String name, final Class declaringClass, final Closure closure) { List res = new ArrayList(); if (closure instanceof MethodClosure) { MethodClosure methodClosure = (MethodClosure) closure; Object owner = closure.getOwner(); Class ownerClass = (Class) (owner instanceof Class ? owner : owner.getClass()); for (CachedMethod method : ReflectionCache.getCachedClass(ownerClass).getMethods() ) { if (method.getName().equals(methodClosure.getMethod())) { MetaMethod metaMethod = new MethodClosureMetaMethod(name, declaringClass, closure, method); res.add(adjustParamTypesForStdMethods(metaMethod, name)); } } } else { if (closure instanceof GeneratedClosure) { for (CachedMethod method : ReflectionCache.getCachedClass(closure.getClass()).getMethods() ) { if (method.getName().equals("doCall")) { MetaMethod metaMethod = new ClosureMetaMethod(name, declaringClass, closure, method); res.add(adjustParamTypesForStdMethods(metaMethod, name)); } } } else { MetaMethod metaMethod = new AnonymousMetaMethod(closure, name, declaringClass); res.add(adjustParamTypesForStdMethods(metaMethod, name)); } } return res; } private static MetaMethod adjustParamTypesForStdMethods(MetaMethod metaMethod, String methodName) { Class[] nativeParamTypes = metaMethod.getNativeParameterTypes(); nativeParamTypes = (nativeParamTypes != null) ? nativeParamTypes : new Class[0]; // for methodMissing, first parameter should be String type - to allow overriding of this method without // type String explicitly specified for first parameter (missing method name) - GROOVY-2951 if("methodMissing".equals(methodName) && nativeParamTypes.length == 2 && nativeParamTypes[0] != String.class) { nativeParamTypes[0] = String.class; } return metaMethod; } public CachedMethod getDoCall() { return doCall; } public static ClosureMetaMethod copy(ClosureMetaMethod closureMethod) { if (closureMethod instanceof MethodClosureMetaMethod) return new MethodClosureMetaMethod(closureMethod.getName(), closureMethod.getDeclaringClass().getTheClass(), closureMethod.getClosure(), closureMethod.getDoCall()); else return new ClosureMetaMethod(closureMethod.getName(), closureMethod.getDeclaringClass().getTheClass(), closureMethod.getClosure(), closureMethod.getDoCall()); } private static class MethodClosureMetaMethod extends ClosureMetaMethod { public MethodClosureMetaMethod(String name, Class declaringClass, Closure closure, CachedMethod method) { super(name, declaringClass, closure, method); } public Object invoke(Object object, Object[] arguments) { return getDoCall().invoke(getClosure().getOwner(), arguments); } } static class AnonymousMetaMethod extends MetaMethod { private final Closure closure; private final String name; private final Class declaringClass; public AnonymousMetaMethod(Closure closure, String name, Class declaringClass) { super(closure.getParameterTypes()); this.closure = closure; this.name = name; this.declaringClass = declaringClass; } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return Object.class; } public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(declaringClass); } public Object invoke(Object object, Object[] arguments) { Closure cloned = (Closure) closure.clone(); cloned.setDelegate(object); arguments = coerceArgumentsToClasses(arguments); return InvokerHelper.invokeMethod(cloned, "call", arguments); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MixinInstanceMetaProperty.java0000644001501200150120000000616211627206700031450 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MetaBeanProperty; import groovy.lang.MetaProperty; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.MixinInMetaClass; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import java.lang.reflect.Modifier; /** * MetaProperty for mixed in classes */ public class MixinInstanceMetaProperty extends MetaBeanProperty { public MixinInstanceMetaProperty(MetaProperty property, MixinInMetaClass mixinInMetaClass) { super(property.getName(), property.getType(), createGetter(property, mixinInMetaClass), createSetter(property, mixinInMetaClass)); } private static MetaMethod createSetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) { return new MetaMethod() { final String name = getSetterName(property.getName()); { setParametersTypes (new CachedClass [] {ReflectionCache.getCachedClass(property.getType())} ); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return property.getType(); } public CachedClass getDeclaringClass() { return mixinInMetaClass.getInstanceClass(); } public Object invoke(Object object, Object[] arguments) { property.setProperty(mixinInMetaClass.getMixinInstance(object), arguments[0]); return null; } }; } private static MetaMethod createGetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) { return new MetaMethod() { final String name = getGetterName(property.getName(), property.getType()); { setParametersTypes (new CachedClass [0]); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return property.getType(); } public CachedClass getDeclaringClass() { return mixinInMetaClass.getInstanceClass(); } public Object invoke(Object object, Object[] arguments) { return property.getProperty(mixinInMetaClass.getMixinInstance(object)); } }; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/OwnedMetaClass.java0000644001501200150120000002256311715031256027177 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.*; import org.codehaus.groovy.ast.ClassNode; import java.util.List; /** * @author Alex Tkachman */ public abstract class OwnedMetaClass extends DelegatingMetaClass { public OwnedMetaClass(final MetaClass delegate) { super(delegate); } public Object getAttribute(Object object, String attribute) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getAttribute(owner, attribute); } protected abstract Object getOwner(); public ClassNode getClassNode() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getClassNode(); } public List getMetaMethods() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMetaMethods(); } @Override public List getMethods() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMethods(); } public List respondsTo(Object obj, String name, Object[] argTypes) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.respondsTo(owner, name, argTypes); } public List respondsTo(Object obj, String name) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.respondsTo(owner, name); } public MetaProperty hasProperty(Object obj, String name) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.hasProperty(owner, name); } public List getProperties() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getProperties(); } public Object getProperty(Object object, String property) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getProperty(owner, property); } public Object invokeConstructor(Object[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeConstructor(arguments); } public Object invokeMethod(Object object, String methodName, Object arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeMethod(owner, methodName, arguments); } public Object invokeMethod(Object object, String methodName, Object[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeMethod(owner, methodName, arguments); } protected abstract MetaClass getOwnerMetaClass(Object owner); public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeStaticMethod(object, methodName, arguments); } public void setAttribute(Object object, String attribute, Object newValue) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); ownerMetaClass.setAttribute(object, attribute, newValue); } public void setProperty(Object object, String property, Object newValue) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); ownerMetaClass.setProperty(object, property, newValue); } public boolean equals(Object obj) { return delegate.equals(obj); } public int hashCode() { return delegate.hashCode(); } public String toString() { return super.toString() + "[" + delegate.toString()+ "]"; } /** * @deprecated */ public MetaMethod pickMethod(String methodName, Class[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.pickMethod(methodName,arguments); } public Object getAttribute(Class sender, Object receiver, String messageName, boolean useSuper) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getAttribute(sender, receiver, messageName, useSuper); } public Object getProperty(Class sender, Object receiver, String messageName, boolean useSuper, boolean fromInsideClass) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getProperty(sender, receiver, messageName, useSuper, fromInsideClass); } public MetaProperty getMetaProperty(String name) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMetaProperty(name); } public MetaMethod getStaticMetaMethod(String name, Object[] args) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getStaticMetaMethod(name, args); } public MetaMethod getStaticMetaMethod(String name, Class[] argTypes) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getStaticMetaMethod(name, argTypes); } public MetaMethod getMetaMethod(String name, Object[] args) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMetaMethod(name, args); } public MetaMethod getMetaMethod(String name, Class[] argTypes) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMetaMethod(name, argTypes); } public Class getTheClass() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getTheClass(); } public Object invokeMethod(Class sender, Object receiver, String methodName, Object[] arguments, boolean isCallToSuper, boolean fromInsideClass) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeMethod(sender, owner, methodName, arguments, isCallToSuper, fromInsideClass); } public Object invokeMissingMethod(Object instance, String methodName, Object[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeMissingMethod(owner, methodName, arguments); } public Object invokeMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.invokeMissingProperty(owner, propertyName, optionalValue, isGetter); } public boolean isGroovyObject() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return GroovyObject.class.isAssignableFrom(ownerMetaClass.getTheClass()); } public void setAttribute(Class sender, Object receiver, String messageName, Object messageValue, boolean useSuper, boolean fromInsideClass) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); ownerMetaClass.setAttribute(sender, owner, messageName, messageValue, useSuper, fromInsideClass); } public void setProperty(Class sender, Object receiver, String messageName, Object messageValue, boolean useSuper, boolean fromInsideClass) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); ownerMetaClass.setProperty(sender, owner, messageName, messageValue, useSuper, fromInsideClass); } public int selectConstructorAndTransformArguments(int numberOfConstructors, Object[] arguments) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.selectConstructorAndTransformArguments(numberOfConstructors, arguments); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MethodSelectionException.java0000644001501200150120000000733011627206700031266 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedConstructor; import org.codehaus.groovy.util.FastArray; import java.lang.reflect.Modifier; /** * This exception is thrown if the runtime is unable to select * a method. This class builds the exception text when calling * getMessage.
      * Note: This exception as for internal use only! * * @author Jochen Theodorou * @since Groovy 1.1 */ public class MethodSelectionException extends GroovyRuntimeException { private final String methodName; private final FastArray methods; private final Class[] arguments; /** * Creates a new MethodSelectionException. * @param methodName name of the method * @param methods a FastArray of methods * @param arguments the method call argument classes */ public MethodSelectionException(String methodName, FastArray methods, Class[] arguments) { super(methodName); this.methodName = methodName; this.arguments = arguments; this.methods = methods; } public String getMessage() { StringBuffer buffer = new StringBuffer(); buffer.append("Could not find which method ").append(methodName); appendClassNames(buffer,arguments); buffer.append(" to invoke from this list:"); appendMethods(buffer); return buffer.toString(); } private void appendClassNames(StringBuffer argBuf, Class[] classes) { argBuf.append("("); for (int i = 0; i < classes.length; i++) { if (i > 0) { argBuf.append(", "); } Class clazz = classes[i]; String name = clazz==null? "null": clazz.getName(); argBuf.append(name); } argBuf.append(")"); } private void appendMethods(StringBuffer buffer) { for (int i = 0; i < methods.size; i++) { buffer.append("\n "); Object methodOrConstructor = methods.get(i); if (methodOrConstructor instanceof MetaMethod) { MetaMethod method = (MetaMethod) methodOrConstructor; buffer.append(Modifier.toString(method.getModifiers())); buffer.append(" ").append(method.getReturnType().getName()); buffer.append(" ").append(method.getDeclaringClass().getName()); buffer.append("#"); buffer.append(method.getName()); appendClassNames(buffer,method.getNativeParameterTypes()); } else { CachedConstructor method = (CachedConstructor) methodOrConstructor; buffer.append(Modifier.toString(method.cachedConstructor.getModifiers())); buffer.append(" ").append(method.cachedConstructor.getDeclaringClass().getName()); buffer.append("#"); appendClassNames(buffer,method.getNativeParameterTypes()); } } } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MissingMethodExceptionNoStack.java0000644001501200150120000000221511627206700032232 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MissingMethodException; public class MissingMethodExceptionNoStack extends MissingMethodException { public MissingMethodExceptionNoStack(String method, Class type, Object[] arguments) { this(method,type,arguments,false); } public MissingMethodExceptionNoStack(String method, Class type, Object[] arguments, boolean isStatic) { super (method, type, arguments, isStatic); } public Throwable fillInStackTrace() { return this; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ConcurrentReaderHashMap.java0000644001501200150120000012077411627206700031040 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modified to support mostly-concurrent reading from this file: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java * which contains the following license information: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at: * http://creativecommons.org/licenses/publicdomain */ package org.codehaus.groovy.runtime.metaclass; import java.util.Map; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.AbstractCollection; import java.util.Collection; import java.util.Set; import java.util.ArrayList; import java.util.Iterator; import java.util.Enumeration; import java.util.NoSuchElementException; import java.io.Serializable; import java.io.IOException; /** * A hash table that supports mostly-concurrent reading, but * exclusive writing. Because reads are not limited to periods * without writes, a concurrent reader policy is weaker than a classic * reader/writer policy, but is generally faster and allows more * concurrency. This class is a good choice especially for tables that * are mainly created by one thread during the start-up phase of a * program, and from then on, are mainly read (with perhaps occasional * additions or removals) in many threads. If you also need concurrency * among writes, consider instead using ConcurrentHashMap. *

      * * Successful retrievals using get(key) and containsKey(key) usually * run without locking. Unsuccessful ones (i.e., when the key is not * present) do involve brief synchronization (locking). Also, the * size and isEmpty methods are always synchronized. * *

      Because retrieval operations can ordinarily overlap with * writing operations (i.e., put, remove, and their derivatives), * retrievals can only be guaranteed to return the results of the most * recently completed operations holding upon their * onset. Retrieval operations may or may not return results * reflecting in-progress writing operations. However, the retrieval * operations do always return consistent results -- either those * holding before any single modification or after it, but never a * nonsense result. For aggregate operations such as putAll and * clear, concurrent reads may reflect insertion or removal of only * some entries. In those rare contexts in which you use a hash table * to synchronize operations across threads (for example, to prevent * reads until after clears), you should either encase operations * in synchronized blocks, or instead use java.util.Hashtable. * *

      * * This class also supports optional guaranteed * exclusive reads, simply by surrounding a call within a synchronized * block, as in
      * ConcurrentReaderHashMap t; ... Object v;
      * synchronized(t) { v = t.get(k); }

      * * But this is not usually necessary in practice. For * example, it is generally inefficient to write: * *

       *   ConcurrentReaderHashMap t; ...            // Inefficient version
       *   Object key; ...
       *   Object value; ...
       *   synchronized(t) { 
       *     if (!t.containsKey(key))
       *       t.put(key, value);
       *       // other code if not previously present
       *     }
       *     else {
       *       // other code if it was previously present
       *     }
       *   }
       *
      * Instead, if the values are intended to be the same in each case, just take advantage of the fact that put returns * null if the key was not previously present: *
       *   ConcurrentReaderHashMap t; ...                // Use this instead
       *   Object key; ...
       *   Object value; ...
       *   Object oldValue = t.put(key, value);
       *   if (oldValue == null) {
       *     // other code if not previously present
       *   }
       *   else {
       *     // other code if it was previously present
       *   }
       *
      *

      * * Iterators and Enumerations (i.e., those returned by * keySet().iterator(), entrySet().iterator(), values().iterator(), * keys(), and elements()) return elements reflecting the state of the * hash table at some point at or since the creation of the * iterator/enumeration. They will return at most one instance of * each element (via next()/nextElement()), but might or might not * reflect puts and removes that have been processed since they were * created. They do not throw ConcurrentModificationException. * However, these iterators are designed to be used by only one * thread at a time. Sharing an iterator across multiple threads may * lead to unpredictable results if the table is being concurrently * modified. Again, you can ensure interference-free iteration by * enclosing the iteration in a synchronized block.

      * * This class may be used as a direct replacement for any use of * java.util.Hashtable that does not depend on readers being blocked * during updates. Like Hashtable but unlike java.util.HashMap, * this class does NOT allow null to be used as a key or * value. This class is also typically faster than ConcurrentHashMap * when there is usually only one thread updating the table, but * possibly many retrieving values from it. *

      * * Implementation note: A slightly faster implementation of * this class will be possible once planned Java Memory Model * revisions are in place. * *

      [ Introduction to this package. ] * * @author Adapted from ConcurrentHashMap (Doug Lea) * @author adapted by the Groovy community */ public class ConcurrentReaderHashMap extends AbstractMap implements Map, Cloneable, Serializable { /* The basic strategy is an optimistic-style scheme based on the guarantee that the hash table and its lists are always kept in a consistent enough state to be read without locking: * Read operations first proceed without locking, by traversing the apparently correct list of the apparently correct bin. If an entry is found, but not invalidated (value field null), it is returned. If not found, operations must recheck (after a memory barrier) to make sure they are using both the right list and the right table (which can change under resizes). If invalidated, reads must acquire main update lock to wait out the update, and then re-traverse. * All list additions are at the front of each bin, making it easy to check changes, and also fast to traverse. Entry next pointers are never assigned. Remove() builds new nodes when necessary to preserve this. * Remove() (also clear()) invalidates removed nodes to alert read operations that they must wait out the full modifications. */ /** A Serializable class for barrier lock **/ protected static class BarrierLock implements java.io.Serializable { } /** * Lock used only for its memory effects. **/ protected final BarrierLock barrierLock = new BarrierLock(); /** * field written to only to guarantee lock ordering. **/ protected transient Object lastWrite; /** * Force a memory synchronization that will cause * all readers to see table. Call only when already * holding main synch lock. **/ protected final void recordModification(Object x) { synchronized(barrierLock) { lastWrite = x; } } /** * Get ref to table; the reference and the cells it * accesses will be at least as fresh as from last * use of barrierLock **/ protected final Entry[] getTableForReading() { synchronized(barrierLock) { return table; } } /** * The default initial number of table slots for this table (32). * Used when not otherwise specified in constructor. **/ public static final int DEFAULT_INITIAL_CAPACITY = 32; /** * The minimum capacity, used if a lower value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two. */ private static final int MINIMUM_CAPACITY = 4; /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * The default load factor for this table (1.0). * Used when not otherwise specified in constructor. **/ public static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The hash table data. */ protected transient Entry[] table; /** * The total number of mappings in the hash table. */ protected transient int count; /** * The table is rehashed when its size exceeds this threshold. (The * value of this field is always (int)(capacity * loadFactor).) * * @serial */ protected int threshold; /** * The load factor for the hash table. * * @serial */ protected float loadFactor; /** * Returns the appropriate capacity (power of two) for the specified * initial capacity argument. */ private int p2capacity(int initialCapacity) { int cap = initialCapacity; // Compute the appropriate capacity int result; if (cap > MAXIMUM_CAPACITY || cap < 0) { result = MAXIMUM_CAPACITY; } else { result = MINIMUM_CAPACITY; while (result < cap) result <<= 1; } return result; } /** * Return hash code for Object x. Since we are using power-of-two * tables, it is worth the effort to improve hashcode via * the same multiplicative scheme as used in IdentityHashMap. */ private static int hash(Object x) { int h = x.hashCode(); // Multiply by 127 (quickly, via shifts), and mix in some high // bits to help guard against bunching of codes that are // consecutive or equally spaced. return ((h << 7) - h + (h >>> 9) + (h >>> 17)); } /** * Check for equality of non-null references x and y. **/ protected boolean eq(Object x, Object y) { return x == y || x.equals(y); } /** * Constructs a new, empty map with the specified initial * capacity and the specified load factor. * * @param initialCapacity the initial capacity * The actual initial capacity is rounded to the nearest power of two. * @param loadFactor the load factor of the ConcurrentReaderHashMap * @throws IllegalArgumentException if the initial maximum number * of elements is less * than zero, or if the load factor is non-positive. */ public ConcurrentReaderHashMap(int initialCapacity, float loadFactor) { if (loadFactor <= 0) throw new IllegalArgumentException("Illegal Load factor: "+ loadFactor); this.loadFactor = loadFactor; int cap = p2capacity(initialCapacity); table = new Entry[cap]; threshold = (int)(cap * loadFactor); } /** * Constructs a new, empty map with the specified initial * capacity and default load factor. * * @param initialCapacity the initial capacity of the * ConcurrentReaderHashMap. * @throws IllegalArgumentException if the initial maximum number * of elements is less than zero. */ public ConcurrentReaderHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs a new, empty map with a default initial capacity * and load factor. */ public ConcurrentReaderHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } /** * Constructs a new map with the same mappings as the given map. The * map is created with a capacity of twice the number of mappings in * the given map or 16 (whichever is greater), and a default load factor. */ public ConcurrentReaderHashMap(Map t) { this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, 16), DEFAULT_LOAD_FACTOR); putAll(t); } /** * Returns the number of key-value mappings in this map. * * @return the number of key-value mappings in this map. */ public synchronized int size() { return count; } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings. */ public synchronized boolean isEmpty() { return count == 0; } /** * Returns the value to which the specified key is mapped in this table. * * @param key a key in the table. * @return the value to which the key is mapped in this table; * null if the key is not mapped to any value in * this table. * @exception NullPointerException if the key is null. * @see #put(Object, Object) */ public Object get(Object key) { // throw null pointer exception if key null int hash = hash(key); /* Start off at the apparently correct bin. If entry is found, we need to check after a barrier anyway. If not found, we need a barrier to check if we are actually in right bin. So either way, we encounter only one barrier unless we need to retry. And we only need to fully synchronize if there have been concurrent modifications. */ Entry[] tab = table; int index = hash & (tab.length - 1); Entry first = tab[index]; Entry e = first; for (;;) { if (e == null) { // If key apparently not there, check to // make sure this was a valid read Entry[] reread = getTableForReading(); if (tab == reread && first == tab[index]) return null; else { // Wrong list -- must restart traversal at new first tab = reread; e = first = tab[index = hash & (tab.length-1)]; } } else if (e.hash == hash && eq(key, e.key)) { Object value = e.value; if (value != null) return value; // Entry was invalidated during deletion. But it could // have been re-inserted, so we must re-traverse. // To avoid useless contention, get lock to wait out modifications // before re-traversing. synchronized(this) { tab = table; } e = first = tab[index = hash & (tab.length-1)]; } else e = e.next; } } /** * Tests if the specified object is a key in this table. * * @param key possible key. * @return true if and only if the specified object * is a key in this table, as determined by the * equals method; false otherwise. * @exception NullPointerException if the key is null. * @see #contains(Object) */ public boolean containsKey(Object key) { return get(key) != null; } /** * Maps the specified key to the specified * value in this table. Neither the key nor the * value can be null.

      * * The value can be retrieved by calling the get method * with a key that is equal to the original key. * * @param key the table key. * @param value the value. * @return the previous value of the specified key in this table, * or null if it did not have one. * @exception NullPointerException if the key or value is null. * @see Object#equals(Object) * @see #get(Object) */ public Object put(Object key, Object value) { if (value == null) throw new NullPointerException(); int hash = hash(key); Entry[] tab = table; int index = hash & (tab.length-1); Entry first = tab[index]; Entry e; for (e = first; e != null; e = e.next) if (e.hash == hash && eq(key, e.key)) break; synchronized(this) { if (tab == table) { if (e == null) { // make sure we are adding to correct list if (first == tab[index]) { // Add to front of list Entry newEntry = new Entry(hash, key, value, first); tab[index] = newEntry; if (++count >= threshold) rehash(); else recordModification(newEntry); return null; } } else { Object oldValue = e.value; if (first == tab[index] && oldValue != null) { e.value = value; return oldValue; } } } // retry if wrong list or lost race against concurrent remove return sput(key, value, hash); } } /** * Continuation of put(), called only when synch lock is * held and interference has been detected. **/ protected Object sput(Object key, Object value, int hash) { Entry[] tab = table; int index = hash & (tab.length-1); Entry first = tab[index]; Entry e = first; for (;;) { if (e == null) { Entry newEntry = new Entry(hash, key, value, first); tab[index] = newEntry; if (++count >= threshold) rehash(); else recordModification(newEntry); return null; } else if (e.hash == hash && eq(key, e.key)) { Object oldValue = e.value; e.value = value; return oldValue; } else e = e.next; } } /** * Rehashes the contents of this map into a new table * with a larger capacity. This method is called automatically when the * number of keys in this map exceeds its capacity and load factor. */ protected void rehash() { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; // avoid retriggering return; } int newCapacity = oldCapacity << 1; int mask = newCapacity - 1; threshold = (int)(newCapacity * loadFactor); Entry[] newTable = new Entry[newCapacity]; /* * Reclassify nodes in each list to new Map. Because we are * using power-of-two expansion, the elements from each bin * must either stay at same index, or move to * oldCapacity+index. We also eliminate unnecessary node * creation by catching cases where old nodes can be reused * because their next fields won't change. Statistically, at * the default threshhold, only about one-sixth of them need * cloning. (The nodes they replace will be garbage * collectable as soon as they are no longer referenced by any * reader thread that may be in the midst of traversing table * right now.) */ for (int i = 0; i < oldCapacity ; i++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. Entry e = oldTable[i]; if (e != null) { int idx = e.hash & mask; Entry next = e.next; // Single node on list if (next == null) newTable[idx] = e; else { // Reuse trailing consecutive sequence of all same bit Entry lastRun = e; int lastIdx = idx; for (Entry last = next; last != null; last = last.next) { int k = last.hash & mask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (Entry p = e; p != lastRun; p = p.next) { int k = p.hash & mask; newTable[k] = new Entry(p.hash, p.key, p.value, newTable[k]); } } } } table = newTable; recordModification(newTable); } /** * Removes the key (and its corresponding value) from this * table. This method does nothing if the key is not in the table. * * @param key the key that needs to be removed. * @return the value to which the key had been mapped in this table, * or null if the key did not have a mapping. * @exception NullPointerException if the key is * null. */ public Object remove(Object key) { /* Find the entry, then 1. Set value field to null, to force get() to retry 2. Rebuild the list without this entry. All entries following removed node can stay in list, but all preceding ones need to be cloned. Traversals rely on this strategy to ensure that elements will not be repeated during iteration. */ int hash = hash(key); Entry[] tab = table; int index = hash & (tab.length-1); Entry first = tab[index]; Entry e = first; for (e = first; e != null; e = e.next) if (e.hash == hash && eq(key, e.key)) break; synchronized(this) { if (tab == table) { if (e == null) { if (first == tab[index]) return null; } else { Object oldValue = e.value; if (first == tab[index] && oldValue != null) { e.value = null; count--; Entry head = e.next; for (Entry p = first; p != e; p = p.next) head = new Entry(p.hash, p.key, p.value, head); tab[index] = head; recordModification(head); return oldValue; } } } // Wrong list or interference return sremove(key, hash); } } /** * Continuation of remove(), called only when synch lock is * held and interference has been detected. **/ protected Object sremove(Object key, int hash) { Entry[] tab = table; int index = hash & (tab.length-1); Entry first = tab[index]; for (Entry e = first; e != null; e = e.next) { if (e.hash == hash && eq(key, e.key)) { Object oldValue = e.value; e.value = null; count--; Entry head = e.next; for (Entry p = first; p != e; p = p.next) head = new Entry(p.hash, p.key, p.value, head); tab[index] = head; recordModification(head); return oldValue; } } return null; } /** * Returns true if this map maps one or more keys to the * specified value. Note: This method requires a full internal * traversal of the hash table, and so is much slower than * method containsKey. * * @param value value whose presence in this map is to be tested. * @return true if this map maps one or more keys to the * specified value. * @exception NullPointerException if the value is null. */ public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); Entry tab[] = getTableForReading(); for (int i = 0 ; i < tab.length; ++i) { for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; } return false; } /** * Tests if some key maps into the specified value in this table. * This operation is more expensive than the containsKey * method.

      * * Note that this method is identical in functionality to containsValue, * (which is part of the Map interface in the collections framework). * * @param value a value to search for. * @return true if and only if some key maps to the * value argument in this table as * determined by the equals method; * false otherwise. * @exception NullPointerException if the value is null. * @see #containsKey(Object) * @see #containsValue(Object) * @see Map */ public boolean contains(Object value) { return containsValue(value); } /** * Copies all of the mappings from the specified map to this one. * * These mappings replace any mappings that this map had for any of the * keys currently in the specified Map. * * @param t Mappings to be stored in this map. */ public synchronized void putAll(Map t) { int n = t.size(); if (n == 0) return; // Expand enough to hold at least n elements without resizing. // We can only resize table by factor of two at a time. // It is faster to rehash with fewer elements, so do it now. while (n >= threshold) rehash(); for (Iterator it = t.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); put(key, value); } } /** * Removes all mappings from this map. */ public synchronized void clear() { Entry tab[] = table; for (int i = 0; i < tab.length ; ++i) { // must invalidate all to force concurrent get's to wait and then retry for (Entry e = tab[i]; e != null; e = e.next) e.value = null; tab[i] = null; } count = 0; recordModification(tab); } /** * Returns a shallow copy of this * ConcurrentReaderHashMap instance: the keys and * values themselves are not cloned. * * @return a shallow copy of this map. */ public synchronized Object clone() { try { ConcurrentReaderHashMap t = (ConcurrentReaderHashMap)super.clone(); t.keySet = null; t.entrySet = null; t.values = null; Entry[] tab = table; t.table = new Entry[tab.length]; Entry[] ttab = t.table; for (int i = 0; i < tab.length; ++i) { Entry first = null; for (Entry e = tab[i]; e != null; e = e.next) first = new Entry(e.hash, e.key, e.value, first); ttab[i] = first; } return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } // Views protected transient Set keySet = null; protected transient Set entrySet = null; protected transient Collection values = null; /** * Returns a set view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. The set supports element removal, which removes the * corresponding mapping from this map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * * @return a set view of the keys contained in this map. */ public Set keySet() { Set ks = keySet; return (ks != null)? ks : (keySet = new KeySet()); } private class KeySet extends AbstractSet { public Iterator iterator() { return new KeyIterator(); } public int size() { return ConcurrentReaderHashMap.this.size(); } public boolean contains(Object o) { return ConcurrentReaderHashMap.this.containsKey(o); } public boolean remove(Object o) { return ConcurrentReaderHashMap.this.remove(o) != null; } public void clear() { ConcurrentReaderHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(); } public Object[] toArray(Object[] a) { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(a); } } /** * Returns a collection view of the values contained in this map. The * collection is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from this map, via the * Iterator.remove, Collection.remove, * removeAll, retainAll, and clear operations. * It does not support the add or addAll operations. * * @return a collection view of the values contained in this map. */ public Collection values() { Collection vs = values; return (vs != null)? vs : (values = new Values()); } private class Values extends AbstractCollection { public Iterator iterator() { return new ValueIterator(); } public int size() { return ConcurrentReaderHashMap.this.size(); } public boolean contains(Object o) { return ConcurrentReaderHashMap.this.containsValue(o); } public void clear() { ConcurrentReaderHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(); } public Object[] toArray(Object[] a) { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(a); } } /** * Returns a collection view of the mappings contained in this map. Each * element in the returned collection is a Map.Entry. The * collection is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from the map, via the * Iterator.remove, Collection.remove, * removeAll, retainAll, and clear operations. * It does not support the add or addAll operations. * * @return a collection view of the mappings contained in this map. */ public Set entrySet() { Set es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } private class EntrySet extends AbstractSet { public Iterator iterator() { return new HashIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object v = ConcurrentReaderHashMap.this.get(entry.getKey()); return v != null && v.equals(entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; return ConcurrentReaderHashMap.this.findAndRemoveEntry((Map.Entry)o); } public int size() { return ConcurrentReaderHashMap.this.size(); } public void clear() { ConcurrentReaderHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(); } public Object[] toArray(Object[] a) { Collection c = new ArrayList(); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(a); } } /** * Helper method for entrySet.remove **/ protected synchronized boolean findAndRemoveEntry(Map.Entry entry) { Object key = entry.getKey(); Object v = get(key); if (v != null && v.equals(entry.getValue())) { remove(key); return true; } else return false; } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table. * @see Enumeration * @see #elements() * @see #keySet() * @see Map */ public Enumeration keys() { return new KeyIterator(); } /** * Returns an enumeration of the values in this table. * Use the Enumeration methods on the returned object to fetch the elements * sequentially. * * @return an enumeration of the values in this table. * @see java.util.Enumeration * @see #keys() * @see #values() * @see Map */ public Enumeration elements() { return new ValueIterator(); } /** * ConcurrentReaderHashMap collision list entry. */ protected static class Entry implements Map.Entry { /* The use of volatile for value field ensures that we can detect status changes without synchronization. The other fields are never changed, and are marked as final. */ protected final int hash; protected final Object key; protected final Entry next; protected volatile Object value; Entry(int hash, Object key, Object value, Entry next) { this.hash = hash; this.key = key; this.next = next; this.value = value; } // Map.Entry Ops public Object getKey() { return key; } /** * Get the value. Note: In an entrySet or entrySet.iterator, * unless the set or iterator is used under synchronization of the * table as a whole (or you can otherwise guarantee lack of * concurrent modification), getValue might * return null, reflecting the fact that the entry has been * concurrently removed. However, there are no assurances that * concurrent removals will be reflected using this method. * * @return the current value, or null if the entry has been * detectably removed. **/ public Object getValue() { return value; } /** * Set the value of this entry. Note: In an entrySet or * entrySet.iterator), unless the set or iterator is used under * synchronization of the table as a whole (or you can otherwise * guarantee lack of concurrent modification), setValue * is not strictly guaranteed to actually replace the value field * obtained via the get operation of the underlying hash * table in multithreaded applications. If iterator-wide * synchronization is not used, and any other concurrent * put or remove operations occur, sometimes * even to other entries, then this change is not * guaranteed to be reflected in the hash table. (It might, or it * might not. There are no assurances either way.) * * @param value the new value. * @return the previous value, or null if entry has been detectably * removed. * @exception NullPointerException if the value is null. * **/ public Object setValue(Object value) { if (value == null) throw new NullPointerException(); Object oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return (key.equals(e.getKey()) && value.equals(e.getValue())); } public int hashCode() { return key.hashCode() ^ value.hashCode(); } public String toString() { return key + "=" + value; } } protected class HashIterator implements Iterator, Enumeration { protected final Entry[] tab; // snapshot of table protected int index; // current slot protected Entry entry = null; // current node of slot protected Object currentKey; // key for current node protected Object currentValue; // value for current node protected Entry lastReturned = null; // last node returned by next protected HashIterator() { tab = ConcurrentReaderHashMap.this.getTableForReading(); index = tab.length - 1; } public boolean hasMoreElements() { return hasNext(); } public Object nextElement() { return next(); } public boolean hasNext() { /* currentKey and currentValue are set here to ensure that next() returns normally if hasNext() returns true. This avoids surprises especially when final element is removed during traversal -- instead, we just ignore the removal during current traversal. */ for (;;) { if (entry != null) { Object v = entry.value; if (v != null) { currentKey = entry.key; currentValue = v; return true; } else entry = entry.next; } while (entry == null && index >= 0) entry = tab[index--]; if (entry == null) { currentKey = currentValue = null; return false; } } } protected Object returnValueOfNext() { return entry; } public Object next() { if (currentKey == null && !hasNext()) throw new NoSuchElementException(); Object result = returnValueOfNext(); lastReturned = entry; currentKey = currentValue = null; entry = entry.next; return result; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); ConcurrentReaderHashMap.this.remove(lastReturned.key); lastReturned = null; } } protected class KeyIterator extends HashIterator { protected Object returnValueOfNext() { return currentKey; } } protected class ValueIterator extends HashIterator { protected Object returnValueOfNext() { return currentValue; } } /** * Save the state of the ConcurrentReaderHashMap * instance to a stream (i.e., * serialize it). * * @param s the stream * @serialData The capacity of the * ConcurrentReaderHashMap (the length of the * bucket array) is emitted (int), followed by the * size of the ConcurrentReaderHashMap (the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping represented by the ConcurrentReaderHashMap * The key-value mappings are emitted in no particular order. */ private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); // Write out number of buckets s.writeInt(table.length); // Write out size (number of Mappings) s.writeInt(count); // Write out keys and values (alternating) for (int index = table.length-1; index >= 0; index--) { Entry entry = table[index]; while (entry != null) { s.writeObject(entry.key); s.writeObject(entry.value); entry = entry.next; } } } /** * Reconstitute the ConcurrentReaderHashMap * instance from a stream (i.e., * deserialize it). * * @param s the stream */ private synchronized void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold, loadfactor, and any hidden stuff s.defaultReadObject(); // Read in number of buckets and allocate the bucket array; int numBuckets = s.readInt(); table = new Entry[numBuckets]; // Read in size (number of Mappings) int size = s.readInt(); // Read the keys and values, and put the mappings in the table for (int i=0; iJames Strachan * @version $Revision$ */ public class MethodHelper { public static boolean isStatic(Method method) { int flags = Modifier.STATIC; return (method.getModifiers() & (flags)) == flags; } public static boolean isPublic(Method method) { int flags = Modifier.PUBLIC; return (method.getModifiers() & (flags)) == flags; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/NewInstanceMetaMethod.java0000644001501200150120000000351311627206700030506 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.reflection.CachedMethod; import java.lang.reflect.Modifier; /** * A MetaMethod implementation where the underlying method is really a static * helper method on some class but it appears to be an instance method on a class. * * This implementation is used to add new methods to the JDK writing them as normal * static methods with the first parameter being the class on which the method is added. * * @author James Strachan * @version $Revision$ */ public class NewInstanceMetaMethod extends NewMetaMethod { public NewInstanceMetaMethod(CachedMethod method) { super(method); } public boolean isStatic() { return false; } public int getModifiers() { // lets clear the static bit return Modifier.PUBLIC; } public Object invoke(Object object, Object[] arguments) { // we need to cheat using the type int size = arguments.length; Object[] newArguments = new Object[size + 1]; newArguments[0] = object; System.arraycopy(arguments, 0, newArguments, 1, size); return super.invoke(null, newArguments); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ThreadManagedMetaBeanProperty.java0000644001501200150120000001561011627206700032147 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.Closure; import groovy.lang.MetaBeanProperty; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.util.ManagedConcurrentMap; import org.codehaus.groovy.util.ReferenceBundle; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; /** * This MetaBeanProperty will create a pseudo property whose value is bound to an object * using weak references. The values will go out of scope and be garbage collected when * the the object is collected * * In fact, this class should be called ExpandoProperty. * * @author Graeme Rocher * @author Alex Tkachman * @since 1.5 */ public class ThreadManagedMetaBeanProperty extends MetaBeanProperty { private static final ConcurrentHashMap PROPNAME_TO_MAP = new ConcurrentHashMap(); private final ManagedConcurrentMap instance2Prop; private Class declaringClass; private ThreadBoundGetter getter; private ThreadBoundSetter setter; private Object initialValue; private Closure initialValueCreator; private static final ReferenceBundle SOFT_BUNDLE = ReferenceBundle.getSoftBundle(); /** * Retrieves the initial value of the ThreadBound property * * @return The initial value */ public synchronized Object getInitialValue() { return getInitialValue(null); } public synchronized Object getInitialValue(Object object) { if (initialValueCreator != null) { return initialValueCreator.call(object); } return initialValue; } /** * Closure responsible for creating the initial value of thread-managed bean properties * * @param callable The closure responsible for creating the initial value */ public void setInitialValueCreator(Closure callable) { this.initialValueCreator = callable; } /** * Constructs a new ThreadManagedBeanProperty for the given arguments * * @param declaringClass The class that declares the property * @param name The name of the property * @param type The type of the property * @param iv The properties initial value */ public ThreadManagedMetaBeanProperty(Class declaringClass, String name, Class type, Object iv) { super(name, type, null, null); this.type = type; this.declaringClass = declaringClass; this.getter = new ThreadBoundGetter(name); this.setter = new ThreadBoundSetter(name); initialValue = iv; instance2Prop = getInstance2PropName(name); } /** * Constructs a new ThreadManagedBeanProperty for the given arguments * * @param declaringClass The class that declares the property * @param name The name of the property * @param type The type of the property * @param initialValueCreator The closure responsible for creating the initial value */ public ThreadManagedMetaBeanProperty(Class declaringClass, String name, Class type, Closure initialValueCreator) { super(name, type, null, null); this.type = type; this.declaringClass = declaringClass; this.getter = new ThreadBoundGetter(name); this.setter = new ThreadBoundSetter(name); this.initialValueCreator = initialValueCreator; instance2Prop = getInstance2PropName(name); } private static ManagedConcurrentMap getInstance2PropName(String name) { ManagedConcurrentMap res = PROPNAME_TO_MAP.get(name); if (res == null) { res = new ManagedConcurrentMap(SOFT_BUNDLE); ManagedConcurrentMap ores = PROPNAME_TO_MAP.putIfAbsent(name, res); if (ores != null) return ores; } return res; } /* (non-Javadoc) * @see groovy.lang.MetaBeanProperty#getGetter() */ public MetaMethod getGetter() { return this.getter; } /* (non-Javadoc) * @see groovy.lang.MetaBeanProperty#getSetter() */ public MetaMethod getSetter() { return this.setter; } /** * Accesses the ThreadBound state of the property as a getter * * @author Graeme Rocher */ class ThreadBoundGetter extends MetaMethod { private final String name; public ThreadBoundGetter(String name) { setParametersTypes(new CachedClass[0]); this.name = getGetterName(name, type); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return type; } public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(declaringClass); } /* (non-Javadoc) * @see groovy.lang.MetaMethod#invoke(java.lang.Object, java.lang.Object[]) */ public Object invoke(Object object, Object[] arguments) { return instance2Prop.getOrPut(object, getInitialValue()).getValue(); } } /** * Sets the ThreadBound state of the property like a setter */ private class ThreadBoundSetter extends MetaMethod { private final String name; public ThreadBoundSetter(String name) { setParametersTypes (new CachedClass [] {ReflectionCache.getCachedClass(type)} ); this.name = getSetterName(name); } public int getModifiers() { return Modifier.PUBLIC; } /* (non-Javadoc) * @see groovy.lang.MetaMethod#getName() */ public String getName() { return name; } public Class getReturnType() { return type; } public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(declaringClass); } /* (non-Javadoc) * @see groovy.lang.MetaMethod#invoke(java.lang.Object, java.lang.Object[]) */ public Object invoke(Object object, Object[] arguments) { instance2Prop.put(object, arguments[0]); return null; } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ClosureStaticMetaMethod.java0000644001501200150120000000517311627206700031060 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.Closure; import groovy.lang.ClosureInvokingMethod; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import java.lang.reflect.Modifier; /** * This class represents a MetaMethod that is a closure that pretends to be a static method. * It is used by ExpandoMetaClass to allow addition of static methods defined as closures * * @author Graeme Rocher * @since 01.1 */ public class ClosureStaticMetaMethod extends MetaMethod implements ClosureInvokingMethod { private final Closure callable; private final CachedClass declaringClass; private final String name; /** * * @param name The name of the MetaMethod * @param declaringClass The class which declared the MetaMethod * @param c The closure that this ClosureMetaMethod will invoke when called */ public ClosureStaticMetaMethod(String name, Class declaringClass, Closure c) { this(name, declaringClass, c, c.getParameterTypes()); } public ClosureStaticMetaMethod(String name, Class declaringClass, Closure c, Class[] paramTypes) { super(paramTypes); this.callable = c; this.declaringClass = ReflectionCache.getCachedClass(declaringClass); this.name = name; } public Object invoke(Object object, Object[] arguments) { Closure cloned = (Closure) callable.clone(); cloned.setDelegate(object); return cloned.call(arguments); } public int getModifiers() { return Modifier.PUBLIC | Modifier.STATIC; } public String getName() { return name; } public Class getReturnType() { return Object.class; } public CachedClass getDeclaringClass() { return this.declaringClass; } /** * Retrieves the closure that is invoked by this MetaMethod * * @return The closure */ public Closure getClosure() { return this.callable; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/TemporaryMethodKey.java0000644001501200150120000000346111713765676030140 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import org.codehaus.groovy.runtime.MethodKey; import org.codehaus.groovy.runtime.MetaClassHelper; /** * A temporary implementation of MethodKey used to perform a fast lookup * for a method using a set of arguments to a method * * @author James Strachan * @version $Revision$ */ public class TemporaryMethodKey extends MethodKey { private final Object[] parameterValues; public TemporaryMethodKey(Class sender, String name, Object[] parameterValues, boolean isCallToSuper) { super(sender, name, isCallToSuper); if (parameterValues == null) { parameterValues = MetaClassHelper.EMPTY_ARRAY; } this.parameterValues = parameterValues; } public int getParameterCount() { return parameterValues.length; } public Class getParameterType(int index) { Object value = parameterValues[index]; if (value != null ) { Class type = (Class)((value.getClass() == java.lang.Class.class) ? value : value.getClass()); return type; } return Object.class; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MetaMethodIndex.java0000644001501200150120000004400411707612074027343 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.reflection.GeneratedMetaMethod; import org.codehaus.groovy.util.SingleKeyHashMap; import java.util.NoSuchElementException; public class MetaMethodIndex { public SingleKeyHashMap methodHeaders = new SingleKeyHashMap(); public static class Header { public Entry head; Class cls; public int clsHashCode31; public Class subclass; public Header(Class cls) { this (cls, null); } public Header(Class cls, Class subclass) { this.cls = cls; this.subclass = subclass; this.clsHashCode31 = 31 * cls.hashCode(); } } public static class CacheEntry { final public Class [] params; final public MetaMethod method; public CacheEntry(final Class[] params, final MetaMethod method) { this.params = params; this.method = method; } } public static class Entry { public int hash; public Entry nextHashEntry, nextClassEntry; public String name; public Class cls; public Object methods, methodsForSuper, staticMethods; public CacheEntry cachedMethod, cachedMethodForSuper, cachedStaticMethod; public String toString () { return "[" + name + ", " + cls.getName() + "]"; } } public MetaMethodIndex(CachedClass theCachedClass) { init(DEFAULT_CAPACITY); CachedClass last = null; if (!theCachedClass.isInterface()) { for (CachedClass c = theCachedClass; c != null; c = c.getCachedSuperClass()) { final SingleKeyHashMap.Entry e = methodHeaders.getOrPut(c.getTheClass()); e.value = new Header (c.getTheClass(), last == null ? null : last.getTheClass()); last = c; } } else { final SingleKeyHashMap.Entry e = methodHeaders.getOrPut(Object.class); e.value = new Header (Object.class, theCachedClass.getTheClass()); } } protected Entry table[]; protected static final int DEFAULT_CAPACITY = 32; protected static final int MINIMUM_CAPACITY = 4; protected static final int MAXIMUM_CAPACITY = 1 << 28; protected int size; protected transient int threshold; public static int hash(int h) { h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void clear() { Object[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } public void init(int initCapacity) { threshold = (initCapacity * 6) / 8; table = new Entry[initCapacity]; } public void resize(int newLength) { Entry[] oldTable = table; int oldLength = table.length; Entry[] newTable = new Entry[newLength]; for (int j = 0; j < oldLength; j++) { for (Entry e = oldTable[j]; e != null;) { Entry next = e.nextHashEntry; int index = e.hash & (newLength - 1); e.nextHashEntry = newTable[index]; newTable[index] = e; e = next; } } table = newTable; threshold = (6 * newLength) / 8; } public interface EntryIterator { boolean hasNext(); Entry next(); } public Entry[] getTable() { return table; } public EntryIterator getEntrySetIterator() { return new EntryIterator() { Entry next; // next entry to return int index; // current slot Entry current; // current entry { Entry[] t = table; int i = t.length; Entry n = null; if (size != 0) { // advance to first entry while (i > 0 && (n = t[--i]) == null) { } } next = n; index = i; } public boolean hasNext() { return next != null; } public Entry next() { return nextEntry(); } Entry nextEntry() { Entry e = next; if (e == null) throw new NoSuchElementException(); Entry n = e.nextHashEntry; Entry[] t = table; int i = index; while (n == null && i > 0) n = t[--i]; index = i; next = n; return current = e; } }; } public final Entry getMethods(Class cls, String name) { int h = hash(31 * cls.hashCode() + name.hashCode()); Entry e = table[h & (table.length - 1)]; for (; e != null; e = e.nextHashEntry) if (e.hash == h && cls == e.cls && (e.name == name || e.name.equals(name)) ) return e; return null; } public Entry getOrPutMethods(String name, Header header) { final Class cls = header.cls; int h = hash(header.clsHashCode31 + name.hashCode()); final Entry[] t = table; final int index = h & (t.length - 1); Entry e = t[index]; for (; e != null; e = e.nextHashEntry) if (e.hash == h && cls == e.cls && (e.name == name || e.name.equals(name)) ) return e; Entry entry = new Entry(); entry.nextHashEntry = t[index]; entry.hash = h; entry.name = name.intern(); entry.cls = cls; t[index] = entry; entry.nextClassEntry = header.head; header.head = entry; if (++size == threshold) resize(2 * t.length); return entry; } public Header getHeader(Class cls) { Header header; final SingleKeyHashMap.Entry head = methodHeaders.getOrPut(cls); if (head.value == null) { head.value = new Header(cls); } header = (Header) head.value; return header; } public void copyNonPrivateMethods(Class from, Class to) { copyNonPrivateMethods(getHeader(from), getHeader(to)); } public void copyNonPrivateMethods(Header from, Header to) { for (Entry e = from.head; e != null; e = e.nextClassEntry) copyNonPrivateMethods(e, to); } public void copyAllMethodsToSuper(Header from, Header to) { for (Entry e = from.head; e != null; e = e.nextClassEntry) copyAllMethodsToSuper(e, to); } public void copyNonPrivateMethodsFromSuper(Header from) { for (Entry e = from.head; e != null; e = e.nextClassEntry) copyNonPrivateMethodsFromSuper(e); } private void copyNonPrivateMethods(Entry from, Header to) { Object oldListOrMethod = from.methods; if (oldListOrMethod instanceof FastArray) { FastArray oldList = (FastArray) oldListOrMethod; Entry e = null; int len1 = oldList.size(); Object list[] = oldList.getArray(); for (int j = 0; j != len1; ++j) { MetaMethod method = (MetaMethod) list[j]; if (method.isPrivate()) continue; if (e == null) e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } else { MetaMethod method = (MetaMethod) oldListOrMethod; if (!method.isPrivate()) { Entry e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } } private void copyAllMethodsToSuper(Entry from, Header to) { Object oldListOrMethod = from.methods; if (oldListOrMethod instanceof FastArray) { FastArray oldList = (FastArray) oldListOrMethod; Entry e = null; int len1 = oldList.size(); Object list[] = oldList.getArray(); for (int j = 0; j != len1; ++j) { MetaMethod method = (MetaMethod) list[j]; if (e == null) e = getOrPutMethods(from.name, to); e.methodsForSuper = addMethodToList(e.methodsForSuper, method); } } else { MetaMethod method = (MetaMethod) oldListOrMethod; Entry e = getOrPutMethods(from.name, to); e.methodsForSuper = addMethodToList(e.methodsForSuper, method); } } private void copyNonPrivateMethodsFromSuper(Entry e) { Object oldListOrMethod = e.methodsForSuper; if (oldListOrMethod == null) return; if (oldListOrMethod instanceof FastArray) { FastArray oldList = (FastArray) oldListOrMethod; int len1 = oldList.size(); Object list[] = oldList.getArray(); for (int j = 0; j != len1; ++j) { MetaMethod method = (MetaMethod) list[j]; if (method.isPrivate()) continue; e.methods = addMethodToList(e.methods, method); } } else { MetaMethod method = (MetaMethod) oldListOrMethod; if (!method.isPrivate()) { e.methods = addMethodToList(e.methods, method); } } } public void copyNonPrivateMethodsDown(Class from, Class to) { copyNonPrivateNonNewMetaMethods(getHeader(from), getHeader(to)); } public void copyNonPrivateNonNewMetaMethods(Header from, Header to) { for (Entry e = from.head; e != null; e = e.nextClassEntry) copyNonPrivateNonNewMetaMethods(e, to); } private void copyNonPrivateNonNewMetaMethods(Entry from, Header to) { Object oldListOrMethod = from.methods; if (oldListOrMethod == null) return; if (oldListOrMethod instanceof FastArray) { FastArray oldList = (FastArray) oldListOrMethod; Entry e = null; int len1 = oldList.size(); Object list[] = oldList.getArray(); for (int j = 0; j != len1; ++j) { MetaMethod method = (MetaMethod) list[j]; if (method instanceof NewMetaMethod || method.isPrivate()) continue; if (e == null) e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } else { MetaMethod method = (MetaMethod) oldListOrMethod; if (method instanceof NewMetaMethod || method.isPrivate()) return; Entry e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } public Object addMethodToList(Object o, MetaMethod method) { if (o == null) { return method; } if (o instanceof MetaMethod) { MetaMethod match = (MetaMethod) o; if (!isMatchingMethod(match, method)) { FastArray list = new FastArray(2); list.add(match); list.add(method); return list; } else { if (match.isPrivate() || (!isNonRealMethod(match) && match.getDeclaringClass().isInterface() && !method.getDeclaringClass().isInterface())) { // do not overwrite interface methods with instance methods // do not overwrite private methods // Note: private methods from parent classes are not shown here, // but when doing the multimethod connection step, we overwrite // methods of the parent class with methods of a subclass and // in that case we want to keep the private methods } else { CachedClass methodC = method.getDeclaringClass(); CachedClass matchC = match.getDeclaringClass(); if (methodC == matchC) { if (isNonRealMethod(method)) { return method; } } else if (!methodC.isAssignableFrom(matchC.getTheClass())) { return method; } } } return o; } if (o instanceof FastArray) { FastArray list = (FastArray) o; int found = findMatchingMethod(list, method); if (found == -1) { list.add(method); } else { MetaMethod match = (MetaMethod) list.get(found); if (match==method) return o; if (match.isPrivate() || (!isNonRealMethod(match) && match.getDeclaringClass().isInterface() && !method.getDeclaringClass().isInterface())) { // do not overwrite interface methods with instance methods // do not overwrite private methods // Note: private methods from parent classes are not shown here, // but when doing the multimethod connection step, we overwrite // methods of the parent class with methods of a subclass and // in that case we want to keep the private methods } else { CachedClass methodC = method.getDeclaringClass(); CachedClass matchC = match.getDeclaringClass(); if (methodC == matchC) { if (isNonRealMethod(method)) { list.set(found, method); } } else if (!methodC.isAssignableFrom(matchC.getTheClass())) { list.set(found, method); } } } } return o; } private boolean isNonRealMethod(MetaMethod method) { return method instanceof NewInstanceMetaMethod || method instanceof NewStaticMetaMethod || method instanceof ClosureMetaMethod || method instanceof GeneratedMetaMethod || method instanceof ClosureStaticMetaMethod || method instanceof MixinInstanceMetaMethod || method instanceof ClosureMetaMethod.AnonymousMetaMethod; } private boolean isMatchingMethod(MetaMethod aMethod, MetaMethod method) { if (aMethod==method) return true; CachedClass[] params1 = aMethod.getParameterTypes(); CachedClass[] params2 = method.getParameterTypes(); if (params1.length != params2.length) { return false; } boolean matches = true; for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) { matches = false; break; } } return matches; } private int findMatchingMethod(FastArray list, MetaMethod method) { int len = list.size(); Object data[] = list.getArray(); for (int j = 0; j != len; ++j) { MetaMethod aMethod = (MetaMethod) data[j]; if (isMatchingMethod(aMethod, method)) return j; } return -1; } public void copyMethodsToSuper() { Entry[] table = this.table; int length = table.length; for (int j = 0; j < length; j++) { for (Entry e = table[j]; e != null; e = e.nextHashEntry) { if (e.methods instanceof FastArray) e.methodsForSuper = ((FastArray) e.methods).copy(); else e.methodsForSuper = e.methods; } } } public void copy(Class c, Header index) { copy(getHeader(c), index); } public void copy(Header from, Header to) { for (Entry e = from.head; e != null; e = e.nextClassEntry) copyAllMethods(e, to); } private void copyAllMethods(Entry from, Header to) { Object oldListOrMethod = from.methods; if (oldListOrMethod instanceof FastArray) { FastArray oldList = (FastArray) oldListOrMethod; Entry e = null; int len1 = oldList.size(); Object list[] = oldList.getArray(); for (int j = 0; j != len1; ++j) { MetaMethod method = (MetaMethod) list[j]; if (e == null) e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } else { MetaMethod method = (MetaMethod) oldListOrMethod; if (!method.isPrivate()) { Entry e = getOrPutMethods(from.name, to); e.methods = addMethodToList(e.methods, method); } } } public void clearCaches() { for (int i = 0; i != table.length; ++i ) for (Entry e = table [i]; e != null; e = e.nextHashEntry ) { e.cachedMethod = e.cachedMethodForSuper = e.cachedStaticMethod = null; } } public void clearCaches(String name) { for (int i = 0; i != table.length; ++i ) for (Entry e = table [i]; e != null; e = e.nextHashEntry ) { if (e.name.equals(name)) { e.cachedMethod = e.cachedMethodForSuper = e.cachedStaticMethod = null; } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl.java0000644001501200150120000004320511713765676030573 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.*; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.reflection.*; import org.codehaus.groovy.runtime.*; import org.codehaus.groovy.vmplugin.VMPluginFactory; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.util.ManagedLinkedList; import org.codehaus.groovy.util.ReferenceBundle; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; /** * A registry of MetaClass instances which caches introspection & * reflection information and allows methods to be dynamically added to * existing classes at runtime * * @author James Strachan * @author John Wilson * @author Jochen Theodorou * @author Graeme Rocher * @author Alex Tkachman * * @version $Revision$ */ public class MetaClassRegistryImpl implements MetaClassRegistry{ private boolean useAccessible; private FastArray instanceMethods = new FastArray(); private FastArray staticMethods = new FastArray(); private LinkedList changeListenerList = new LinkedList(); private ManagedLinkedList metaClassInfo = new ManagedLinkedList(ReferenceBundle.getWeakBundle()); public static final int LOAD_DEFAULT = 0; public static final int DONT_LOAD_DEFAULT = 1; private static MetaClassRegistry instanceInclude; private static MetaClassRegistry instanceExclude; public MetaClassRegistryImpl() { this(LOAD_DEFAULT, true); } public MetaClassRegistryImpl(int loadDefault) { this(loadDefault, true); } /** * @param useAccessible defines whether or not the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} * method will be called to enable access to all methods when using reflection */ public MetaClassRegistryImpl(boolean useAccessible) { this(LOAD_DEFAULT, useAccessible); } public MetaClassRegistryImpl(final int loadDefault, final boolean useAccessible) { this.useAccessible = useAccessible; if (loadDefault == LOAD_DEFAULT) { Map> map = new HashMap>(); // let's register the default methods registerMethods(null, true, true, map); final Class[] additionals = DefaultGroovyMethods.additionals; for (int i = 0; i != additionals.length; ++i) { createMetaMethodFromClass(map, additionals[i]); } Class[] pluginDGMs = VMPluginFactory.getPlugin().getPluginDefaultGroovyMethods(); for (Class plugin : pluginDGMs) { registerMethods(plugin, false, true, map); } registerMethods(DefaultGroovyStaticMethods.class, false, false, map); Class[] staticPluginDGMs = VMPluginFactory.getPlugin().getPluginStaticGroovyMethods(); for (Class plugin : staticPluginDGMs) { registerMethods(plugin, false, false, map); } for (Map.Entry> e : map.entrySet()) { CachedClass cls = e.getKey(); cls.setNewMopMethods(e.getValue()); } } installMetaClassCreationHandle(); final MetaClass emcMetaClass = metaClassCreationHandle.create(ExpandoMetaClass.class, this); emcMetaClass.initialize(); ClassInfo.getClassInfo(ExpandoMetaClass.class).setStrongMetaClass(emcMetaClass); addMetaClassRegistryChangeEventListener(new MetaClassRegistryChangeEventListener(){ public void updateConstantMetaClass(MetaClassRegistryChangeEvent cmcu) { synchronized (metaClassInfo) { metaClassInfo.add(cmcu.getNewMetaClass()); Class c = cmcu.getClassToUpdate(); DefaultMetaClassInfo.setPrimitiveMeta(c, cmcu.getNewMetaClass()==null); Field sdyn; try { sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL); sdyn.setBoolean(null, cmcu.getNewMetaClass()!=null); } catch (Throwable e) { //DO NOTHING } } } }); } /** * Looks for a class called 'groovy.runtime.metaclass.CustomMetaClassCreationHandle' and if it exists uses it as the MetaClassCreationHandle * otherwise uses the default * * @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle */ private void installMetaClassCreationHandle() { try { final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle"); final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor(new Class[]{}); this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance(); } catch (final ClassNotFoundException e) { this.metaClassCreationHandle = new MetaClassCreationHandle(); } catch (final Exception e) { throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e); } } private void registerMethods(final Class theClass, final boolean useMethodWrapper, final boolean useInstanceMethods, Map> map) { if (useMethodWrapper) { // Here we instantiate objects representing MetaMethods for DGM methods. // Calls for such meta methods done without reflection, so more effectively. try { List records = GeneratedMetaMethod.DgmMethodRecord.loadDgmInfo(); for (GeneratedMetaMethod.DgmMethodRecord record : records) { Class[] newParams = new Class[record.parameters.length - 1]; System.arraycopy(record.parameters, 1, newParams, 0, record.parameters.length-1); MetaMethod method = new GeneratedMetaMethod.Proxy( record.className, record.methodName, ReflectionCache.getCachedClass(record.parameters[0]), record.returnType, newParams ); final CachedClass declClass = method.getDeclaringClass(); List arr = map.get(declClass); if (arr == null) { arr = new ArrayList(4); map.put(declClass, arr); } arr.add(method); instanceMethods.add(method); } } catch (Throwable e) { e.printStackTrace(); // we print the error, but we don't stop with an exception here // since it is more comfortable this way for development } } else { CachedMethod[] methods = ReflectionCache.getCachedClass(theClass).getMethods(); for (CachedMethod method : methods) { final int mod = method.getModifiers(); if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && method.getCachedMethod().getAnnotation(Deprecated.class) == null) { CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length > 0) { List arr = map.get(paramTypes[0]); if (arr == null) { arr = new ArrayList(4); map.put(paramTypes[0], arr); } if (useInstanceMethods) { final NewInstanceMetaMethod metaMethod = new NewInstanceMetaMethod(method); arr.add(metaMethod); instanceMethods.add(metaMethod); } else { final NewStaticMetaMethod metaMethod = new NewStaticMetaMethod(method); arr.add(metaMethod); staticMethods.add(metaMethod); } } } } } } private void createMetaMethodFromClass(Map> map, Class aClass) { try { MetaMethod method = (MetaMethod) aClass.newInstance(); final CachedClass declClass = method.getDeclaringClass(); List arr = map.get(declClass); if (arr == null) { arr = new ArrayList(4); map.put(declClass, arr); } arr.add(method); instanceMethods.add(method); } catch (InstantiationException e) { /* ignore */ } catch (IllegalAccessException e) { /* ignore */ } } public final MetaClass getMetaClass(Class theClass) { return ClassInfo.getClassInfo(theClass).getMetaClass(); } public MetaClass getMetaClass(Object obj) { return ClassInfo.getClassInfo(obj.getClass()).getMetaClass(obj); } /** * if oldMc is null, newMc will replace whatever meta class was used before. * if oldMc is not null, then newMc will be used only if he stored mc is * the same as oldMc */ private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) { final ClassInfo info = ClassInfo.getClassInfo(theClass); MetaClass mc = null; info.lock(); try { mc = info.getStrongMetaClass(); info.setStrongMetaClass(newMc); } finally { info.unlock(); } if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) { fireConstantMetaClassUpdate(null, theClass, mc, newMc); } } public void removeMetaClass(Class theClass) { setMetaClass(theClass, null, null); } /** * Registers a new MetaClass in the registry to customize the type * * @param theClass * @param theMetaClass */ public void setMetaClass(Class theClass, MetaClass theMetaClass) { setMetaClass(theClass,null,theMetaClass); } public void setMetaClass(Object obj, MetaClass theMetaClass) { Class theClass = obj.getClass (); final ClassInfo info = ClassInfo.getClassInfo(theClass); MetaClass oldMC = null; info.lock(); try { oldMC = info.getPerInstanceMetaClass(obj); info.setPerInstanceMetaClass(obj, theMetaClass); } finally { info.unlock(); } fireConstantMetaClassUpdate(obj, theClass, oldMC, theMetaClass); } public boolean useAccessible() { return useAccessible; } // the following is experimental code, not intended for stable use yet private volatile MetaClassCreationHandle metaClassCreationHandle = new MetaClassCreationHandle(); /** * Gets a handle internally used to create MetaClass implementations * WARNING: experimental code, likely to change soon * @return the handle */ public MetaClassCreationHandle getMetaClassCreationHandler() { return metaClassCreationHandle; } /** * Sets a handle internally used to create MetaClass implementations. * When replacing the handle with a custom version, you should * reuse the old handle to keep custom logic and to use the * default logic as fall back. * WARNING: experimental code, likely to change soon * @param handle the handle */ public void setMetaClassCreationHandle(MetaClassCreationHandle handle) { if(handle == null) throw new IllegalArgumentException("Cannot set MetaClassCreationHandle to null value!"); ClassInfo.clearModifiedExpandos(); handle.setDisableCustomMetaClassLookup(metaClassCreationHandle.isDisableCustomMetaClassLookup()); metaClassCreationHandle = handle; } /** * Adds a listener for constant meta classes. * @param listener the listener */ public void addMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) { synchronized (changeListenerList) { changeListenerList.add(listener); } } /** * Removes a constant meta class listener. * @param listener the listener */ public void removeMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) { synchronized (changeListenerList) { Object first = changeListenerList.getFirst(); changeListenerList.remove(listener); // we want to keep the first entry! if (changeListenerList.size() == 0) changeListenerList.addFirst(first); } } /** * Causes the execution of all registered listeners. This method is used mostly * internal to kick of the listener notification. It can also be used by subclasses * to achieve the same. * * @param obj object instance if the MetaClass change is on a per-instance metaclass (or null if global) * @param c the class * @param oldMC the old MetaClass * @param newMc the new MetaClass */ protected void fireConstantMetaClassUpdate(Object obj, Class c, final MetaClass oldMC, MetaClass newMc) { MetaClassRegistryChangeEventListener[] listener = getMetaClassRegistryChangeEventListeners(); MetaClassRegistryChangeEvent cmcu = new MetaClassRegistryChangeEvent(this, obj, c, oldMC, newMc); for (int i = 0; iJames Strachan * @version $Revision$ */ public class TransformMetaMethod extends MetaMethod { private MetaMethod metaMethod; public TransformMetaMethod(MetaMethod metaMethod) { this.metaMethod = metaMethod; setParametersTypes(metaMethod.getParameterTypes()); nativeParamTypes = metaMethod.getNativeParameterTypes(); } public int getModifiers() { return metaMethod.getModifiers(); } public String getName() { return metaMethod.getName(); } public Class getReturnType() { return metaMethod.getReturnType(); } public CachedClass getDeclaringClass() { return metaMethod.getDeclaringClass(); } public Object invoke(Object object, Object[] arguments) { return metaMethod.invoke(object, arguments); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ReflectionMetaMethod.java0000644001501200150120000000420211713765676030400 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.runtime.InvokerInvocationException; import java.lang.reflect.InvocationTargetException; public class ReflectionMetaMethod extends MetaMethod { protected final CachedMethod method; public ReflectionMetaMethod(CachedMethod method) { this.method = method; setParametersTypes(method.getParameterTypes()); } public int getModifiers() { return method.getModifiers(); } public String getName() { return method.getName(); } public Class getReturnType() { return method.getReturnType(); } public CachedClass getDeclaringClass() { return method.cachedClass; } public Object invoke(Object object, Object[] arguments) { try { return method.setAccessible().invoke(object, arguments); } catch (IllegalArgumentException e) { throw new InvokerInvocationException(e); } catch (IllegalAccessException e) { throw new InvokerInvocationException(e); } catch (InvocationTargetException e) { throw e.getCause() instanceof RuntimeException ? (RuntimeException)e.getCause() : new InvokerInvocationException(e); } } public String toString () { return method.toString(); } protected Class[] getPT() { return method.getNativeParameterTypes(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/metaclass/ClosureMetaClass.java0000644001501200150120000007460411707612046027545 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.metaclass; import groovy.lang.*; import org.codehaus.groovy.reflection.*; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PogoMetaClassSite; import org.codehaus.groovy.runtime.wrappers.Wrapper; import org.codehaus.groovy.util.FastArray; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.*; /** * A meta class for closures generated by the Groovy compiler. These classes * have special characteristics this MetaClass uses. One of these is that a * generated Closure has only additional doCall methods, all other methods * are in the Closure class as well. To use this fact this MetaClass uses * a MetaClass for Closure as static field And delegates calls to this * MetaClass if needed. This allows a lean implementation for this MetaClass. * Multiple generated closures will then use the same MetaClass for Closure. * For static dispatching this class uses the MetaClass of Class, again * all instances of this class will share that MetaClass. The Class MetaClass * is initialized lazy, because most operations do not need this MetaClass. *

      * The Closure and Class MetaClasses are not replaceable. *

      * This MetaClass is for internal usage only! * * @author Jochen Theodorou * @since 1.5 */ public final class ClosureMetaClass extends MetaClassImpl { private boolean initialized; private final FastArray closureMethods = new FastArray(3); private Map attributes = new HashMap(); private MethodChooser chooser; private volatile boolean attributeInitDone = false; private static final MetaClassImpl CLOSURE_METACLASS; private static MetaClassImpl classMetaClass; private static final Object[] EMPTY_ARGUMENTS = {}; private static final String CLOSURE_CALL_METHOD = "call"; private static final String CLOSURE_DO_CALL_METHOD = "doCall"; static { CLOSURE_METACLASS = new MetaClassImpl(Closure.class); CLOSURE_METACLASS.initialize(); } private static synchronized MetaClass getStaticMetaClass() { if (classMetaClass == null) { classMetaClass = new MetaClassImpl(Class.class); classMetaClass.initialize(); } return classMetaClass; } private interface MethodChooser { Object chooseMethod(Class[] arguments, boolean coerce); } private static class StandardClosureChooser implements MethodChooser { private final MetaMethod doCall0; private final MetaMethod doCall1; StandardClosureChooser(MetaMethod m0, MetaMethod m1) { doCall0 = m0; doCall1 = m1; } public Object chooseMethod(Class[] arguments, boolean coerce) { if (arguments.length == 0) return doCall0; if (arguments.length == 1) return doCall1; return null; } } private static class NormalMethodChooser implements MethodChooser { private final FastArray methods; final Class theClass; NormalMethodChooser(Class theClass, FastArray methods) { this.theClass = theClass; this.methods = methods; } public Object chooseMethod(Class[] arguments, boolean coerce) { if (arguments.length == 0) { return MetaClassHelper.chooseEmptyMethodParams(methods); } else if (arguments.length == 1 && arguments[0] == null) { return MetaClassHelper.chooseMostGeneralMethodWith1NullParam(methods); } else { List matchingMethods = new ArrayList(); final int len = methods.size(); final Object[] data = methods.getArray(); for (int i = 0; i != len; ++i) { Object method = data[i]; // making this false helps find matches if (((ParameterTypes) method).isValidMethod(arguments)) { matchingMethods.add(method); } } if (matchingMethods.isEmpty()) { return null; } else if (matchingMethods.size() == 1) { return matchingMethods.get(0); } return chooseMostSpecificParams(CLOSURE_DO_CALL_METHOD, matchingMethods, arguments); } } private Object chooseMostSpecificParams(String name, List matchingMethods, Class[] arguments) { long matchesDistance = -1; LinkedList matches = new LinkedList(); for (Iterator iter = matchingMethods.iterator(); iter.hasNext();) { Object method = iter.next(); final ParameterTypes parameterTypes = (ParameterTypes) method; Class[] paramTypes = parameterTypes.getNativeParameterTypes(); if (!MetaClassHelper.parametersAreCompatible(arguments, paramTypes)) continue; long dist = MetaClassHelper.calculateParameterDistance(arguments, parameterTypes); if (dist == 0) return method; if (matches.isEmpty()) { matches.add(method); matchesDistance = dist; } else if (dist < matchesDistance) { matchesDistance = dist; matches.clear(); matches.add(method); } else if (dist == matchesDistance) { matches.add(method); } } if (matches.size() == 1) { return matches.getFirst(); } if (matches.isEmpty()) { return null; } // more than one matching method found --> ambiguous! String msg = "Ambiguous method overloading for method "; msg += theClass.getName() + "#" + name; msg += ".\nCannot resolve which method to invoke for "; msg += InvokerHelper.toString(arguments); msg += " due to overlapping prototypes between:"; for (Object match : matches) { CachedClass[] types = ((ParameterTypes) match).getParameterTypes(); msg += "\n\t" + InvokerHelper.toString(types); } throw new GroovyRuntimeException(msg); } } public ClosureMetaClass(MetaClassRegistry registry, Class theClass) { super(registry, theClass); } public MetaProperty getMetaProperty(String name) { return CLOSURE_METACLASS.getMetaProperty(name); } private void unwrap(Object[] arguments) { for (int i = 0; i != arguments.length; i++) { if (arguments[i] instanceof Wrapper) { arguments[i] = ((Wrapper) arguments[i]).unwrap(); } } } private MetaMethod pickClosureMethod(Class[] argClasses) { Object answer = chooser.chooseMethod(argClasses, false); return (MetaMethod) answer; } private MetaMethod getDelegateMethod(Closure closure, Object delegate, String methodName, Class[] argClasses) { if (delegate == closure || delegate == null) return null; MetaClass delegateMetaClass; if (delegate instanceof Class) { delegateMetaClass = registry.getMetaClass((Class) delegate); return delegateMetaClass.getStaticMetaMethod(methodName, argClasses); } else { delegateMetaClass = lookupObjectMetaClass(delegate); MetaMethod method = delegateMetaClass.pickMethod(methodName, argClasses); if (method != null) { return method; } if (delegateMetaClass instanceof ExpandoMetaClass) { method = ((ExpandoMetaClass) delegateMetaClass).findMixinMethod(methodName, argClasses); if (method != null) { onMixinMethodFound(method); return method; } } if (delegateMetaClass instanceof MetaClassImpl) { method = MetaClassImpl.findMethodInClassHierarchy(getTheClass(), methodName, argClasses, this); if (method != null) { onSuperMethodFoundInHierarchy(method); return method; } } return method; } } public Object invokeMethod(Class sender, Object object, String methodName, Object[] originalArguments, boolean isCallToSuper, boolean fromInsideClass) { checkInitalised(); if (object == null) { throw new NullPointerException("Cannot invoke method: " + methodName + " on null object"); } final Object[] arguments = makeArguments(originalArguments, methodName); final Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); unwrap(arguments); MetaMethod method = null; final Closure closure = (Closure) object; if (CLOSURE_DO_CALL_METHOD.equals(methodName) || CLOSURE_CALL_METHOD.equals(methodName)) { method = pickClosureMethod(argClasses); if (method == null && arguments.length == 1 && arguments[0] instanceof List) { Object[] newArguments = ((List) arguments[0]).toArray(); Class[] newArgClasses = MetaClassHelper.convertToTypeArray(newArguments); method = pickClosureMethod(newArgClasses); if (method != null) { method = new TransformMetaMethod(method) { public Object invoke(Object object, Object[] arguments) { Object firstArgument = arguments[0]; List list = (List) firstArgument; arguments = list.toArray(); return super.invoke(object, arguments); } }; } } if (method == null) throw new MissingMethodException(methodName, theClass, arguments, false); } boolean shouldDefer = closure.getResolveStrategy() == Closure.DELEGATE_ONLY && isInternalMethod(methodName); if (method == null && !shouldDefer) { method = CLOSURE_METACLASS.pickMethod(methodName, argClasses); } if (method != null) return method.doMethodInvoke(object, arguments); MissingMethodException last = null; Object callObject = object; if (method == null) { final Object owner = closure.getOwner(); final Object delegate = closure.getDelegate(); final Object thisObject = closure.getThisObject(); final int resolveStrategy = closure.getResolveStrategy(); boolean invokeOnDelegate = false; boolean invokeOnOwner = false; boolean ownerFirst = true; switch (resolveStrategy) { case Closure.TO_SELF: break; case Closure.DELEGATE_ONLY: method = getDelegateMethod(closure, delegate, methodName, argClasses); callObject = delegate; if (method == null) { invokeOnDelegate = delegate != closure && (delegate instanceof GroovyObject); } break; case Closure.OWNER_ONLY: method = getDelegateMethod(closure, owner, methodName, argClasses); callObject = owner; if (method == null) { invokeOnOwner = owner != closure && (owner instanceof GroovyObject); } break; case Closure.DELEGATE_FIRST: method = getDelegateMethod(closure, delegate, methodName, argClasses); callObject = delegate; if (method == null) { method = getDelegateMethod(closure, owner, methodName, argClasses); callObject = owner; } if (method == null) { invokeOnDelegate = delegate != closure && (delegate instanceof GroovyObject); invokeOnOwner = owner != closure && (owner instanceof GroovyObject); ownerFirst = false; } break; default: // owner first // owner first means we start with the outer most owner that is not a generated closure // this owner is equal to the this object, so we check that one first. method = getDelegateMethod(closure, thisObject, methodName, argClasses); callObject = thisObject; if (method == null) { // try finding a delegate that has that method... we start from // outside building a stack and try each delegate LinkedList list = new LinkedList(); for (Object current = closure; current != thisObject;) { Closure currentClosure = (Closure) current; if (currentClosure.getDelegate() != null) list.add(current); current = currentClosure.getOwner(); } while (!list.isEmpty() && method == null) { Closure closureWithDelegate = (Closure) list.removeLast(); Object currentDelegate = closureWithDelegate.getDelegate(); method = getDelegateMethod(closureWithDelegate, currentDelegate, methodName, argClasses); callObject = currentDelegate; } } if (method == null) { invokeOnDelegate = delegate != closure && (delegate instanceof GroovyObject); invokeOnOwner = owner != closure && (owner instanceof GroovyObject); } } if (method == null && (invokeOnOwner || invokeOnDelegate)) { try { if (ownerFirst) { return invokeOnDelegationObjects(invokeOnOwner, owner, invokeOnDelegate, delegate, methodName, arguments); } else { return invokeOnDelegationObjects(invokeOnDelegate, delegate, invokeOnOwner, owner, methodName, arguments); } } catch (MissingMethodException mme) { last = mme; } } } if (method != null) { MetaClass metaClass = registry.getMetaClass(callObject.getClass()); if (metaClass instanceof ProxyMetaClass) { return metaClass.invokeMethod(callObject, methodName, arguments); } else { return method.doMethodInvoke(callObject, arguments); } } else { // if no method was found, try to find a closure defined as a field of the class and run it Object value = null; try { value = this.getProperty(object, methodName); } catch (MissingPropertyException mpe) { // ignore } if (value instanceof Closure) { // This test ensures that value != this If you ever change this ensure that value != this Closure cl = (Closure) value; MetaClass delegateMetaClass = cl.getMetaClass(); return delegateMetaClass.invokeMethod(cl.getClass(), closure, CLOSURE_DO_CALL_METHOD, originalArguments, false, fromInsideClass); } } if (last != null) throw last; throw new MissingMethodException(methodName, theClass, arguments, false); } private boolean isInternalMethod(String methodName) { return methodName.equals("curry") || methodName.equals("ncurry") || methodName.equals("rcurry") || methodName.equals("leftShift") || methodName.equals("rightShift"); } private Object[] makeArguments(Object[] arguments, String methodName) { if (arguments == null) return EMPTY_ARGUMENTS; return arguments; } private static Throwable unwrap(GroovyRuntimeException gre) { Throwable th = gre; if (th.getCause() != null && th.getCause() != gre) th = th.getCause(); if (th != gre && (th instanceof GroovyRuntimeException)) return unwrap((GroovyRuntimeException) th); return th; } private Object invokeOnDelegationObjects( boolean invoke1, Object o1, boolean invoke2, Object o2, String methodName, Object[] args) { MissingMethodException first = null; if (invoke1) { GroovyObject go = (GroovyObject) o1; try { return go.invokeMethod(methodName, args); } catch (MissingMethodException mme) { first = mme; } catch (GroovyRuntimeException gre) { Throwable th = unwrap(gre); if ((th instanceof MissingMethodException) && (methodName.equals(((MissingMethodException) th).getMethod()))) { first = (MissingMethodException) th; } else { throw gre; } } } if (invoke2 && (!invoke1 || o1 != o2)) { GroovyObject go = (GroovyObject) o2; try { return go.invokeMethod(methodName, args); } catch (MissingMethodException mme) { // patch needed here too, but we need a test case to trip it first if (first == null) first = mme; } catch (GroovyRuntimeException gre) { Throwable th = unwrap(gre); if (th instanceof MissingMethodException) { first = (MissingMethodException) th; } else { throw gre; } } } throw first; } private synchronized void initAttributes() { if (!attributes.isEmpty()) return; attributes.put("!", null); // just a dummy for later CachedField[] fieldArray = theCachedClass.getFields(); for (CachedField aFieldArray : fieldArray) { attributes.put(aFieldArray.getName(), aFieldArray); } attributeInitDone = !attributes.isEmpty(); } public synchronized void initialize() { if (!isInitialized()) { CachedMethod[] methodArray = theCachedClass.getMethods(); synchronized (theCachedClass) { for (final CachedMethod cachedMethod : methodArray) { if (!cachedMethod.getName().equals(CLOSURE_DO_CALL_METHOD)) continue; closureMethods.add(cachedMethod); } } assignMethodChooser(); initialized = true; } } private void assignMethodChooser() { if (closureMethods.size() == 1) { final MetaMethod doCall = (MetaMethod) closureMethods.get(0); final CachedClass[] c = doCall.getParameterTypes(); int length = c.length; if (length == 0) { // no arg method chooser = new MethodChooser() { public Object chooseMethod(Class[] arguments, boolean coerce) { if (arguments.length == 0) return doCall; return null; } }; } else { if (length == 1 && c[0].getTheClass() == Object.class) { // Object fits all, so simple dispatch rule here chooser = new MethodChooser() { public Object chooseMethod(Class[] arguments, boolean coerce) { // <2, because foo() is same as foo(null) if (arguments.length < 2) return doCall; return null; } }; } else { boolean allObject = true; for (int i = 0; i < c.length - 1; i++) { if (c[i].getTheClass() != Object.class) { allObject = false; break; } } if (allObject && c[c.length - 1].getTheClass() == Object.class) { // all arguments are object, so test only if argument number is correct chooser = new MethodChooser() { public Object chooseMethod(Class[] arguments, boolean coerce) { if (arguments.length == c.length) return doCall; return null; } }; } else { if (allObject && c[c.length - 1].getTheClass() == Object[].class) { // all arguments are Object but last, which is a vargs argument, that // will fit all, so just test if the number of argument is equal or // more than the parameters we have. final int minimumLength = c.length - 2; chooser = new MethodChooser() { public Object chooseMethod(Class[] arguments, boolean coerce) { if (arguments.length > minimumLength) return doCall; return null; } }; } else { // general case for single method chooser = new MethodChooser() { public Object chooseMethod(Class[] arguments, boolean coerce) { if (doCall.isValidMethod(arguments)) { return doCall; } return null; } }; } } } } } else if (closureMethods.size() == 2) { MetaMethod m0 = null, m1 = null; for (int i = 0; i != closureMethods.size(); ++i) { MetaMethod m = (MetaMethod) closureMethods.get(i); CachedClass[] c = m.getParameterTypes(); if (c.length == 0) { m0 = m; } else { if (c.length == 1 && c[0].getTheClass() == Object.class) { m1 = m; } } } if (m0 != null && m1 != null) { // standard closure (2 methods because "it" is with default null) chooser = new StandardClosureChooser(m0, m1); } } if (chooser == null) { // standard chooser for cases if it is not a single method and if it is // not the standard closure. chooser = new NormalMethodChooser(theClass, closureMethods); } } private MetaClass lookupObjectMetaClass(Object object) { if (object instanceof GroovyObject) { GroovyObject go = (GroovyObject) object; return go.getMetaClass(); } Class ownerClass = object.getClass(); if (ownerClass == Class.class) { ownerClass = (Class) object; return registry.getMetaClass(ownerClass); } MetaClass metaClass = InvokerHelper.getMetaClass(object); return metaClass; } @Override public List getMethods() { List answer = CLOSURE_METACLASS.getMetaMethods(); answer.addAll(closureMethods.toList()); return answer; } @Override public List getMetaMethods() { return CLOSURE_METACLASS.getMetaMethods(); } @Override public List getProperties() { return CLOSURE_METACLASS.getProperties(); } @Override public MetaMethod pickMethod(String name, Class[] argTypes) { if (argTypes == null) argTypes = MetaClassHelper.EMPTY_CLASS_ARRAY; if (name.equals(CLOSURE_CALL_METHOD) || name.equals(CLOSURE_DO_CALL_METHOD)) { return pickClosureMethod(argTypes); } return CLOSURE_METACLASS.getMetaMethod(name, argTypes); } public MetaMethod retrieveStaticMethod(String methodName, Class[] arguments) { return null; } protected boolean isInitialized() { return initialized; } public MetaMethod getStaticMetaMethod(String name, Object[] args) { return CLOSURE_METACLASS.getStaticMetaMethod(name, args); } public MetaMethod getStaticMetaMethod(String name, Class[] argTypes) { return CLOSURE_METACLASS.getStaticMetaMethod(name, argTypes); } public Object getProperty(Class sender, Object object, String name, boolean useSuper, boolean fromInsideClass) { if (object instanceof Class) { return getStaticMetaClass().getProperty(sender, object, name, useSuper, fromInsideClass); } else { return CLOSURE_METACLASS.getProperty(sender, object, name, useSuper, fromInsideClass); } } @Override public Object getAttribute(Class sender, Object object, String attribute, boolean useSuper, boolean fromInsideClass) { if (object instanceof Class) { return getStaticMetaClass().getAttribute(sender, object, attribute, useSuper); } else { if (!attributeInitDone) initAttributes(); CachedField mfp = attributes.get(attribute); if (mfp == null) { return CLOSURE_METACLASS.getAttribute(sender, object, attribute, useSuper); } else { return mfp.getProperty(object); } } } @Override public void setAttribute(Class sender, Object object, String attribute, Object newValue, boolean useSuper, boolean fromInsideClass) { if (object instanceof Class) { getStaticMetaClass().setAttribute(sender, object, attribute, newValue, useSuper, fromInsideClass); } else { if (!attributeInitDone) initAttributes(); CachedField mfp = attributes.get(attribute); if (mfp == null) { CLOSURE_METACLASS.setAttribute(sender, object, attribute, newValue, useSuper, fromInsideClass); } else { mfp.setProperty(object, newValue); } } } public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { return getStaticMetaClass().invokeMethod(Class.class, object, methodName, arguments, false, false); } public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) { if (object instanceof Class) { getStaticMetaClass().setProperty(sender, object, name, newValue, useSuper, fromInsideClass); } else { CLOSURE_METACLASS.setProperty(sender, object, name, newValue, useSuper, fromInsideClass); } } public MetaMethod getMethodWithoutCaching(int index, Class sender, String methodName, Class[] arguments, boolean isCallToSuper) { throw new UnsupportedOperationException(); } public void setProperties(Object bean, Map map) { throw new UnsupportedOperationException(); } public void addMetaBeanProperty(MetaBeanProperty mp) { throw new UnsupportedOperationException(); } public void addMetaMethod(MetaMethod method) { throw new UnsupportedOperationException(); } public void addNewInstanceMethod(Method method) { throw new UnsupportedOperationException(); } public void addNewStaticMethod(Method method) { throw new UnsupportedOperationException(); } public Constructor retrieveConstructor(Class[] arguments) { throw new UnsupportedOperationException(); } public CallSite createPojoCallSite(CallSite site, Object receiver, Object[] args) { throw new UnsupportedOperationException(); } public CallSite createPogoCallSite(CallSite site, Object[] args) { return new PogoMetaClassSite(site, this); } public CallSite createPogoCallCurrentSite(CallSite site, Class sender, Object[] args) { return new PogoMetaClassSite(site, this); } public List respondsTo(Object obj, String name, Object[] argTypes) { loadMetaInfo(); return super.respondsTo(obj, name, argTypes); } public List respondsTo(final Object obj, final String name) { loadMetaInfo(); return super.respondsTo(obj, name); } private synchronized void loadMetaInfo() { if (metaMethodIndex.isEmpty()) { initialized = false; super.initialize(); initialized = true; } } protected void applyPropertyDescriptors(PropertyDescriptor[] propertyDescriptors) { // do nothing } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java0000644001501200150120000252667111715031256026503 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.io.EncodingAwareBufferedWriter; import groovy.io.FileType; import groovy.io.FileVisitResult; import groovy.io.GroovyPrintWriter; import groovy.lang.*; import groovy.util.*; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.reflection.MixinInMetaClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberDiv; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMultiply; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberPlus; import org.codehaus.groovy.runtime.dgmimpl.arrays.*; import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl; import org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.typehandling.GroovyCastException; import org.codehaus.groovy.runtime.typehandling.NumberMath; import org.codehaus.groovy.tools.RootLoader; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.math.BigDecimal; import java.math.BigInteger; import java.net.*; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class defines new groovy methods which appear on normal JDK * classes inside the Groovy environment. Static methods are used with the * first parameter being the destination class, * i.e. public static String reverse(String self) * provides a reverse() method for String. *

      * NOTE: While this class contains many 'public' static methods, it is * primarily regarded as an internal class (its internal package name * suggests this also). We value backwards compatibility of these * methods when used within Groovy but value less backwards compatibility * at the Java method call level. I.e. future versions of Groovy may * remove or move a method call in this file but would normally * aim to keep the method available from within Groovy. * * @author James Strachan * @author Jeremy Rayner * @author Sam Pullara * @author Rod Cope * @author Guillaume Laforge * @author John Wilson * @author Hein Meling * @author Dierk Koenig * @author Pilho Kim * @author Marc Guillemot * @author Russel Winder * @author bing ran * @author Jochen Theodorou * @author Paul King * @author Michael Baehr * @author Joachim Baumann * @author Alex Tkachman * @author Ted Naleid * @author Brad Long * @author Jim Jagielski * @author Rodolfo Velasco * @author jeremi Joslin * @author Hamlet D'Arcy * @author Cedric Champeau * @author Tim Yates * @author Dinko Srkoc */ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport { private static final Logger LOG = Logger.getLogger(DefaultGroovyMethods.class.getName()); private static final Integer ONE = 1; private static final BigInteger BI_INT_MAX = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger BI_INT_MIN = BigInteger.valueOf(Integer.MIN_VALUE); private static final BigInteger BI_LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger BI_LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); public static final Class [] additionals = { NumberNumberPlus.class, NumberNumberMultiply.class, NumberNumberMinus.class, NumberNumberDiv.class, ObjectArrayGetAtMetaMethod.class, ObjectArrayPutAtMetaMethod.class, BooleanArrayGetAtMetaMethod.class, BooleanArrayPutAtMetaMethod.class, ByteArrayGetAtMetaMethod.class, ByteArrayPutAtMetaMethod.class, CharacterArrayGetAtMetaMethod.class, CharacterArrayPutAtMetaMethod.class, ShortArrayGetAtMetaMethod.class, ShortArrayPutAtMetaMethod.class, IntegerArrayGetAtMetaMethod.class, IntegerArrayPutAtMetaMethod.class, LongArrayGetAtMetaMethod.class, LongArrayPutAtMetaMethod.class, FloatArrayGetAtMetaMethod.class, FloatArrayPutAtMetaMethod.class, DoubleArrayGetAtMetaMethod.class, DoubleArrayPutAtMetaMethod.class, }; /** * Identity check. Since == is overridden in Groovy with the meaning of equality * we need some fallback to check for object identity. Invoke using the * 'is' method, like so: def same = this.is(that) * * @param self an object * @param other an object to compare identity with * @return true if self and other are both references to the same * instance, false otherwise * @since 1.0 */ public static boolean is(Object self, Object other) { return self == other; } /** * Allows the closure to be called for the object reference self. * Synonym for 'with()'. * * @param self the object to have a closure act upon * @param closure the closure to call on the object * @return result of calling the closure * @since 1.0 */ public static T identity(Object self, Closure closure) { return DefaultGroovyMethods.with(self, closure); } /** * Allows the closure to be called for the object reference self.

      * Any method invoked inside the closure will first be invoked on the * self reference. For instance, the following method calls to the append() * method are invoked on the StringBuilder instance: *

           * def b = new StringBuilder().with {
           *   append('foo')
           *   append('bar')
           *   return it
           * }
           * assert b.toString() == 'foobar' 
           * 
      * This is commonly used to simplify object creation, such as this example: *
           * def p = new Person().with {
           *   firstName = 'John'
           *   lastName = 'Doe'
           *   return it
           * }
           * 
      * * @param self the object to have a closure act upon * @param closure the closure to call on the object * @return result of calling the closure * @since 1.5.0 */ public static T with(Object self, Closure closure) { @SuppressWarnings("unchecked") final Closure clonedClosure = (Closure) closure.clone(); clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST); clonedClosure.setDelegate(self); return clonedClosure.call(self); } /** * Allows the subscript operator to be used to lookup dynamic property values. * bean[somePropertyNameExpression]. The normal property notation * of groovy is neater and more concise but only works with compile-time known * property names. * * @param self the object to act upon * @param property the property name of interest * @return the property value * @since 1.0 */ public static Object getAt(Object self, String property) { return InvokerHelper.getProperty(self, property); } /** * Allows the subscript operator to be used to set dynamically named property values. * bean[somePropertyNameExpression] = foo. The normal property notation * of groovy is neater and more concise but only works with property names which * are known at compile time. * * @param self the object to act upon * @param property the name of the property to set * @param newValue the value to set * @since 1.0 */ public static void putAt(Object self, String property, Object newValue) { InvokerHelper.setProperty(self, property, newValue); } /** * Generates a detailed dump string of an object showing its class, * hashCode and fields. * * @param self an object * @return the dump representation * @since 1.0 */ public static String dump(Object self) { if (self == null) { return "null"; } StringBuilder buffer = new StringBuilder("<"); Class klass = self.getClass(); buffer.append(klass.getName()); buffer.append("@"); buffer.append(Integer.toHexString(self.hashCode())); boolean groovyObject = self instanceof GroovyObject; /*jes this may be rewritten to use the new getProperties() stuff * but the original pulls out private variables, whereas getProperties() * does not. What's the real use of dump() here? */ while (klass != null) { for (final Field field : klass.getDeclaredFields()) { if ((field.getModifiers() & Modifier.STATIC) == 0) { if (groovyObject && field.getName().equals("metaClass")) { continue; } AccessController.doPrivileged(new PrivilegedAction() { public Object run() { field.setAccessible(true); return null; } }); buffer.append(" "); buffer.append(field.getName()); buffer.append("="); try { buffer.append(InvokerHelper.toString(field.get(self))); } catch (Exception e) { buffer.append(e); } } } klass = klass.getSuperclass(); } /* here is a different implementation that uses getProperties(). I have left * it commented out because it returns a slightly different list of properties; * i.e. it does not return privates. I don't know what dump() really should be doing, * although IMO showing private fields is a no-no */ /* List props = getProperties(self); for(Iterator itr = props.keySet().iterator(); itr.hasNext(); ) { String propName = itr.next().toString(); // the original skipped this, so I will too if(pv.getName().equals("class")) continue; if(pv.getName().equals("metaClass")) continue; buffer.append(" "); buffer.append(propName); buffer.append("="); try { buffer.append(InvokerHelper.toString(props.get(propName))); } catch (Exception e) { buffer.append(e); } } */ buffer.append(">"); return buffer.toString(); } /** * Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it * in a list of {@link groovy.lang.PropertyValue} objects that additionally provide * the value for each property of 'self'. * * @param self the receiver object * @return list of {@link groovy.lang.PropertyValue} objects * @see groovy.util.Expando#getMetaPropertyValues() * @since 1.0 */ public static List getMetaPropertyValues(Object self) { MetaClass metaClass = InvokerHelper.getMetaClass(self); List mps = metaClass.getProperties(); List props = new ArrayList(mps.size()); for (MetaProperty mp : mps) { props.add(new PropertyValue(self, mp)); } return props; } /** * Convenience method that calls {@link #getMetaPropertyValues(java.lang.Object)}(self) * and provides the data in form of simple key/value pairs, i.e.&nsbp;without * type() information. * * @param self the receiver object * @return meta properties as Map of key/value pairs * @since 1.0 */ public static Map getProperties(Object self) { List metaProps = getMetaPropertyValues(self); Map props = new LinkedHashMap(metaProps.size()); for (PropertyValue mp : metaProps) { try { props.put(mp.getName(), mp.getValue()); } catch (Exception e) { LOG.throwing(self.getClass().getName(), "getProperty(" + mp.getName() + ")", e); } } return props; } /** * Scoped use method * * @param self any Object * @param categoryClass a category class to use * @param closure the closure to invoke with the category in place * @return the value returned from the closure * @since 1.0 */ public static T use(Object self, Class categoryClass, Closure closure) { return GroovyCategorySupport.use(categoryClass, closure); } /** * Extend object with category methods. * All methods for given class and all super classes will be added to the object. * * @param self any Class * @param categoryClasses a category classes to use * @since 1.6.0 */ public static void mixin(MetaClass self, List categoryClasses) { MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses); } /** * Extend class globally with category methods. * All methods for given class and all super classes will be added to the class. * * @param self any Class * @param categoryClasses a category classes to use * @since 1.6.0 */ public static void mixin(Class self, List categoryClasses) { mixin(getMetaClass(self), categoryClasses); } /** * Extend class globally with category methods. * * @param self any Class * @param categoryClass a category class to use * @since 1.6.0 */ public static void mixin(Class self, Class categoryClass) { mixin(getMetaClass(self), Collections.singletonList(categoryClass)); } /** * Extend class globally with category methods. * * @param self any Class * @param categoryClass a category class to use * @since 1.6.0 */ public static void mixin(Class self, Class[] categoryClass) { mixin(getMetaClass(self), Arrays.asList(categoryClass)); } /** * Extend class globally with category methods. * * @param self any Class * @param categoryClass a category class to use * @since 1.6.0 */ public static void mixin(MetaClass self, Class categoryClass) { mixin(self, Collections.singletonList(categoryClass)); } /** * Extend class globally with category methods. * * @param self any Class * @param categoryClass a category class to use * @since 1.6.0 */ public static void mixin(MetaClass self, Class[] categoryClass) { mixin(self, Arrays.asList(categoryClass)); } /** * Scoped use method with list of categories. * * @param self any Object * @param categoryClassList a list of category classes * @param closure the closure to invoke with the categories in place * @return the value returned from the closure * @since 1.0 */ public static T use(Object self, List categoryClassList, Closure closure) { return GroovyCategorySupport.use(categoryClassList, closure); } /** * Allows the usage of addShutdownHook without getting the runtime first. * * @param self the object the method is called on (ignored) * @param closure the shutdown hook action * @since 1.5.0 */ public static void addShutdownHook(Object self, Closure closure) { Runtime.getRuntime().addShutdownHook(new Thread(closure)); } /** * Allows you to use a list of categories, specifying the list as varargs. * use(CategoryClass1, CategoryClass2) { ... } * This method saves having to wrap the the category * classes in a list. * * @param self any Object * @param array a list of category classes and a Closure * @return the value returned from the closure * @since 1.0 */ public static Object use(Object self, Object[] array) { if (array.length < 2) throw new IllegalArgumentException( "Expecting at least 2 arguments, a category class and a Closure"); Closure closure; try { closure = (Closure) array[array.length - 1]; } catch (ClassCastException e) { throw new IllegalArgumentException("Expecting a Closure to be the last argument"); } List list = new ArrayList(array.length - 1); for (int i = 0; i < array.length - 1; ++i) { Class categoryClass; try { categoryClass = (Class) array[i]; } catch (ClassCastException e) { throw new IllegalArgumentException("Expecting a Category Class for argument " + i); } list.add(categoryClass); } return GroovyCategorySupport.use(list, closure); } /** * Print a value formatted Groovy style to self if it * is a Writer, otherwise to the standard output stream. * * @param self any Object * @param value the value to print * @since 1.0 */ public static void print(Object self, Object value) { // we won't get here if we are a PrintWriter if (self instanceof Writer) { try { ((Writer) self).write(InvokerHelper.toString(value)); } catch (IOException e) { // TODO: Should we have some unified function like PrintWriter.checkError()? } } else { System.out.print(InvokerHelper.toString(value)); } } /** * Print a value formatted Groovy style to the print writer. * * @param self a PrintWriter * @param value the value to print * @since 1.0 */ public static void print(PrintWriter self, Object value) { self.print(InvokerHelper.toString(value)); } /** * Print a value formatted Groovy style to the print stream. * * @param self a PrintStream * @param value the value to print * @since 1.6.0 */ public static void print(PrintStream self, Object value) { self.print(InvokerHelper.toString(value)); } /** * Print a value to the standard output stream. * This method delegates to the owner to execute the method. * * @param self a generated closure * @param value the value to print * @since 1.0 */ public static void print(Closure self, Object value) { Object owner = getClosureOwner(self); InvokerHelper.invokeMethod(owner, "print", new Object[]{value}); } /** * Print a linebreak to the standard output stream. * * @param self any Object * @since 1.0 */ public static void println(Object self) { // we won't get here if we are a PrintWriter if (self instanceof Writer) { PrintWriter pw = new GroovyPrintWriter((Writer) self); pw.println(); } else { System.out.println(); } } /** * Print a linebreak to the standard output stream. * This method delegates to the owner to execute the method. * * @param self a closure * @since 1.0 */ public static void println(Closure self) { Object owner = getClosureOwner(self); InvokerHelper.invokeMethod(owner, "println", new Object[0]); } private static Object getClosureOwner(Closure cls) { Object owner = cls.getOwner(); while (owner instanceof GeneratedClosure) { owner = ((Closure) owner).getOwner(); } return owner; } /** * Print a value formatted Groovy style (followed by a newline) to self * if it is a Writer, otherwise to the standard output stream. * * @param self any Object * @param value the value to print * @since 1.0 */ public static void println(Object self, Object value) { // we won't get here if we are a PrintWriter if (self instanceof Writer) { final PrintWriter pw = new GroovyPrintWriter((Writer) self); pw.println(value); } else { System.out.println(InvokerHelper.toString(value)); } } /** * Print a value formatted Groovy style (followed by a newline) to the print writer. * * @param self a PrintWriter * @param value the value to print * @since 1.0 */ public static void println(PrintWriter self, Object value) { self.println(InvokerHelper.toString(value)); } /** * Print a value formatted Groovy style (followed by a newline) to the print stream. * * @param self any Object * @param value the value to print * @since 1.6.0 */ public static void println(PrintStream self, Object value) { self.println(InvokerHelper.toString(value)); } /** * Print a value (followed by a newline) to the standard output stream. * This method delegates to the owner to execute the method. * * @param self a closure * @param value the value to print * @since 1.0 */ public static void println(Closure self, Object value) { Object owner = getClosureOwner(self); InvokerHelper.invokeMethod(owner, "println", new Object[]{value}); } /** * Printf to a console (Only works with JDK1.5 or later). * * @param self any Object * @param format a format string * @param values values referenced by the format specifiers in the format string. * @since 1.0 */ public static void printf(Object self, String format, Object[] values) { if (self instanceof PrintStream) ((PrintStream)self).printf(format, values); else System.out.printf(format, values); } /** * Sprintf to a string (Only works with JDK1.5 or later). * * @param self any Object * @param format a format string * @param values values referenced by the format specifiers in the format string. * @return the resulting formatted string * @since 1.5.0 */ public static String sprintf(Object self, String format, Object[] values) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(outputStream); out.printf(format, values); return outputStream.toString(); } /** * Prints a formatted string using the specified format string and * arguments. *

      * For examples,

           *     printf ( "Hello, %s!\n" , [ "world" ] as String[] )
           *     printf ( "Hello, %s!\n" , [ "Groovy" ])
           *     printf ( "%d + %d = %d\n" , [ 1 , 2 , 1+2 ] as Integer[] )
           *     printf ( "%d + %d = %d\n" , [ 3 , 3 , 3+3 ])
           * 

      * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as Integer[] ) } * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as int[] ) } * ( 0x41..0x45 ).each { printf ( "-- %c\n" , [ it ] as char[] ) } * ( 07..011 ).each { printf ( "-- %d\n" , [ it ] as byte[] ) } * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as short[] ) } * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as long[] ) } * ( 7..11 ).each { printf ( "-- %5.2f\n" , [ it ] as float[] ) } * ( 7..11 ).each { printf ( "-- %5.2g\n" , [ it ] as double[] ) } *

      *

      * * @param self any Object * @param format A format string * @param arg Argument which is referenced by the format specifiers in the format * string. The type of arg should be one of Object[], List, * int[], short[], byte[], char[], boolean[], long[], float[], or double[]. * @since 1.0 */ public static void printf(Object self, String format, Object arg) { if (self instanceof PrintStream) printf((PrintStream) self, format, arg); else if (self instanceof Writer) printf((Writer) self, format, arg); else printf(System.out, format, arg); } private static void printf(PrintStream self, String format, Object arg) { self.print(sprintf(self, format, arg)); } private static void printf(Writer self, String format, Object arg) { try { self.write(sprintf(self, format, arg)); } catch (IOException e) { printf(System.out, format, arg); } } /** * Returns a formatted string using the specified format string and * arguments. *

      * * @param self any Object * @param format A format string * @param arg Argument which is referenced by the format specifiers in the format * string. The type of arg should be one of Object[], List, * int[], short[], byte[], char[], boolean[], long[], float[], or double[]. * @return the resulting printf'd string * @since 1.5.0 */ public static String sprintf(Object self, String format, Object arg) { if (arg instanceof Object[]) { return sprintf(self, format, (Object[]) arg); } if (arg instanceof List) { return sprintf(self, format, ((List) arg).toArray()); } if (!arg.getClass().isArray()) { Object[] o = (Object[]) java.lang.reflect.Array.newInstance(arg.getClass(), 1); o[0] = arg; return sprintf(self, format, o); } Object[] ans; String elemType = arg.getClass().getName(); if (elemType.equals("[I")) { int[] ia = (int[]) arg; ans = new Integer[ia.length]; for (int i = 0; i < ia.length; i++) { ans[i] = ia[i]; } } else if (elemType.equals("[C")) { char[] ca = (char[]) arg; ans = new Character[ca.length]; for (int i = 0; i < ca.length; i++) { ans[i] = ca[i]; } } else if (elemType.equals("[Z")) { boolean[] ba = (boolean[]) arg; ans = new Boolean[ba.length]; for (int i = 0; i < ba.length; i++) { ans[i] = ba[i]; } } else if (elemType.equals("[B")) { byte[] ba = (byte[]) arg; ans = new Byte[ba.length]; for (int i = 0; i < ba.length; i++) { ans[i] = ba[i]; } } else if (elemType.equals("[S")) { short[] sa = (short[]) arg; ans = new Short[sa.length]; for (int i = 0; i < sa.length; i++) { ans[i] = sa[i]; } } else if (elemType.equals("[F")) { float[] fa = (float[]) arg; ans = new Float[fa.length]; for (int i = 0; i < fa.length; i++) { ans[i] = fa[i]; } } else if (elemType.equals("[J")) { long[] la = (long[]) arg; ans = new Long[la.length]; for (int i = 0; i < la.length; i++) { ans[i] = la[i]; } } else if (elemType.equals("[D")) { double[] da = (double[]) arg; ans = new Double[da.length]; for (int i = 0; i < da.length; i++) { ans[i] = da[i]; } } else { throw new RuntimeException("sprintf(String," + arg + ")"); } return sprintf(self, format, ans); } /** * Inspects returns the String that matches what would be typed into a * terminal to create this object. * * @param self any Object * @return a String that matches what would be typed into a terminal to * create this object. e.g. [1, 'hello'].inspect() -> [1, "hello"] * @since 1.0 */ public static String inspect(Object self) { return InvokerHelper.inspect(self); } /** * Print to a console in interactive format. * * @param self any Object * @param out the PrintWriter used for printing * @since 1.0 */ public static void print(Object self, PrintWriter out) { if (out == null) { out = new PrintWriter(System.out); } out.print(InvokerHelper.toString(self)); } /** * Print to a console in interactive format. * * @param self any Object * @param out the PrintWriter used for printing * @since 1.0 */ public static void println(Object self, PrintWriter out) { if (out == null) { out = new PrintWriter(System.out); } out.println(InvokerHelper.toString(self)); } /** * Provide a dynamic method invocation method which can be overloaded in * classes to implement dynamic proxies easily. * * @param object any Object * @param method the name of the method to call * @param arguments the arguments to use * @return the result of the method call * @since 1.0 */ public static Object invokeMethod(Object object, String method, Object arguments) { return InvokerHelper.invokeMethod(object, method, arguments); } // isCase methods //------------------------------------------------------------------------- /** * Method for overloading the behavior of the 'case' method in switch statements. * The default implementation handles arrays types but otherwise simply delegates * to Object#equals, but this may be overridden for other types. In this example: *

       switch( a ) {
           *   case b: //some code
           * }
      * "some code" is called when b.isCase( a ) returns * true. * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue is deemed to be equal to the caseValue * @since 1.0 */ public static boolean isCase(Object caseValue, Object switchValue) { if (caseValue.getClass().isArray()) { return isCase(DefaultTypeTransformation.asCollection(caseValue), switchValue); } return caseValue.equals(switchValue); } /** * 'Case' implementation for a String, which uses String#equals(Object) * in order to allow Strings to be used in switch statements. * For example: *
      switch( str ) {
           *   case 'one' :
           *   // etc...
           * }
      * Note that this returns true for the case where both the * 'switch' and 'case' operand is null. * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue's toString() equals the caseValue * @since 1.0 */ public static boolean isCase(String caseValue, Object switchValue) { if (switchValue == null) { return caseValue == null; } return caseValue.equals(switchValue.toString()); } /** * 'Case' implementation for a CharSequence, which simply calls the equivalent method for String. * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue's toString() equals the caseValue * @since 1.8.2 */ public static boolean isCase(CharSequence caseValue, Object switchValue) { return isCase(caseValue.toString(), switchValue); } /** * 'Case' implementation for a GString, which simply calls the equivalent method for String. * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue's toString() equals the caseValue * @since 1.6.0 */ public static boolean isCase(GString caseValue, Object switchValue) { return isCase(caseValue.toString(), switchValue); } /** * Special 'Case' implementation for Class, which allows testing * for a certain class in a switch statement. * For example: *
      switch( obj ) {
           *   case List :
           *     // obj is a list
           *     break;
           *   case Set :
           *     // etc
           * }
      * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue is deemed to be assignable from the given class * @since 1.0 */ public static boolean isCase(Class caseValue, Object switchValue) { if (switchValue instanceof Class) { Class val = (Class) switchValue; return caseValue.isAssignableFrom(val); } return caseValue.isInstance(switchValue); } /** * 'Case' implementation for collections which tests if the 'switch' * operand is contained in any of the 'case' values. * For example: *
      switch( 3 ) {
           *   case [1,3,5]:
           *     assert true
           *     break
           *   default:
           *     assert false
           * }
      * * @param caseValue the case value * @param switchValue the switch value * @return true if the caseValue is deemed to contain the switchValue * @see java.util.Collection#contains(java.lang.Object) * @since 1.0 */ public static boolean isCase(Collection caseValue, Object switchValue) { return caseValue.contains(switchValue); } /** * 'Case' implementation for maps which tests the groovy truth * value obtained using the 'switch' operand as key. * For example: *
      switch( 'foo' ) {
           *   case [foo:true, bar:false]:
           *     assert true
           *     break
           *   default:
           *     assert false
           * }
      * * @param caseValue the case value * @param switchValue the switch value * @return the groovy truth value from caseValue corresponding to the switchValue key * @since 1.7.6 */ public static boolean isCase(Map caseValue, Object switchValue) { return DefaultTypeTransformation.castToBoolean(caseValue.get(switchValue)); } /** * 'Case' implementation for the {@link java.util.regex.Pattern} class, which allows * testing a String against a number of regular expressions. * For example: *
      switch( str ) {
           *   case ~/one/ :
           *     // the regex 'one' matches the value of str
           * }
           * 
      * Note that this returns true for the case where both the pattern and * the 'switch' values are null. * * @param caseValue the case value * @param switchValue the switch value * @return true if the switchValue is deemed to match the caseValue * @since 1.0 */ public static boolean isCase(Pattern caseValue, Object switchValue) { if (switchValue == null) { return caseValue == null; } final Matcher matcher = caseValue.matcher(switchValue.toString()); if (matcher.matches()) { RegexSupport.setLastMatcher(matcher); return true; } else { return false; } } /** * Special 'case' implementation for all numbers, which delegates to the * compareTo() method for comparing numbers of different * types. * * @param caseValue the case value * @param switchValue the switch value * @return true if the numbers are deemed equal * @since 1.5.0 */ public static boolean isCase(Number caseValue, Number switchValue) { return NumberMath.compareTo(caseValue, switchValue) == 0; } /** * Returns an iterator equivalent to this iterator all duplicated items removed * by using the default comparator. The original iterator will become * exhausted of elements after determining the unique values. A new iterator * for the unique values will be returned. * * @param self an Iterator * @return the modified Iterator * @since 1.5.5 */ public static Iterator unique(Iterator self) { return toList(unique(toList(self))).listIterator(); } /** * Modifies this collection to remove all duplicated items, using the * default comparator. *
      assert [1,3] == [1,3,3].unique()
      * * @param self a collection * @return the now modified collection * @see #unique(Collection, boolean) * @since 1.0 */ public static Collection unique(Collection self) { return unique(self, true); } /** * Remove all duplicates from a given Collection using the default comparator. * If mutate is true, it works by modifying the original object (and also returning it). * If mutate is false, a new collection is returned leaving the original unchanged. *
           * assert [1,3] == [1,3,3].unique()
           * 
      *
           * def orig = [1, 3, 2, 3]
           * def uniq = orig.unique(false)
           * assert orig == [1, 3, 2, 3]
           * assert uniq == [1, 3, 2]
           * 
      * * @param self a collection * @param mutate false will cause a new list containing unique items from the collection to be created, true will mutate collections in place * @return the now modified collection * @since 1.8.1 */ public static Collection unique(Collection self, boolean mutate) { List answer = new ArrayList(); for (T t : self) { boolean duplicated = false; for (T t2 : answer) { if (coercedEquals(t, t2)) { duplicated = true; break; } } if (!duplicated) answer.add(t); } if (mutate) { self.clear(); self.addAll(answer); } return mutate ? self : answer ; } /** * Provides a method that compares two comparables using Groovy's * default number aware comparator. * * @param self a Comparable * @param other another Comparable * @return a -ve number, 0 or a +ve number according to Groovy's compareTo contract * @since 1.6.0 */ public static int numberAwareCompareTo(Comparable self, Comparable other) { NumberAwareComparator numberAwareComparator = new NumberAwareComparator(); return numberAwareComparator.compare(self, other); } /** * Returns an iterator equivalent to this iterator but with all duplicated items * removed by using a Closure to determine duplicate (equal) items. * The original iterator will be fully processed after the call. *

      * If the closure takes a * single parameter, the argument passed will be each element, and the * closure should return a value used for comparison (either using * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}). * If the closure takes two parameters, two items from the Iterator * will be passed as arguments, and the closure should return an * int value (with 0 indicating the items are not unique). * * @param self an Iterator * @param closure a Closure used to determine unique items * @return the modified Iterator * @since 1.5.5 */ public static Iterator unique(Iterator self, Closure closure) { return toList(unique(toList(self), closure)).listIterator(); } /** * A convenience method for making a collection unique using a Closure * to determine duplicate (equal) items. *

      * If the closure takes a single parameter, the * argument passed will be each element, and the closure * should return a value used for comparison (either using * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}). * If the closure takes two parameters, two items from the collection * will be passed as arguments, and the closure should return an * int value (with 0 indicating the items are not unique). *
      assert [1,4] == [1,3,4,5].unique { it % 2 }
      *
      assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }
      * * @param self a Collection * @param closure a 1 or 2 arg Closure used to determine unique items * @return self without any duplicates * @see #unique(Collection, boolean, Closure) * @since 1.0 */ public static Collection unique(Collection self, Closure closure) { return unique(self, true, closure); } /** * A convenience method for making a collection unique using a Closure to determine duplicate (equal) items. * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned. *

      * If the closure takes a single parameter, the * argument passed will be each element, and the closure * should return a value used for comparison (either using * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}). * If the closure takes two parameters, two items from the collection * will be passed as arguments, and the closure should return an * int value (with 0 indicating the items are not unique). *
           * def orig = [1, 3, 4, 5]
           * def uniq = orig.unique(false) { it % 2 }
           * assert orig == [1, 3, 4, 5]
           * assert uniq == [1, 4]
           * 
      *
           * def orig = [2, 3, 3, 4]
           * def uniq = orig.unique(false) { a, b -> a <=> b }
           * assert orig == [2, 3, 3, 4]
           * assert uniq == [2, 3, 4]
           * 
      * * @param self a Collection * @param mutate false will always cause a new list to be created, true will mutate lists in place * @param closure a 1 or 2 arg Closure used to determine unique items * @return self without any duplicates * @since 1.8.1 */ public static Collection unique(Collection self, boolean mutate, Closure closure) { // use a comparator of one item or two int params = closure.getMaximumNumberOfParameters(); if (params == 1) { OrderBy by = new OrderBy(closure); by.setEqualityCheck(true); self = unique(self, mutate, by); } else { self = unique(self, mutate, new ClosureComparator(closure)); } return self; } /** * Returns an iterator equivalent to this iterator with all duplicated * items removed by using the supplied comparator. * * @param self an Iterator * @param comparator a Comparator * @return the modified Iterator * @since 1.5.5 */ public static Iterator unique(Iterator self, Comparator comparator) { return toList(unique(toList(self), comparator)).listIterator(); } /** * Remove all duplicates from a given Collection. * Works on the original object (and also returns it). * The order of members in the Collection are compared by the given Comparator. * For each duplicate, the first member which is returned * by the given Collection's iterator is retained, but all other ones are removed. * The given Collection's original order is preserved. *

      *

           *     class Person {
           *         def fname, lname
           *         String toString() {
           *             return fname + " " + lname
           *         }
           *     }
           *
           *     class PersonComparator implements Comparator {
           *         int compare(Object o1, Object o2) {
           *             Person p1 = (Person) o1
           *             Person p2 = (Person) o2
           *             if (p1.lname != p2.lname)
           *                 return p1.lname.compareTo(p2.lname)
           *             else
           *                 return p1.fname.compareTo(p2.fname)
           *         }
           *
           *         boolean equals(Object obj) {
           *             return this.equals(obj)
           *         }
           *     }
           *
           *     Person a = new Person(fname:"John", lname:"Taylor")
           *     Person b = new Person(fname:"Clark", lname:"Taylor")
           *     Person c = new Person(fname:"Tom", lname:"Cruz")
           *     Person d = new Person(fname:"Clark", lname:"Taylor")
           *
           *     def list = [a, b, c, d]
           *     List list2 = list.unique(new PersonComparator())
           *     assert( list2 == list && list == [a, b, c] )
           * 
      * * @param self a Collection * @param comparator a Comparator * @return self the now modified collection without duplicates * @see #unique(java.util.Collection, boolean, java.util.Comparator) * @since 1.0 */ public static Collection unique(Collection self, Comparator comparator) { return unique(self, true, comparator) ; } /** * Remove all duplicates from a given Collection. * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new collection is returned. * The order of members in the Collection are compared by the given Comparator. * For each duplicate, the first member which is returned * by the given Collection's iterator is retained, but all other ones are removed. * The given Collection's original order is preserved. *

      *

           *     class Person {
           *         def fname, lname
           *         String toString() {
           *             return fname + " " + lname
           *         }
           *     }
           *
           *     class PersonComparator implements Comparator {
           *         int compare(Object o1, Object o2) {
           *             Person p1 = (Person) o1
           *             Person p2 = (Person) o2
           *             if (p1.lname != p2.lname)
           *                 return p1.lname.compareTo(p2.lname)
           *             else
           *                 return p1.fname.compareTo(p2.fname)
           *         }
           *
           *         boolean equals(Object obj) {
           *             return this.equals(obj)
           *         }
           *     }
           *
           *     Person a = new Person(fname:"John", lname:"Taylor")
           *     Person b = new Person(fname:"Clark", lname:"Taylor")
           *     Person c = new Person(fname:"Tom", lname:"Cruz")
           *     Person d = new Person(fname:"Clark", lname:"Taylor")
           *
           *     def list = [a, b, c, d]
           *     List list2 = list.unique(false, new PersonComparator())
           *     assert( list2 != list && list2 == [a, b, c] )
           * 
      * * * @param self a Collection * @param mutate false will always cause a new collection to be created, true will mutate collections in place * @param comparator a Comparator * @return self the collection without duplicates * @since 1.8.1 */ public static Collection unique(Collection self, boolean mutate, Comparator comparator) { List answer = new ArrayList(); for (T t : self) { boolean duplicated = false; for (T t2 : answer) { if (comparator.compare(t, t2) == 0) { duplicated = true; break; } } if (!duplicated) answer.add(t); } if (mutate) { self.clear(); self.addAll(answer); } return mutate ? self : answer; } /** * Iterates through an aggregate type or data structure, * passing each item to the given closure. Custom types may utilize this * method by simply providing an "iterator()" method. The items returned * from the resulting iterator will be passed to the closure. * * @param self the object over which we iterate * @param closure the closure applied on each element found * @return the self Object * @since 1.0 */ public static T each(T self, Closure closure) { each(InvokerHelper.asIterator(self), closure); return self; } /** * Iterates through an aggregate type or data structure, * passing each item and the item's index (a counter starting at * zero) to the given closure. * * @param self an Object * @param closure a Closure to operate on each item * @return the self Object * @since 1.0 */ public static T eachWithIndex(T self, Closure closure) { final Object[] args = new Object[2]; int counter = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { args[0] = iter.next(); args[1] = counter++; closure.call(args); } return self; } private static Iterator each(Iterator iter, Closure closure) { while (iter.hasNext()) { Object arg = iter.next(); closure.call(arg); } return iter; } /** * Allows a Map to be iterated through using a closure. If the * closure takes one parameter then it will be passed the Map.Entry * otherwise if the closure takes two parameters then it will be * passed the key and the value. *
      def result = ""
           * [a:1, b:3].each { key, value -> result += "$key$value" }
           * assert result == "a1b3"
      *
      def result = ""
           * [a:1, b:3].each { entry -> result += entry }
           * assert result == "a=1b=3"
      * * In general, the order in which the map contents are processed * cannot be guaranteed. In practise, specialized forms of Map, * e.g. a TreeMap will have its contents processed according to * the natural ordering of the map. * * @param self the map over which we iterate * @param closure the 1 or 2 arg closure applied on each entry of the map * @return returns the self parameter * @since 1.5.0 */ public static Map each(Map self, Closure closure) { for (Map.Entry entry : self.entrySet()) { callClosureForMapEntry(closure, entry); } return self; } /** * Allows a Map to be iterated through in reverse order using a closure. * * In general, the order in which the map contents are processed * cannot be guaranteed. In practise, specialized forms of Map, * e.g. a TreeMap will have its contents processed according to the * reverse of the natural ordering of the map. * * @param self the map over which we iterate * @param closure the 1 or 2 arg closure applied on each entry of the map * @return returns the self parameter * @see #each(Map, Closure) * @since 1.7.2 */ public static Map reverseEach(Map self, Closure closure) { final Iterator> entries = reverse(self.entrySet().iterator()); while (entries.hasNext()) { callClosureForMapEntry(closure, entries.next()); } return self; } /** * Allows a Map to be iterated through using a closure. If the * closure takes two parameters then it will be passed the Map.Entry and * the item's index (a counter starting at zero) otherwise if the closure * takes three parameters then it will be passed the key, the value, and * the index. *
      def result = ""
           * [a:1, b:3].eachWithIndex { key, value, index -> result += "$index($key$value)" }
           * assert result == "0(a1)1(b3)"
      *
      def result = ""
           * [a:1, b:3].eachWithIndex { entry, index -> result += "$index($entry)" }
           * assert result == "0(a=1)1(b=3)"
      * * @param self the map over which we iterate * @param closure a 2 or 3 arg Closure to operate on each item * @return the self Object * @since 1.5.0 */ public static Map eachWithIndex(Map self, Closure closure) { int counter = 0; for (Map.Entry entry : self.entrySet()) { callClosureForMapEntryAndCounter(closure, entry, counter++); } return self; } /** * Iterate over each element of the list in the reverse order. *
      def result = []
           * [1,2,3].reverseEach { result << it }
           * assert result == [3,2,1]
      * * @param self a List * @param closure a closure to which each item is passed. * @return the original list * @since 1.5.0 */ public static List reverseEach(List self, Closure closure) { each(new ReverseListIterator(self), closure); return self; } /** * Iterate over each element of the array in the reverse order. * * @param self an Object array * @param closure a closure to which each item is passed * @return the original array * @since 1.5.2 */ public static T[] reverseEach(T[] self, Closure closure) { each(new ReverseListIterator(Arrays.asList(self)), closure); return self; } /** * Used to determine if the given predicate closure is valid (i.e.&nsbp;returns * true for all items in this data structure). * A simple example for a list: *
      def list = [3,4,5]
           * def greaterThanTwo = list.every { it > 2 }
           * 
      * * @param self the object over which we iterate * @param closure the closure predicate used for matching * @return true if every iteration of the object matches the closure predicate * @since 1.0 */ public static boolean every(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (!DefaultTypeTransformation.castToBoolean(closure.call(iter.next()))) { return false; } } return true; } /** * Iterates over the entries of a map, and checks whether a predicate is * valid for all entries. If the * closure takes one parameter then it will be passed the Map.Entry * otherwise if the closure takes two parameters then it will be * passed the key and the value. *
      def map = [a:1, b:2.0, c:2L]
           * assert !map.every { key, value -> value instanceof Integer }
           * assert map.every { entry -> entry.value instanceof Number }
      * * @param self the map over which we iterate * @param closure the 1 or 2 arg Closure predicate used for matching * @return true if every entry of the map matches the closure predicate * @since 1.5.0 */ public static boolean every(Map self, Closure closure) { for (Map.Entry entry : self.entrySet()) { if (!DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) { return false; } } return true; } /** * Iterates over every element of a collection, and checks whether all * elements are true according to the Groovy Truth. * Equivalent to self.every({element -> element}) * * @param self the object over which we iterate * @return true if every item in the collection matches the closure * predicate * @since 1.5.0 */ public static boolean every(Object self) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (!DefaultTypeTransformation.castToBoolean(iter.next())) { return false; } } return true; } /** * Iterates over the contents of an object or collection, and checks whether a * predicate is valid for at least one element. * * @param self the object over which we iterate * @param closure the closure predicate used for matching * @return true if any iteration for the object matches the closure predicate * @since 1.0 */ public static boolean any(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (DefaultTypeTransformation.castToBoolean(closure.call(iter.next()))) { return true; } } return false; } /** * Iterates over the entries of a map, and checks whether a predicate is * valid for at least one entry. If the * closure takes one parameter then it will be passed the Map.Entry * otherwise if the closure takes two parameters then it will be * passed the key and the value. *
           * assert [2:3, 4:5, 5:10].any { key, value -> key * 2 == value }
           * assert ![2:3, 4:5, 5:10].any { entry -> entry.key == entry.value * 2 }
           * 
      * * @param self the map over which we iterate * @param closure the 1 or 2 arg closure predicate used for matching * @return true if any entry in the map matches the closure predicate * @since 1.5.0 */ public static boolean any(Map self, Closure closure) { for (Map.Entry entry : self.entrySet()) { if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) { return true; } } return false; } /** * Iterates over the elements of a collection, and checks whether at least * one element is true according to the Groovy Truth. * Equivalent to self.any({element -> element}) * * @param self the object over which we iterate * @return true if any item in the collection matches the closure predicate * @since 1.5.0 */ public static boolean any(Object self) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (DefaultTypeTransformation.castToBoolean(iter.next())) { return true; } } return false; } /** * Iterates over the collection of items which this Object represents and returns each item that matches * the given filter - calling the {@link #isCase(java.lang.Object, java.lang.Object)} * method used by switch statements. This method can be used with different * kinds of filters like regular expressions, classes, ranges etc. * Example: *
           * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
           * assert list.grep( ~/a+/ )  == ['a', 'aa']
           * assert list.grep( ~/../ )  == ['aa', 'bc']
           * assert list.grep( Number ) == [ 3, 4.5 ]
           * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
           * 
      * * @param self the object over which we iterate * @param filter the filter to perform on the object (using the {@link #isCase(java.lang.Object, java.lang.Object)} method) * @return a collection of objects which match the filter * @since 1.5.6 */ public static Collection grep(Object self, Object filter) { Collection answer = createSimilarOrDefaultCollection(self); MetaClass metaClass = InvokerHelper.getMetaClass(filter); for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object object = iter.next(); if (DefaultTypeTransformation.castToBoolean(metaClass.invokeMethod(filter, "isCase", object))) { answer.add(object); } } return answer; } /** * Iterates over the collection of items which this Object represents and returns each item that matches * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth. *

      * Example: *

           * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
           * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
           * 
      * * @param self the object over which we iterate * @return a collection of objects which match the filter * @since 1.8.1 * @see Closure#IDENTITY */ public static Collection grep(Object self) { return grep(self, Closure.IDENTITY); } /** * Counts the number of occurrences of the given value from the * items within this Iterator. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * The iterator will become exhausted of elements after determining the count value. * * @param self the Iterator from which we count the number of matching occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.5.0 */ public static Number count(Iterator self, Object value) { long answer = 0; while (self.hasNext()) { if (DefaultTypeTransformation.compareEqual(self.next(), value)) { ++answer; } } // for b/c with Java return an int if we can if (answer <= Integer.MAX_VALUE) return (int) answer; return answer; } /** * Counts the number of occurrences which satisfy the given closure from the * items within this Iterator. * The iterator will become exhausted of elements after determining the count value. *

      * Example usage: *

      assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2
      * * @param self the Iterator from which we count the number of matching occurrences * @param closure a closure condition * @return the number of occurrences * @since 1.8.0 */ public static Number count(Iterator self, Closure closure) { long answer = 0; while (self.hasNext()) { if (DefaultTypeTransformation.castToBoolean(closure.call(self.next()))) { ++answer; } } // for b/c with Java return an int if we can if (answer <= Integer.MAX_VALUE) return (int) answer; return answer; } /** * Counts the number of occurrences of the given value inside this collection. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). *

      * Example usage: *

      assert [2,4,2,1,3,5,2,4,3].count(4) == 2
      * * @param self the collection within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.0 */ public static Number count(Collection self, Object value) { return count(self.iterator(), value); } /** * Counts the number of occurrences which satisfy the given closure from inside this collection. *

      * Example usage: *

      assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5
      * * @param self the collection within which we count the number of occurrences * @param closure a closure condition * @return the number of occurrences * @since 1.8.0 */ public static Number count(Collection self, Closure closure) { return count(self.iterator(), closure); } /** * Counts the number of occurrences which satisfy the given closure from inside this map. * If the closure takes one parameter then it will be passed the Map.Entry. * Otherwise, the closure should take two parameters and will be passed the key and value. *

      * Example usage: *

      assert [a:1, b:1, c:2, d:2].count{ k,v -> k == 'a' || v == 2 } == 3
      * * @param self the map within which we count the number of occurrences * @param closure a 1 or 2 arg Closure condition applying on the entries * @return the number of occurrences * @since 1.8.0 */ public static Number count(Map self, Closure closure) { long answer = 0; for (Object entry : self.entrySet()) { if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, (Map.Entry) entry))) { ++answer; } } // for b/c with Java return an int if we can if (answer <= Integer.MAX_VALUE) return (int) answer; return answer; } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(Object[] self, Object value) { return count(Arrays.asList(self), value); } /** * Counts the number of occurrences which satisfy the given closure from inside this array. * * @param self the array within which we count the number of occurrences * @param closure a closure condition * @return the number of occurrences * @since 1.8.0 */ public static Number count(Object[] self, Closure closure) { return count(Arrays.asList(self), closure); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(int[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(long[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(short[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(char[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(boolean[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(double[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(float[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Counts the number of occurrences of the given value inside this array. * Comparison is done using Groovy's == operator (using * compareTo(value) == 0 or equals(value) ). * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.6.4 */ public static Number count(byte[] self, Object value) { return count(InvokerHelper.asIterator(self), value); } /** * Convert a Collection to a List. Always returns a new List * even if the Collection is already a List. *

      * Example usage: *

      def x = [1,2,3] as HashSet
           * assert x.class == HashSet
           * assert x.toList() instanceof List
      * * @param self a collection * @return a List * @since 1.0 */ public static List toList(Collection self) { List answer = new ArrayList(self.size()); answer.addAll(self); return answer; } /** * Convert an iterator to a List. The iterator will become * exhausted of elements after making this conversion. * * @param self an iterator * @return a List * @since 1.5.0 */ public static List toList(Iterator self) { List answer = new ArrayList(); while (self.hasNext()) { answer.add(self.next()); } return answer; } /** * Convert an enumeration to a List. * * @param self an enumeration * @return a List * @since 1.5.0 */ public static List toList(Enumeration self) { List answer = new ArrayList(); while (self.hasMoreElements()) { answer.add(self.nextElement()); } return answer; } /** * Collates this list into sub-lists of length size. * Example: *
      def list = [ 1, 2, 3, 4, 5, 6, 7 ]
           * def coll = list.collate( 3 )
           * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
      * * @param self a List * @param size the length of each sub-list in the returned list * @return a List containing the data collated into sub-lists * @since 1.8.6 */ public static List> collate( List self, int size ) { return collate( self, size, size, true ) ; } /** * Collates this list into sub-lists of length size stepping through the code step * elements for each subList. * Example: *
      def list = [ 1, 2, 3, 4 ]
           * def coll = list.collate( 3, 1 )
           * assert coll == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
      * * @param self a List * @param size the length of each sub-list in the returned list * @param step the number of elements to step through for each sub-list * @return a List containing the data collated into sub-lists * @since 1.8.6 */ public static List> collate( List self, int size, int step ) { return collate( self, size, step, true ) ; } /** * Collates this list into sub-lists of length size. Any remaining elements in * the list after the subdivision will be dropped if keepRemainder is false. * Example: *
      def list = [ 1, 2, 3, 4, 5, 6, 7 ]
           * def coll = list.collate( 3, false )
           * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
      * * @param self a List * @param size the length of each sub-list in the returned list * @param keepRemainder if true, any rmeaining elements are returned as sub-lists. Otherwise they are discarded * @return a List containing the data collated into sub-lists * @since 1.8.6 */ public static List> collate( List self, int size, boolean keepRemainder ) { return collate( self, size, size, keepRemainder ) ; } /** * Collates this list into sub-lists of length size stepping through the code step * elements for each sub-list. Any remaining elements in the list after the subdivision will be dropped if * keepRemainder is false. * Example: *
      def list = [ 1, 2, 3, 4 ]
           * assert list.collate( 3, 1, true  ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
           * assert list.collate( 3, 1, false ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ] ]
      * * @param self a List * @param size the length of each sub-list in the returned list * @param step the number of elements to step through for each sub-list * @param keepRemainder if true, any rmeaining elements are returned as sub-lists. Otherwise they are discarded * @return a List containing the data collated into sub-lists * @since 1.8.6 */ public static List> collate( List self, int size, int step, boolean keepRemainder ) { List> answer = new ArrayList>(); if( size <= 0 || self.size() == 0 ) { answer.add( self ) ; } else { for( int pos = 0 ; pos < self.size() && pos > -1 ; pos += step ) { if( !keepRemainder && pos > self.size() - size ) { break ; } List element = new ArrayList() ; for( int offs = pos ; offs < pos + size && offs < self.size() ; offs++ ) { element.add( self.get( offs ) ) ; } answer.add( element ) ; } } return answer ; } /** * Iterates through this aggregate Object transforming each item into a new value using the * transform closure, returning a list of transformed values. * Example: *
      def list = [1, 'a', 1.23, true ]
           * def types = list.collect { it.class }
           * assert types == [Integer, String, BigDecimal, Boolean]
      * * @param self an aggregate Object with an Iterator returning its items * @param transform the closure used to transform each item of the aggregate object * @return a List of the transformed values * @since 1.0 */ public static List collect(Object self, Closure transform) { return (List) collect(self, new ArrayList(), transform); } /** * Iterates through this aggregate Object transforming each item into a new value using Closure.IDENTITY * as a transformer, basically returning a list of items copied from the original object. *
      assert [1,2,3] == [1,2,3].iterator().collect()
      * * @param self an aggregate Object with an Iterator returning its items * @return a List of the transformed values * @see Closure#IDENTITY * @since 1.8.5 */ public static Collection collect(Object self) { return collect(self, Closure.IDENTITY); } /** * Iterates through this aggregate Object transforming each item into a new value using the transform closure * and adding it to the supplied collector. * * @param self an aggregate Object with an Iterator returning its items * @param collector the Collection to which the transformed values are added * @param transform the closure used to transform each item of the aggregate object * @return the collector with all transformed values added to it * @since 1.0 */ public static Collection collect(Object self, Collection collector, Closure transform) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) { collector.add(transform.call(iter.next())); } return collector; } /** * Iterates through this collection transforming each entry into a new value using the transform closure * returning a list of transformed values. *
      assert [2,4,6] == [1,2,3].collect { it * 2 }
      * * @param self a collection * @param transform the closure used to transform each item of the collection * @return a List of the transformed values * @since 1.0 */ public static List collect(Collection self, Closure transform) { return (List) collect(self, new ArrayList(self.size()), transform); } /** * Iterates through this collection transforming each entry into a new value using Closure.IDENTITY * as a transformer, basically returning a list of items copied from the original collection. *
      assert [1,2,3] == [1,2,3].collect()
      * * @param self a collection * @return a List of the transformed values * @since 1.8.5 * @see Closure#IDENTITY */ public static List collect(Collection self) { return (List) collect(self, Closure.IDENTITY); } /** * Iterates through this collection transforming each value into a new value using the transform closure * and adding it to the supplied collector. *
      assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }
      * * @param self a collection * @param collector the Collection to which the transformed values are added * @param transform the closure used to transform each item of the collection * @return the collector with all transformed values added to it * @since 1.0 */ public static Collection collect(Collection self, Collection collector, Closure transform) { for (Object item : self) { collector.add(transform.call(item)); if (transform.getDirective() == Closure.DONE) { break; } } return collector; } /** * Deprecated alias for collectNested * * @deprecated Use collectNested instead * @see #collectNested(Collection, Closure) */ public static List collectAll(Collection self, Closure transform) { return collectNested(self, transform); } /** * Recursively iterates through this collection transforming each non-Collection value * into a new value using the closure as a transformer. Returns a potentially nested * list of transformed values. *
           * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
           * 
      * * @param self a collection * @param transform the closure used to transform each item of the collection * @return the resultant collection * @since 1.8.1 */ public static List collectNested(Collection self, Closure transform) { return (List) collectNested(self, new ArrayList(self.size()), transform); } /** * Deprecated alias for collectNested * * @deprecated Use collectNested instead * @see #collectNested(Collection, Collection, Closure) */ public static Collection collectAll(Collection self, Collection collector, Closure transform) { return collectNested(self, collector, transform); } /** * Recursively iterates through this collection transforming each non-Collection value * into a new value using the transform closure. Returns a potentially nested * collection of transformed values. *
      def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 }
           * assert x == [2,[4,6],[8],[]]
           * assert x instanceof Vector
      * * @param self a collection * @param collector an initial Collection to which the transformed values are added * @param transform the closure used to transform each element of the collection * @return the collector with all transformed values added to it * @since 1.8.1 */ public static Collection collectNested(Collection self, Collection collector, Closure transform) { for (Object item : self) { if (item instanceof Collection) { Collection c = (Collection) item; collector.add(collectNested(c, createSimilarCollection(collector, c.size()), transform)); } else { collector.add(transform.call(item)); } if (transform.getDirective() == Closure.DONE) { break; } } return collector; } /** * Projects each item from a source collection to a collection and concatenates (flattens) the resulting collections into a single list. *

      *

           * def nums = 1..10
           * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
           * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
           *
           * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
           * def smallAnimals = animals.collectMany{ it.size() > 3 ? [] : [it.toLowerCase()] }
           * assert smallAnimals == ['cat', 'dog']
           *
           * def orig = nums as Set
           * def origPlusIncrements = orig.collectMany{ [it, it+1] }
           * assert origPlusIncrements.size() == orig.size() * 2
           * assert origPlusIncrements.unique().size() == orig.size() + 1
           * 
      * * @param self a collection * @param projection a projecting Closure returning a collection of items * @return a list created from the projected collections concatenated (flattened) together * @see #sum(java.util.Collection, groovy.lang.Closure) * @since 1.8.1 */ public static List collectMany(Collection self, Closure> projection) { return (List) collectMany(self, new ArrayList(), projection); } /** * Projects each item from a source collection to a result collection and concatenates (flattens) the resulting * collections adding them into the collector. *

      *

           * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
           * def smallAnimals = animals.collectMany(['ant', 'bee']){ it.size() > 3 ? [] : [it.toLowerCase()] }
           * assert smallAnimals == ['ant', 'bee', 'cat', 'dog']
           *
           * def nums = 1..5
           * def origPlusIncrements = nums.collectMany([] as Set){ [it, it+1] }
           * assert origPlusIncrements.size() == nums.size() + 1
           * 
      * * @param self a collection * @param collector an initial collection to add the projected items to * @param projection a projecting Closure returning a collection of items * @return the collector with the projected collections concatenated (flattened) to it * @since 1.8.5 */ public static Collection collectMany(Collection self, Collection collector, Closure> projection) { for (Object next : self) { collector.addAll(projection.call(next)); } return collector; } /** * Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list. *

      *

           * def nums = [1, 2, 3, 4, 5, 6] as Object[]
           * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
           * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
           * 
      * * @param self an object array * @param projection a projecting Closure returning a collection of items * @return a list created from the projected collections concatenated (flattened) together * @see #sum(Object[], groovy.lang.Closure) * @since 1.8.1 */ public static List collectMany(Object[] self, Closure> projection) { return collectMany(toList(self), projection); } /** * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list. *

      *

           * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
           * def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
           * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
           * 
      * * @param self an iterator * @param projection a projecting Closure returning a collection of items * @return a list created from the projected collections concatenated (flattened) together * @see #sum(Iterator, groovy.lang.Closure) * @since 1.8.1 */ public static List collectMany(Iterator self, Closure> projection) { return collectMany(toList(self), projection); } /** * Iterates through this Map transforming each map entry into a new value using the transform closure * returning the collector with all transformed vakues added to it. *
      assert [a:1, b:2].collect( [] as HashSet ) { key, value -> key*value } == ["a", "bb"] as Set
           * assert [3:20, 2:30].collect( [] as HashSet ) { entry -> entry.key * entry.value } == [60] as Set
      * * @param self a Map * @param collector the Collection to which transformed values are added * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters * @return the collector with all transformed values added to it * @since 1.0 */ public static Collection collect(Map self, Collection collector, Closure transform) { for (Map.Entry entry : self.entrySet()) { collector.add(callClosureForMapEntry(transform, entry)); } return collector; } /** * Iterates through this Map transforming each map entry into a new value using the transform closure * returning a list of transformed values. *
      assert [a:1, b:2].collect { key, value -> key*value } == ["a", "bb"]
           * assert [3:20, 2:30].collect { entry -> entry.key * entry.value } == [60, 60]
      * * @param self a Map * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters * @return the resultant list of transformed values * @since 1.0 */ public static List collect(Map self, Closure transform) { return (List) collect(self, new ArrayList(self.size()), transform); } /** * Iterates through this Map transforming each map entry using the transform closure * returning a map of the transformed entries. *
           * assert [a:1, b:2].collectEntries( [:] ) { k, v -> [v, k] } == [1:'a', 2:'b']
           * assert [a:1, b:2].collectEntries( [30:'C'] ) { key, value ->
           *     [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
           * 
      * * @param self a Map * @param collector the Map into which the transformed entries are put * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return the collector with all transformed values added to it * @see #collect(Map, Collection, Closure) * @since 1.7.9 */ public static Map collectEntries(Map self, Map collector, Closure transform) { for (Map.Entry entry : self.entrySet()) { addEntry(collector, callClosureForMapEntry(transform, entry)); } return collector; } /** * Iterates through this Map transforming each entry using the transform closure * and returning a map of the transformed entries. *
           * assert [a:1, b:2].collectEntries { key, value -> [value, key] } == [1:'a', 2:'b']
           * assert [a:1, b:2].collectEntries { key, value ->
           *     [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
           * 
      * * @param self a Map * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return a Map of the transformed entries * @see #collect(Map, Collection, Closure) * @since 1.7.9 */ public static Map collectEntries(Map self, Closure transform) { return collectEntries(self, createSimilarMap(self), transform); } /** * Iterates through this Collection transforming each item using the transform closure * and returning a map of the resulting transformed entries. *
           * def letters = "abc"
           * // collect letters with index using list style
           * assert (0..2).collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
           * // collect letters with index using map style
           * assert (0..2).collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
           * 
      * * @param self a Collection * @param transform the closure used for transforming, which has an item from self as the parameter and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return a Map of the transformed entries * @see #collectEntries(Collection, Map, Closure) * @since 1.7.9 */ public static Map collectEntries(Collection self, Closure transform) { return collectEntries(self, new LinkedHashMap(), transform); } /** * A variant of collectEntries using the identity closure as the transform. * The source collection should be a list of [key, value] tuples or a Map.Entry. *
           * def nums = [1, 10, 100, 1000]
           * def tuples = nums.collect{ [it, it.toString().size()] }
           * assert tuples == [[1, 1], [10, 2], [100, 3], [1000, 4]]
           * def map = tuples.collectEntries()
           * assert map == [1:1, 10:2, 100:3, 1000:4]
           * 
      * * @param self a Collection * @return a Map of the transformed entries * @see #collectEntries(Collection, Closure) * @since 1.8.5 */ public static Map collectEntries(Collection self) { return collectEntries(self, new LinkedHashMap(), Closure.IDENTITY); } /** * Iterates through this Collection transforming each item using the closure * as a transformer into a map entry, returning a map of the transformed entries. *
           * def letters = "abc"
           * // collect letters with index
           * assert (0..2).collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
           * assert (0..2).collectEntries( [4:'d'] ) { index ->
           *     [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
           * 
      * * @param self a Collection * @param collector the Map into which the transformed entries are put * @param transform the closure used for transforming, which has an item from self as the parameter and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return the collector with all transformed values added to it * @see #collect(Map, Collection, Closure) * @since 1.7.9 */ public static Map collectEntries(Collection self, Map collector, Closure transform) { for (Object next : self) { addEntry(collector, transform.call(next)); } return collector; } /** * A variant of collectEntries using the identity closure as the transform. * * @param self a Collection * @param collector the Map into which the transformed entries are put * @return the collector with all transformed values added to it * @see #collectEntries(Collection, Map, Closure) * @since 1.8.5 */ public static Map collectEntries(Collection self, Map collector) { return collectEntries(self, collector, Closure.IDENTITY); } /** * Iterates through this array transforming each item using the transform closure * and returning a map of the resulting transformed entries. *
           * def letters = "abc"
           * def nums = [0, 1, 2] as Integer[]
           * // collect letters with index
           * assert nums.collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
           * assert nums.collectEntries( [4:'d'] ) { index ->
           *     [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
           * 
      * * @param self an Object array * @param collector the Map into which the transformed entries are put * @param transform the closure used for transforming, which has an item from self as the parameter and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return the collector with all transformed values added to it * @see #collect(Map, Collection, Closure) * @since 1.7.9 */ public static Map collectEntries(Object[] self, Map collector, Closure transform) { return collectEntries(toList(self), collector, transform); } /** * A variant of collectEntries using the identity closure as the transform. * * @param self an Object array * @param collector the Map into which the transformed entries are put * @return the collector with all transformed values added to it * @see #collectEntries(Object[], Map, Closure) * @since 1.8.5 */ public static Map collectEntries(Object[] self, Map collector) { return collectEntries(self, collector, Closure.IDENTITY); } /** * Iterates through this array transforming each item using the transform closure * and returning a map of the resulting transformed entries. *
           * def letters = "abc"
           * def nums = [0, 1, 2] as Integer[]
           * // collect letters with index using list style
           * assert nums.collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
           * // collect letters with index using map style
           * assert nums.collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
           * 
      * * @param self a Collection * @param transform the closure used for transforming, which has an item from self as the parameter and * should return a Map.Entry, a Map or a two-element list containing the resulting key and value * @return a Map of the transformed entries * @see #collectEntries(Collection, Map, Closure) * @since 1.7.9 */ public static Map collectEntries(Object[] self, Closure transform) { return collectEntries(toList(self), new LinkedHashMap(), transform); } /** * A variant of collectEntries using the identity closure as the transform. * * @param self an Object array * @return the collector with all transformed values added to it * @see #collectEntries(Object[], Closure) * @since 1.8.5 */ public static Map collectEntries(Object[] self) { return collectEntries(self, Closure.IDENTITY); } private static void addEntry(Map result, Object newEntry) { if (newEntry instanceof Map) { leftShift(result, (Map)newEntry); } else if (newEntry instanceof List && ((List)newEntry).size() == 2) { List list = (List) newEntry; leftShift(result, new MapEntry(list.get(0), list.get(1))); } else { // TODO: enforce stricter behavior? // given Map.Entry is an interface, we get a proxy which gives us lots // of flexibility but sometimes the error messages might be unexpected leftShift(result, asType(newEntry, Map.Entry.class)); } } /** * Finds the first value matching the closure condition * * @param self an Object with an iterator returning its values * @param closure a closure condition * @return the first Object found or null if none was found * @since 1.0 */ public static Object find(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object value = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { return value; } } return null; } /** * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth). *

      * Example: *

           * def items = [null, 0, 0.0, false, '', [], 42, 43]
           * assert items.find() == 42
           * 
      * * @param self an Object with an Iterator returning its values * @return the first Object found or null if none was found * @since 1.8.1 * @see Closure#IDENTITY */ public static Object find(Object self) { return find(self, Closure.IDENTITY); } /** * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns the defaultResult. * * @param self an Object with an iterator returning its values * @param defaultResult an Object that should be returned if all closure results are null * @param closure a closure that returns a non-null value when processing should stop * @return the first non-null result of the closure, otherwise the default value * @since 1.7.5 */ public static Object findResult(Object self, Object defaultResult, Closure closure) { Object result = findResult(self, closure); if (result == null) return defaultResult; return result; } /** * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns null. * * @param self an Object with an iterator returning its values * @param closure a closure that returns a non-null value when processing should stop * @return the first non-null result of the closure * @since 1.7.5 */ public static Object findResult(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object value = iter.next(); Object result = closure.call(value); if (result != null) { return result; } } return null; } /** * Finds the first value matching the closure condition. Example: *
      def list = [1,2,3]
           * assert 2 == list.find { it > 1 }
           * 
      * * @param self a Collection * @param closure a closure condition * @return the first Object found * @since 1.0 */ public static T find(Collection self, Closure closure) { for (T value : self) { if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { return value; } } return null; } /** * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth). *

      * Example: *

           * def items = [null, 0, 0.0, false, '', [], 42, 43]
           * assert items.find() == 42
           * 
      * * @param self a Collection * @return the first Object found or null if none was found * @since 1.8.1 * @see Closure#IDENTITY */ public static T find(Collection self) { return find(self, Closure.IDENTITY); } /** * Iterates through the collection calling the given closure for each item but stopping once the first non-null * result is found and returning that result. If all are null, the defaultResult is returned. *

      * Examples: *

           * def list = [1,2,3]
           * assert "Found 2" == list.findResult("default") { it > 1 ? "Found $it" : null }
           * assert "default" == list.findResult("default") { it > 3 ? "Found $it" : null }
           * 
      * * @param self a Collection * @param defaultResult an Object that should be returned if all closure results are null * @param closure a closure that returns a non-null value when processing should stop and a value should be returned * @return the first non-null result from calling the closure, or the defaultValue * @since 1.7.5 */ public static T findResult(Collection self, U defaultResult, Closure closure) { T result = findResult(self, closure); if (result == null) return defaultResult; return result; } /** * Iterates through the collection calling the given closure for each item but stopping once the first non-null * result is found and returning that result. If all results are null, null is returned. *

      * Example: *

           * def list = [1,2,3]
           * assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }
           * 
      * * @param self a Collection * @param closure a closure that returns a non-null value when processing should stop and a value should be returned * @return the first non-null result from calling the closure, or null * @since 1.7.5 */ public static T findResult(Collection self, Closure closure) { for (Object value : self) { T result = closure.call(value); if (result != null) { return result; } } return null; } /** * Iterates through the collection transforming items using the supplied closure * and collecting any non-null results. *

      * Example: *

           * def list = [1,2,3]
           * def result = list.findResults { it > 1 ? "Found $it" : null }
           * assert result == ["Found 2", "Found 3"]
           * 
      * * @param self a Collection * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded * @return the list of non-null transformed values * @since 1.8.1 */ public static Collection findResults(Collection self, Closure filteringTransform) { List result = new ArrayList(); for (Object value : self) { T transformed = filteringTransform.call(value); if (transformed != null) { result.add(transformed); } } return result; } /** * Iterates through the map transforming items using the supplied closure * and collecting any non-null results. * If the closure takes two parameters, the entry key and value are passed. * If the closure takes one parameter, the Map.Entry object is passed. *

      * Example: *

           * def map = [a:1, b:2, hi:2, cat:3, dog:2]
           * def result = map.findResults { k, v -> k.size() == v ? "Found $k:$v" : null }
           * assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
           * 
      * * @param self a Map * @param filteringTransform a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discarded * @return the list of non-null transformed values * @since 1.8.1 */ public static Collection findResults(Map self, Closure filteringTransform) { List result = new ArrayList(); for (Map.Entry entry : self.entrySet()) { T transformed = callClosureForMapEntry(filteringTransform, entry); if (transformed != null) { result.add(transformed); } } return result; } /** * Finds the first entry matching the closure condition. * If the closure takes two parameters, the entry key and value are passed. * If the closure takes one parameter, the Map.Entry object is passed. *
      assert [a:1, b:3].find { it.value == 3 }.key == "b"
      * * @param self a Map * @param closure a 1 or 2 arg Closure condition * @return the first Object found * @since 1.0 */ public static Map.Entry find(Map self, Closure closure) { for (Map.Entry entry : self.entrySet()) { if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) { return entry; } } return null; } /** * Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned. * If the closure takes two parameters, the entry key and value are passed. * If the closure takes one parameter, the Map.Entry object is passed. *
           * assert "Found b:3" == [a:1, b:3].findResult("default") { if (it.value == 3) return "Found ${it.key}:${it.value}" }
           * assert "default" == [a:1, b:3].findResult("default") { if (it.value == 9) return "Found ${it.key}:${it.value}" }
           * assert "Found a:1" == [a:1, b:3].findResult("default") { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
           * 
      * * @param self a Map * @param defaultResult an Object that should be returned if all closure results are null * @param closure a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned * @return the first non-null result collected by calling the closure, or the defaultResult if no such result was found * @since 1.7.5 */ public static T findResult(Map self, U defaultResult, Closure closure) { T result = findResult(self, closure); if (result == null) return defaultResult; return result; } /** * Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned. * If the closure takes two parameters, the entry key and value are passed. * If the closure takes one parameter, the Map.Entry object is passed. *
           * assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
           * assert null == [a:1, b:3].findResult { if (it.value == 9) return "Found ${it.key}:${it.value}" }
           * assert "Found a:1" == [a:1, b:3].findResult { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
           * 
      * * @param self a Map * @param closure a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned * @return the first non-null result collected by calling the closure, or null if no such result was found * @since 1.7.5 */ public static T findResult(Map self, Closure closure) { for (Map.Entry entry : self.entrySet()) { T result = callClosureForMapEntry(closure, entry); if (result != null) { return result; } } return null; } /** * Finds all values matching the closure condition. *
      assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }
      * * @param self a Collection * @param closure a closure condition * @return a Collection of matching values * @since 1.5.6 */ public static Collection findAll(Collection self, Closure closure) { Collection answer = createSimilarCollection(self); Iterator iter = self.iterator(); return findAll(closure, answer, iter); } /** * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth). *

      * Example: *

           * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
           * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
           * 
      * * @param self a Collection * @return a List of the values found * @since 1.8.1 * @see Closure#IDENTITY */ public static Collection findAll(Collection self) { return findAll(self, Closure.IDENTITY); } /** * Finds all items matching the closure condition. * * @param self an Object with an Iterator returning its values * @param closure a closure condition * @return a List of the values found * @since 1.6.0 */ public static Collection findAll(Object self, Closure closure) { List answer = new ArrayList(); Iterator iter = InvokerHelper.asIterator(self); return findAll(closure, answer, iter); } /** * Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth). *

      * Example: *

           * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
           * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
           * 
      * * @param self an Object with an Iterator returning its values * @return a List of the values found * @since 1.8.1 * @see Closure#IDENTITY */ public static Collection findAll(Object self) { return findAll(self, Closure.IDENTITY); } private static Collection findAll(Closure closure, Collection answer, Iterator iter) { while (iter.hasNext()) { T value = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { answer.add(value); } } return answer; } /** * Returns true if this collection contains all of the elements * in the specified array. * * @param self a Collection to be checked for containment * @param items array to be checked for containment in this collection * @return true if this collection contains all of the elements * in the specified array * @see Collection#containsAll(Collection) * @since 1.7.2 */ public static boolean containsAll(Collection self, Object[] items) { return self.containsAll(Arrays.asList(items)); } /** * Modifies this collection by removing its elements that are contained * within the specified object array. * * See also findAll and grep when wanting to produce a new list * containing items which don't match some criteria while leaving the original collection unchanged. * * @param self a Collection to be modified * @param items array containing elements to be removed from this collection * @return true if this collection changed as a result of the call * @see Collection#removeAll(Collection) * @since 1.7.2 */ public static boolean removeAll(Collection self, Object[] items) { return self.removeAll(Arrays.asList(items)); } /** * Modifies this collection so that it retains only its elements that are contained * in the specified array. In other words, removes from this collection all of * its elements that are not contained in the specified array. * * See also grep and findAll when wanting to produce a new list * containing items which match some specified items but leaving the original collection unchanged. * * @param self a Collection to be modified * @param items array containing elements to be retained from this collection * @return true if this collection changed as a result of the call * @see Collection#retainAll(Collection) * @since 1.7.2 */ public static boolean retainAll(Collection self, Object[] items) { return self.retainAll(Arrays.asList(items)); } /** * Modifies this collection so that it retains only its elements * that are matched according to the specified closure condition. In other words, * removes from this collection all of its elements that don't match. * * See also findAll and grep when wanting to produce a new list * containing items which match some criteria but leaving the original collection unchanged. * * @param self a Collection to be modified * @param condition a closure condition * @return true if this collection changed as a result of the call * @see Iterator#remove() * @since 1.7.2 */ public static boolean retainAll(Collection self, Closure condition) { Iterator iter = InvokerHelper.asIterator(self); boolean result = false; while (iter.hasNext()) { Object value = iter.next(); if (!DefaultTypeTransformation.castToBoolean(condition.call(value))) { iter.remove(); result = true; } } return result; } /** * Modifies this collection by removing the elements that are matched according * to the specified closure condition. * * See also findAll and grep when wanting to produce a new list * containing items which don't match some criteria while leaving the original collection unchanged. * * @param self a Collection to be modified * @param condition a closure condition * @return true if this collection changed as a result of the call * @see Iterator#remove() * @since 1.7.2 */ public static boolean removeAll(Collection self, Closure condition) { Iterator iter = InvokerHelper.asIterator(self); boolean result = false; while (iter.hasNext()) { Object value = iter.next(); if (DefaultTypeTransformation.castToBoolean(condition.call(value))) { iter.remove(); result = true; } } return result; } /** * Modifies the collection by adding all of the elements in the specified array to the collection. * The behavior of this operation is undefined if * the specified array is modified while the operation is in progress. * * See also plus or the '+' operator if wanting to produce a new collection * containing additional items but while leaving the original collection unchanged. * * @param self a Collection to be modified * @param items array containing elements to be added to this collection * @return true if this collection changed as a result of the call * @see Collection#addAll(Collection) * @since 1.7.2 */ public static boolean addAll(Collection self, T[] items) { return self.addAll(Arrays.asList(items)); } /** * Modifies this list by inserting all of the elements in the specified array into the * list at the specified position. Shifts the * element currently at that position (if any) and any subsequent * elements to the right (increases their indices). The new elements * will appear in this list in the order that they occur in the array. * The behavior of this operation is undefined if the specified array * is modified while the operation is in progress. * * See also plus for similar functionality with copy semantics, i.e. which produces a new * list after adding the additional items at the specified position but leaves the original list unchanged. * * @param self a list to be modified * @param items array containing elements to be added to this collection * @param index index at which to insert the first element from the * specified array * @return true if this collection changed as a result of the call * @see List#addAll(int, Collection) * @since 1.7.2 */ public static boolean addAll(List self, int index, T[] items) { return self.addAll(index, Arrays.asList(items)); } /** * Splits all items into two lists based on the closure condition. * The first list contains all items matching the closure expression. * The second list all those that don't. * * @param self an Object with an Iterator returning its values * @param closure a closure condition * @return a List whose first item is the accepted values and whose second item is the rejected values * @since 1.6.0 */ public static Collection split(Object self, Closure closure) { List accept = new ArrayList(); List reject = new ArrayList(); return split(closure, accept, reject, InvokerHelper.asIterator(self)); } /** * Splits all items into two collections based on the closure condition. * The first list contains all items which match the closure expression. * The second list all those that don't. *

      * Example usage: *

      assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }
      * * @param self a Collection of values * @param closure a closure condition * @return a List whose first item is the accepted values and whose second item is the rejected values * @since 1.6.0 */ public static Collection> split(Collection self, Closure closure) { Collection accept = createSimilarCollection(self); Collection reject = createSimilarCollection(self); Iterator iter = self.iterator(); return split(closure, accept, reject, iter); } private static Collection> split(Closure closure, Collection accept, Collection reject, Iterator iter) { List> answer = new ArrayList>(); while (iter.hasNext()) { T value = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { accept.add(value); } else { reject.add(value); } } answer.add(accept); answer.add(reject); return answer; } /** * Adds GroovyCollections#combinations(Collection) as a method on collections. *

      * Example usage: *

      assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
      * * @param self a Collection of lists * @return a List of the combinations found * @see groovy.util.GroovyCollections#combinations(java.util.Collection) * @since 1.5.0 */ public static List combinations(Collection self) { return GroovyCollections.combinations(self); } /** * Finds all non-null subsequences of a list. *

      * Example usage: *

      def result = [1, 2, 3].subsequences()
           * assert result == [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] as Set
      * * @param self the List of items * @return the subsequences from the list * @since 1.7.0 */ public static Set> subsequences(List self) { return GroovyCollections.subsequences(self); } /** * Finds all permutations of a collection. *

      * Example usage: *

      def result = [1, 2, 3].permutations()
           * assert result == [[3, 2, 1], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2, 1, 3], [1, 2, 3]] as Set
      * * @param self the Collection of items * @return the permutations from the list * @since 1.7.0 */ public static Set> permutations(List self) { Set> ans = new HashSet>(); PermutationGenerator generator = new PermutationGenerator(self); while (generator.hasNext()) { ans.add(generator.next()); } return ans; } /** * Iterates over all permutations of a collection, running a closure for each iteration. *

      * Example usage: *

      def permutations = []
           * [1, 2, 3].eachPermutation{ permutations << it }
           * assert permutations == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
      * * @param self the Collection of items * @param closure the closure to call for each permutation * @return the permutations from the list * @since 1.7.0 */ public static Iterator> eachPermutation(Collection self, Closure closure) { Iterator> generator = new PermutationGenerator(self); while (generator.hasNext()) { closure.call(generator.next()); } return generator; } /** * Adds GroovyCollections#transpose(List) as a method on lists.
      * A TransposeFunction takes a collection of columns and returns a collection of * rows. The first row consists of the first element from each column. Successive * rows are constructed similarly. *

      * Example usage: *

      def result = [['a', 'b'], [1, 2]].transpose()
           * assert result == [['a', 1], ['b', 2]]
      *
      def result = [['a', 'b'], [1, 2], [3, 4]].transpose()
           * assert result == [['a', 1, 3], ['b', 2, 4]]
      * * @param self a List of lists * @return a List of the transposed lists * @see groovy.util.GroovyCollections#transpose(java.util.List) * @since 1.5.0 */ public static List transpose(List self) { return GroovyCollections.transpose(self); } /** * Finds all entries matching the closure condition. If the * closure takes one parameter then it will be passed the Map.Entry. * Otherwise if the closure should take two parameters, which will be * the key and the value. *

      * If the self map is one of TreeMap, LinkedHashMap, Hashtable * or Properties, the returned Map will preserve that type, otherwise a HashMap will * be returned. *

      * Example usage: *

      def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
           * assert result.every { it instanceof Map.Entry }
           * assert result*.key == ["b", "c"]
           * assert result*.value == [2, 4]
      * * @param self a Map * @param closure a 1 or 2 arg Closure condition applying on the entries * @return a new subMap * @since 1.0 */ public static Map findAll(Map self, Closure closure) { Map answer = createSimilarMap(self); for (Map.Entry entry : self.entrySet()) { if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) { answer.put(entry.getKey(), entry.getValue()); } } return answer; } /** * Sorts all collection members into groups determined by the * supplied mapping closure. The closure should return the key that this * item should be grouped by. The returned LinkedHashMap will have an entry for each * distinct key returned from the closure, with each value being a list of * items for that group. *

      * Example usage: *

      assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }
      * * @param self a collection to group * @param closure a closure mapping entries on keys * @return a new Map grouped by keys * @since 1.0 */ public static Map> groupBy(Collection self, Closure closure) { Map> answer = new LinkedHashMap>(); for (T element : self) { K value = closure.call(element); groupAnswer(answer, element, value); } return answer; } /** * Sorts all collection members into (sub)groups determined by the supplied * mapping closures. Each closure should return the key that this item * should be grouped by. The returned LinkedHashMap will have an entry for each * distinct 'key path' returned from the closures, with each value being a list * of items for that 'group path'.

      * * Example usage: *

      def result = [1,2,3,4,5,6].groupBy({ it % 2 }, { it < 4 })
           * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]
      * * Another example: *
      def sql = groovy.sql.Sql.newInstance(/* ... */)
           * def data = sql.rows("SELECT * FROM a_table").groupBy({ it.column1 }, { it.column2 }, { it.column3 })
           * if (data.val1.val2.val3) {
           *     // there exists a record where:
           *     //   a_table.column1 == val1
           *     //   a_table.column2 == val2, and
           *     //   a_table.column3 == val3
           * } else {
           *     // there is no such record
           * }
      * If an empty array of closures is supplied the IDENTITY Closure will be used. * * @param self a collection to group * @param closures an array of closures, each mapping entries on keys * @return a new Map grouped by keys on each criterion * @since 1.8.1 * @see Closure#IDENTITY */ public static Map groupBy(Collection self, Object... closures) { final Closure head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0]; @SuppressWarnings("unchecked") Map first = groupBy(self, head); if (closures.length < 2) return first; final Object[] tail = new Object[closures.length - 1]; System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6 // inject([:]) { a,e -> a << [(e.key): e.value.groupBy(tail)] } Map acc = new LinkedHashMap(); for (Map.Entry item : first.entrySet()) { acc.put(item.getKey(), groupBy(item.getValue(), tail)); } return acc; } /** * Sorts all collection members into (sub)groups determined by the supplied * mapping closures. Each closure should return the key that this item * should be grouped by. The returned LinkedHashMap will have an entry for each * distinct 'key path' returned from the closures, with each value being a list * of items for that 'group path'.

      * * Example usage: *

      def result = [1,2,3,4,5,6].groupBy([{ it % 2 }, { it < 4 }])
           * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]
      * * Another example: *
      def sql = groovy.sql.Sql.newInstance(/* ... */)
           * def data = sql.rows("SELECT * FROM a_table").groupBy([{ it.column1 }, { it.column2 }, { it.column3 }])
           * if (data.val1.val2.val3) {
           *     // there exists a record where:
           *     //   a_table.column1 == val1
           *     //   a_table.column2 == val2, and
           *     //   a_table.column3 == val3
           * } else {
           *     // there is no such record
           * }
      * If an empty list of closures is supplied the IDENTITY Closure will be used. * * @param self a collection to group * @param closures a list of closures, each mapping entries on keys * @return a new Map grouped by keys on each criterion * @since 1.8.1 * @see Closure#IDENTITY */ public static Map groupBy(Collection self, List closures) { return groupBy(self, closures.toArray()); } /** * Sorts all collection members into groups determined by the supplied mapping * closure and counts the group size. The closure should return the key that each * item should be grouped by. The returned Map will have an entry for each * distinct key returned from the closure, with each value being the frequency of * items occurring for that group. *

      * Example usage: *

      assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }
      * * @param self a collection to group and count * @param closure a closure mapping items to the frequency keys * @return a new Map grouped by keys with frequency counts * @since 1.8.0 */ public static Map countBy(Collection self, Closure closure) { return countBy(self.iterator(), closure); } /** * Sorts all array members into groups determined by the supplied mapping * closure and counts the group size. The closure should return the key that each * item should be grouped by. The returned Map will have an entry for each * distinct key returned from the closure, with each value being the frequency of * items occurring for that group. *

      * Example usage: *

      assert ([1,2,2,2,3] as Object[]).countBy{ it % 2 } == [1:2, 0:3]
      * * @param self an object array to group and count * @param closure a closure mapping items to the frequency keys * @return a new Map grouped by keys with frequency counts * @see #countBy(Collection, Closure) * @since 1.8.0 */ public static Map countBy(Object[] self, Closure closure) { return countBy(Arrays.asList(self), closure); } /** * Sorts all iterator items into groups determined by the supplied mapping * closure and counts the group size. The closure should return the key that each * item should be grouped by. The returned Map will have an entry for each * distinct key returned from the closure, with each value being the frequency of * items occurring for that group. *

      * Example usage: *

      assert [1,2,2,2,3].toSet().iterator().countBy{ it % 2 } == [1:2, 0:1]
      * * @param self an iterator to group and count * @param closure a closure mapping items to the frequency keys * @return a new Map grouped by keys with frequency counts * @see #countBy(Collection, Closure) * @since 1.8.0 */ public static Map countBy(Iterator self, Closure closure) { Map answer = new LinkedHashMap(); while (self.hasNext()) { K value = closure.call(self.next()); countAnswer(answer, value); } return answer; } /** * Groups all map entries into groups determined by the * supplied mapping closure. The closure will be passed a Map.Entry or * key and value (depending on the number of parameters the closure accepts) * and should return the key that each item should be grouped under. The * resulting map will have an entry for each 'group' key returned by the * closure, with values being the list of map entries that belong to each * group. (If instead of a list of map entries, you want an actual map * use {code}groupBy{code}.) *
      def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupEntriesBy { it.value % 2 }
           * assert result[0]*.key == ["b", "d", "f"]
           * assert result[1]*.value == [1, 3, 5]
      * * @param self a map to group * @param closure a 1 or 2 arg Closure mapping entries on keys * @return a new Map grouped by keys * @since 1.5.2 */ public static Map>> groupEntriesBy(Map self, Closure closure) { final Map>> answer = new LinkedHashMap>>(); for (Map.Entry entry : self.entrySet()) { G value = callClosureForMapEntry(closure, entry); groupAnswer(answer, entry, value); } return answer; } /** * Groups the members of a map into sub maps determined by the * supplied mapping closure. The closure will be passed a Map.Entry or * key and value (depending on the number of parameters the closure accepts) * and should return the key that each item should be grouped under. The * resulting map will have an entry for each 'group' key returned by the * closure, with values being the map members from the original map that * belong to each group. (If instead of a map, you want a list of map entries * use {code}groupEntriesBy{code}.) *

      * If the self map is one of TreeMap, Hashtable or Properties, * the returned Map will preserve that type, otherwise a LinkedHashMap will * be returned. *

      def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy { it.value % 2 }
           * assert result == [0:[b:2, d:4, f:6], 1:[a:1, c:3, e:5]]
      * * @param self a map to group * @param closure a closure mapping entries on keys * @return a new Map grouped by keys * @since 1.0 */ public static Map> groupBy(Map self, Closure closure) { final Map>> initial = groupEntriesBy(self, closure); final Map> answer = new LinkedHashMap>(); for (Map.Entry>> outer : initial.entrySet()) { G key = outer.getKey(); List> entries = outer.getValue(); Map target = createSimilarMap(self); putAll(target, entries); answer.put(key, target); } return answer; } /** * Groups the members of a map into sub maps determined by the supplied * mapping closures. Each closure will be passed a Map.Entry or key and * value (depending on the number of parameters the closure accepts) and * should return the key that each item should be grouped under. The * resulting map will have an entry for each 'group path' returned by all * closures, with values being the map members from the original map that * belong to each such 'group path'.

      * * If the self map is one of TreeMap, Hashtable, or Properties, * the returned Map will preserve that type, otherwise a LinkedHashMap will * be returned. * *

      def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy({ it.value % 2 }, { it.key.next() })
           * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]
      * If an empty array of closures is supplied the IDENTITY Closure will be used. * * @param self a map to group * @param closures an array of closures that map entries on keys * @return a new map grouped by keys on each criterion * @since 1.8.1 * @see Closure#IDENTITY */ public static Map groupBy(Map self, Object... closures) { @SuppressWarnings("unchecked") final Closure head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0]; @SuppressWarnings("unchecked") Map first = groupBy(self, head); if (closures.length < 2) return first; final Object[] tail = new Object[closures.length - 1]; System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6 Map acc = new LinkedHashMap(); for (Map.Entry item: first.entrySet()) { acc.put(item.getKey(), groupBy(item.getValue(), tail)); } return acc; } /** * Groups the members of a map into sub maps determined by the supplied * mapping closures. Each closure will be passed a Map.Entry or key and * value (depending on the number of parameters the closure accepts) and * should return the key that each item should be grouped under. The * resulting map will have an entry for each 'group path' returned by all * closures, with values being the map members from the original map that * belong to each such 'group path'.

      * * If the self map is one of TreeMap, Hashtable, or Properties, * the returned Map will preserve that type, otherwise a LinkedHashMap will * be returned. * *

      def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }])
           * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]
      * If an empty list of closures is supplied the IDENTITY Closure will be used. * * @param self a map to group * @param closures a list of closures that map entries on keys * @return a new map grouped by keys on each criterion * @since 1.8.1 * @see Closure#IDENTITY */ public static Map groupBy(Map self, List closures) { return groupBy(self, closures.toArray()); } /** * Groups the members of a map into groups determined by the * supplied mapping closure and counts the frequency of the created groups. * The closure will be passed a Map.Entry or * key and value (depending on the number of parameters the closure accepts) * and should return the key that each item should be grouped under. The * resulting map will have an entry for each 'group' key returned by the * closure, with values being the frequency counts for that 'group'. *

      *

      def result = [a:1,b:2,c:3,d:4,e:5].countBy { it.value % 2 }
           * assert result == [0:2, 1:3]
      * * @param self a map to group and count * @param closure a closure mapping entries to frequency count keys * @return a new Map grouped by keys with frequency counts * @since 1.8.0 */ public static Map countBy(Map self, Closure closure) { Map answer = new LinkedHashMap(); for (Object entry : self.entrySet()) { countAnswer(answer, callClosureForMapEntry(closure, (Map.Entry) entry)); } return answer; } /** * Groups the current element according to the value * * @param answer the map containing the results * @param element the element to be placed * @param value the value according to which the element will be placed * @since 1.5.0 */ protected static void groupAnswer(final Map> answer, T element, K value) { if (answer.containsKey(value)) { answer.get(value).add(element); } else { List groupedElements = new ArrayList(); groupedElements.add(element); answer.put(value, groupedElements); } } private static void countAnswer(final Map answer, T mappedKey) { if (!answer.containsKey(mappedKey)) { answer.put(mappedKey, 0); } int current = answer.get(mappedKey); answer.put(mappedKey, current + 1); } // internal helper method protected static T callClosureForMapEntry(Closure closure, Map.Entry entry) { if (closure.getMaximumNumberOfParameters() == 2) { return closure.call(new Object[]{entry.getKey(), entry.getValue()}); } return closure.call(entry); } // internal helper method protected static T callClosureForLine(Closure closure, String line, int counter) { if (closure.getMaximumNumberOfParameters() == 2) { return closure.call(new Object[]{line, counter}); } return closure.call(line); } // internal helper method protected static T callClosureForMapEntryAndCounter(Closure closure, Map.Entry entry, int counter) { if (closure.getMaximumNumberOfParameters() == 3) { return closure.call(new Object[]{entry.getKey(), entry.getValue(), counter}); } if (closure.getMaximumNumberOfParameters() == 2) { return closure.call(new Object[]{entry, counter}); } return closure.call(entry); } /** * Iterates through the given Collection, passing in the initial value to * the 2-arg closure along with the first item. The result is passed back (injected) into * the closure along with the second item. The new result is injected back into * the closure along with the third item and so on until the entire collection * has been used. Also known as foldLeft or reduce in functional parlance. * * Examples: *
           * assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val }
           *
           * assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val }
           *
           * assert 'The quick brown fox' ==
           *     ['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val }
           *
           * assert 'bat' ==
           *     ['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min }
           *
           * def max = { a, b -> [a, b].max() }
           * def animals = ['bat', 'rat', 'cat']
           * assert 'rat' == animals.inject('aaa', max)
           * 
      * Visual representation of the last example above: *
           *    initVal  animals[0]
           *       v        v
           * max('aaa',   'bat')  =>  'bat'  animals[1]
           *                            v       v
           *                      max('bat',  'rat')  =>  'rat'  animals[2]
           *                                                v       v
           *                                          max('rat',  'cat')  =>  'rat'
           * 
      * * @param self a Collection * @param initialValue some initial value * @param closure a closure * @return the result of the last closure call * @since 1.0 */ public static T inject(Collection self, U initialValue, Closure closure) { return (T) inject(self.iterator(), initialValue, closure); } /** * Iterates through the given Map, passing in the initial value to * the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value). * The result is passed back (injected) into * the closure along with the second item. The new result is injected back into * the closure along with the third item and so on until the entire collection * has been used. Also known as foldLeft or reduce in functional parlance. * * Examples: *
           * def map = [a:1, b:2, c:3]
           * assert map.inject([]) { list, k, v ->
           *   list + [k] * v
           * } == ['a', 'b', 'b', 'c', 'c', 'c']
           * 
      * * @param self a Map * @param initialValue some initial value * @param closure a 2 or 3 arg Closure * @return the result of the last closure call * @since 1.8.1 */ public static T inject(Map self, U initialValue, Closure closure) { T value = initialValue; for (Map.Entry entry : self.entrySet()) { if (closure.getMaximumNumberOfParameters() == 3) { value = closure.call(value, entry.getKey(), entry.getValue()); } else { value = closure.call(value, entry); } } return value; } /** * Iterates through the given Iterator, passing in the initial value to * the closure along with the first item. The result is passed back (injected) into * the closure along with the second item. The new result is injected back into * the closure along with the third item and so on until the Iterator has been * expired of values. Also known as foldLeft in functional parlance. * * @param self an Iterator * @param initialValue some initial value * @param closure a closure * @return the result of the last closure call * @see #inject(Collection, Object, Closure) * @since 1.5.0 */ public static T inject(Iterator self, U initialValue, Closure closure) { T value = initialValue; Object[] params = new Object[2]; while (self.hasNext()) { Object item = self.next(); params[0] = value; params[1] = item; value = closure.call(params); } return value; } /** * Iterates through the given Object, passing in the initial value to * the closure along with the first item. The result is passed back (injected) into * the closure along with the second item. The new result is injected back into * the closure along with the third item and so on until further iteration of * the object is not possible. Also known as foldLeft in functional parlance. * * @param self an Object * @param initialValue some initial value * @param closure a closure * @return the result of the last closure call * @see #inject(Collection, Object, Closure) * @since 1.5.0 */ public static T inject(Object self, U initialValue, Closure closure) { Iterator iter = InvokerHelper.asIterator(self); return (T) inject(iter, initialValue, closure); } /** * Iterates through the given array, passing in the initial value to * the closure along with the first item. The result is passed back (injected) into * the closure along with the second item. The new result is injected back into * the closure along with the third item and so on until all elements of the array * have been used. Also known as foldLeft in functional parlance. * * @param self an Object[] * @param initialValue some initial value * @param closure a closure * @return the result of the last closure call * @see #inject(Collection, Object, Closure) * @since 1.5.0 */ public static T inject(Object[] self, U initialValue, Closure closure) { Object[] params = new Object[2]; T value = initialValue; for (Object next : self) { params[0] = value; params[1] = next; value = closure.call(params); } return value; } /** * Sums the items in a collection. This is equivalent to invoking the * "plus" method on all items in the collection. *
      assert 1+2+3+4 == [1,2,3,4].sum()
      * * @param self Collection of values to add together * @return The sum of all of the items * @since 1.0 */ public static Object sum(Collection self) { return sum(self, null, true); } /** * Sums the items in an array. This is equivalent to invoking the * "plus" method on all items in the array. * * @param self The array of values to add together * @return The sum of all of the items * @see #sum(java.util.Collection) * @since 1.7.1 */ public static Object sum(Object[] self) { return sum(toList(self), null, true); } /** * Sums the items from an Iterator. This is equivalent to invoking the * "plus" method on all items from the Iterator. The iterator will become * exhausted of elements after determining the sum value. * * @param self an Iterator for the values to add together * @return The sum of all of the items * @since 1.5.5 */ public static Object sum(Iterator self) { return sum(toList(self), null, true); } /** * Sums the items in a collection, adding the result to some initial value. *
      assert 5+1+2+3+4 == [1,2,3,4].sum(5)
      * * @param self a collection of values to sum * @param initialValue the items in the collection will be summed to this initial value * @return The sum of all of the items. * @since 1.5.0 */ public static Object sum(Collection self, Object initialValue) { return sum(self, initialValue, false); } /** * Sums the items in an array, adding the result to some initial value. * * @param self an array of values to sum * @param initialValue the items in the array will be summed to this initial value * @return The sum of all of the items. * @since 1.7.1 */ public static Object sum(Object[] self, Object initialValue) { return sum(toList(self), initialValue, false); } /** * Sums the items from an Iterator, adding the result to some initial value. This is * equivalent to invoking the "plus" method on all items from the Iterator. The iterator * will become exhausted of elements after determining the sum value. * * @param self an Iterator for the values to add together * @param initialValue the items in the collection will be summed to this initial value * @return The sum of all of the items * @since 1.5.5 */ public static Object sum(Iterator self, Object initialValue) { return sum(toList(self), initialValue, false); } private static Object sum(Collection self, Object initialValue, boolean first) { Object result = initialValue; Object[] param = new Object[1]; for (Object next : self) { param[0] = next; if (first) { result = param[0]; first = false; continue; } MetaClass metaClass = InvokerHelper.getMetaClass(result); result = metaClass.invokeMethod(result, "plus", param); } return result; } /** * Sums the result of apply a closure to each item of a collection. * coll.sum(closure) is equivalent to: * coll.collect(closure).sum(). *
      assert 4+6+10+12 == [2,3,5,6].sum() { it * 2 }
      * * @param self a Collection * @param closure a single parameter closure that returns a numeric value. * @return The sum of the values returned by applying the closure to each * item of the collection. * @since 1.0 */ public static Object sum(Collection self, Closure closure) { return sum(self, null, closure, true); } /** * Sums the result of apply a closure to each item of an array. * array.sum(closure) is equivalent to: * array.collect(closure).sum(). * * @param self An array * @param closure a single parameter closure that returns a numeric value. * @return The sum of the values returned by applying the closure to each * item of the array. * @since 1.7.1 */ public static Object sum(Object[] self, Closure closure) { return sum(toList(self), null, closure, true); } /** * Sums the result of apply a closure to each item returned from an iterator. * iter.sum(closure) is equivalent to: * iter.collect(closure).sum(). The iterator will become * exhausted of elements after determining the sum value. * * @param self An Iterator * @param closure a single parameter closure that returns a numeric value. * @return The sum of the values returned by applying the closure to each * item from the Iterator. * @since 1.7.1 */ public static Object sum(Iterator self, Closure closure) { return sum(toList(self), null, closure, true); } /** * Sums the result of applying a closure to each item of a collection to some initial value. * coll.sum(initVal, closure) is equivalent to: * coll.collect(closure).sum(initVal). *
      assert 50+4+6+10+12 == [2,3,5,6].sum(50) { it * 2 }
      * * @param self a Collection * @param closure a single parameter closure that returns a numeric value. * @param initialValue the closure results will be summed to this initial value * @return The sum of the values returned by applying the closure to each * item of the collection. * @since 1.5.0 */ public static Object sum(Collection self, Object initialValue, Closure closure) { return sum(self, initialValue, closure, false); } /** * Sums the result of applying a closure to each item of an array to some initial value. * array.sum(initVal, closure) is equivalent to: * array.collect(closure).sum(initVal). * * @param self an array * @param closure a single parameter closure that returns a numeric value. * @param initialValue the closure results will be summed to this initial value * @return The sum of the values returned by applying the closure to each * item of the array. * @since 1.7.1 */ public static Object sum(Object[] self, Object initialValue, Closure closure) { return sum(toList(self), initialValue, closure, false); } /** * Sums the result of applying a closure to each item of an Iterator to some initial value. * iter.sum(initVal, closure) is equivalent to: * iter.collect(closure).sum(initVal). The iterator will become * exhausted of elements after determining the sum value. * * @param self an Iterator * @param closure a single parameter closure that returns a numeric value. * @param initialValue the closure results will be summed to this initial value * @return The sum of the values returned by applying the closure to each * item from the Iterator. * @since 1.7.1 */ public static Object sum(Iterator self, Object initialValue, Closure closure) { return sum(toList(self), initialValue, closure, false); } private static Object sum(Collection self, Object initialValue, Closure closure, boolean first) { Object result = initialValue; Object[] closureParam = new Object[1]; Object[] plusParam = new Object[1]; for (Object next : self) { closureParam[0] = next; plusParam[0] = closure.call(closureParam); if (first) { result = plusParam[0]; first = false; continue; } MetaClass metaClass = InvokerHelper.getMetaClass(result); result = metaClass.invokeMethod(result, "plus", plusParam); } return result; } /** * Concatenates the toString() representation of each * item from the iterator, with the given String as a separator between * each item. The iterator will become exhausted of elements after * determining the resulting conjoined value. * * @param self an Iterator of items * @param separator a String separator * @return the joined String * @since 1.5.5 */ public static String join(Iterator self, String separator) { return join(toList(self), separator); } /** * Concatenates the toString() representation of each * item in this collection, with the given String as a separator between * each item. *
      assert "1, 2, 3" == [1,2,3].join(", ")
      * * @param self a Collection of objects * @param separator a String separator * @return the joined String * @since 1.0 */ public static String join(Collection self, String separator) { StringBuilder buffer = new StringBuilder(); boolean first = true; if (separator == null) separator = ""; for (Object value : self) { if (first) { first = false; } else { buffer.append(separator); } buffer.append(InvokerHelper.toString(value)); } return buffer.toString(); } /** * Concatenates the toString() representation of each * items in this array, with the given String as a separator between each * item. * * @param self an array of Object * @param separator a String separator * @return the joined String * @since 1.0 */ public static String join(Object[] self, String separator) { StringBuilder buffer = new StringBuilder(); boolean first = true; if (separator == null) separator = ""; for (Object next : self) { String value = InvokerHelper.toString(next); if (first) { first = false; } else { buffer.append(separator); } buffer.append(value); } return buffer.toString(); } /** * Adds min() method to Collection objects. *
      assert 2 == [4,2,5].min()
      * * @param self a Collection * @return the minimum value * @see groovy.util.GroovyCollections#min(java.util.Collection) * @since 1.0 */ public static T min(Collection self) { return GroovyCollections.min(self); } /** * Adds min() method to Iterator objects. The iterator will become * exhausted of elements after determining the minimum value. * * @param self an Iterator * @return the minimum value * @see #min(java.util.Collection) * @since 1.5.5 */ public static T min(Iterator self) { return min(toList(self)); } /** * Adds min() method to Object arrays. * * @param self an Object array * @return the minimum value * @see #min(java.util.Collection) * @since 1.5.5 */ public static T min(T[] self) { return min(toList(self)); } /** * Selects the minimum value found in the collection using the given comparator. *
      assert "hi" == ["hello","hi","hey"].min( { a, b -> a.length() <=> b.length() } as Comparator )
      * * @param self a Collection * @param comparator a Comparator * @return the minimum value * @since 1.0 */ public static T min(Collection self, Comparator comparator) { T answer = null; for (T value : self) { if (answer == null || comparator.compare(value, answer) < 0) { answer = value; } } return answer; } /** * Selects the minimum value found from the Iterator using the given comparator. * * @param self an Iterator * @param comparator a Comparator * @return the minimum value * @see #min(java.util.Collection, java.util.Comparator) * @since 1.5.5 */ public static T min(Iterator self, Comparator comparator) { return min(toList(self), comparator); } /** * Selects the minimum value found from the Object array using the given comparator. * * @param self an Object array * @param comparator a Comparator * @return the minimum value * @see #min(java.util.Collection, java.util.Comparator) * @since 1.5.5 */ public static T min(T[] self, Comparator comparator) { return min(toList(self), comparator); } /** * Selects an item in the collection having the minimum * value as determined by the supplied closure. * If more than one item has the minimum value, * an arbitrary choice is made between the items having the minimum value. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. *
           * assert "hi" == ["hello","hi","hey"].min { it.length() }
           * 
      *
           * def lastDigit = { a, b -> a % 10 <=> b % 10 }
           * assert [19, 55, 91].min(lastDigit) == 91
           * 
      *
           * def pets = ['dog', 'cat', 'anaconda']
           * def shortestName = pets.min{ it.size() } // one of 'dog' or 'cat'
           * assert shortestName.size() == 3
           * 
      * * @param self a Collection * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return the minimum value * @since 1.0 */ public static T min(Collection self, Closure closure) { int params = closure.getMaximumNumberOfParameters(); if (params != 1) { return min(self, new ClosureComparator(closure)); } T answer = null; Object answer_value = null; for (T item : self) { Object value = closure.call(item); if (answer == null || ScriptBytecodeAdapter.compareLessThan(value, answer_value)) { answer = item; answer_value = value; } } return answer; } /** * Selects an entry in the map having the minimum * calculated value as determined by the supplied closure. * If more than one entry has the minimum value, * an arbitrary choice is made between the entries having the minimum value. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. *
           * def zoo = [monkeys:6, lions:5, tigers:7]
           * def leastCommonEntry = zoo.min{ it.value }
           * assert leastCommonEntry.value == 5
           * def mostCommonEntry = zoo.min{ a, b -> b.value <=> a.value } // double negative!
           * assert mostCommonEntry.value == 7
           * 
      * Edge case for multiple min values: *
           * def zoo = [monkeys:6, lions:5, tigers:7]
           * def lastCharOfName = { e -> e.key[-1] }
           * def ans = zoo.min(lastCharOfName) // some random entry
           * assert lastCharOfName(ans) == 's'
           * 
      * * @param self a Map * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return the Map.Entry having the minimum value as determined by the closure * @since 1.7.6 */ public static Map.Entry min(Map self, Closure closure) { return min(self.entrySet(), closure); } /** * Selects an entry in the map having the maximum * calculated value as determined by the supplied closure. * If more than one entry has the maximum value, * an arbitrary choice is made between the entries having the maximum value. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. An example: *
           * def zoo = [monkeys:6, lions:5, tigers:7]
           * def mostCommonEntry = zoo.max{ it.value }
           * assert mostCommonEntry.value == 7
           * def leastCommonEntry = zoo.max{ a, b -> b.value <=> a.value } // double negative!
           * assert leastCommonEntry.value == 5
           * 
      * Edge case for multiple max values: *
           * def zoo = [monkeys:6, lions:5, tigers:7]
           * def lengthOfNamePlusNumber = { e -> e.key.size() + e.value }
           * def ans = zoo.max(lengthOfNamePlusNumber) // one of [monkeys:6, tigers:7]
           * assert lengthOfNamePlusNumber(ans) == 13
           * 
      * * @param self a Map * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return the Map.Entry having the maximum value as determined by the closure * @since 1.7.6 */ public static Map.Entry max(Map self, Closure closure) { return max(self.entrySet(), closure); } /** * Selects the minimum value found from the Iterator * using the closure to determine the correct ordering. * The iterator will become * exhausted of elements after this operation. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. * * @param self an Iterator * @param closure a Closure used to determine the correct ordering * @return the minimum value * @see #min(java.util.Collection, groovy.lang.Closure) * @since 1.5.5 */ public static T min(Iterator self, Closure closure) { return min(toList(self), closure); } /** * Selects the minimum value found from the Object array * using the closure to determine the correct ordering. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. * * @param self an Object array * @param closure a Closure used to determine the correct ordering * @return the minimum value * @see #min(java.util.Collection, groovy.lang.Closure) * @since 1.5.5 */ public static T min(T[] self, Closure closure) { return min(toList(self), closure); } /** * Adds max() method to Collection objects. *
      assert 5 == [2,3,1,5,4].max()
      * * @param self a Collection * @return the maximum value * @see groovy.util.GroovyCollections#max(java.util.Collection) * @since 1.0 */ public static T max(Collection self) { return GroovyCollections.max(self); } /** * Adds max() method to Iterator objects. The iterator will become * exhausted of elements after determining the maximum value. * * @param self an Iterator * @return the maximum value * @see groovy.util.GroovyCollections#max(java.util.Collection) * @since 1.5.5 */ public static T max(Iterator self) { return max(toList(self)); } /** * Adds max() method to Object arrays. * * @param self an Object array * @return the maximum value * @see #max(java.util.Collection) * @since 1.5.5 */ public static T max(T[] self) { return max(toList(self)); } /** * Selects an item in the collection having the maximum * value as determined by the supplied closure. * If more than one item has the maximum value, * an arbitrary choice is made between the items having the maximum value. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. *
      assert "hello" == ["hello","hi","hey"].max { it.length() }
      *
      assert "hello" == ["hello","hi","hey"].max { a, b -> a.length() <=> b.length() }
      *
           * def pets = ['dog', 'elephant', 'anaconda']
           * def longestName = pets.max{ it.size() } // one of 'elephant' or 'anaconda'
           * assert longestName.size() == 8
           * 
      * * @param self a Collection * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return the maximum value * @since 1.0 */ public static T max(Collection self, Closure closure) { int params = closure.getMaximumNumberOfParameters(); if (params != 1) { return max(self, new ClosureComparator(closure)); } T answer = null; Object answerValue = null; for (T item : self) { Object value = closure.call(item); if (answer == null || ScriptBytecodeAdapter.compareLessThan(answerValue, value)) { answer = item; answerValue = value; } } return answer; } /** * Selects the maximum value found from the Iterator * using the closure to determine the correct ordering. * The iterator will become exhausted of elements after this operation. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. * * @param self an Iterator * @param closure a Closure used to determine the correct ordering * @return the maximum value * @see #max(java.util.Collection, groovy.lang.Closure) * @since 1.5.5 */ public static T max(Iterator self, Closure closure) { return max(toList(self), closure); } /** * Selects the maximum value found from the Object array * using the closure to determine the correct ordering. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. * * @param self an Object array * @param closure a Closure used to determine the correct ordering * @return the maximum value * @see #max(java.util.Collection, groovy.lang.Closure) * @since 1.5.5 */ public static T max(T[] self, Closure closure) { return max(toList(self), closure); } /** * Selects the maximum value found in the collection using the given comparator. *
      assert "hello" == ["hello","hi","hey"].max( { a, b -> a.length() <=> b.length() } as Comparator )
      * * @param self a Collection * @param comparator a Comparator * @return the maximum value * @since 1.0 */ public static T max(Collection self, Comparator comparator) { T answer = null; for (T value : self) { if (answer == null || comparator.compare(value, answer) > 0) { answer = value; } } return answer; } /** * Selects the maximum value found from the Iterator using the given comparator. * * @param self an Iterator * @param comparator a Comparator * @return the maximum value * @since 1.5.5 */ public static T max(Iterator self, Comparator comparator) { return max(toList(self), comparator); } /** * Selects the maximum value found from the Object array using the given comparator. * * @param self an Object array * @param comparator a Comparator * @return the maximum value * @since 1.5.5 */ public static T max(T[] self, Comparator comparator) { return max(toList(self), comparator); } /** * Provide the standard Groovy size() method for Iterator. * The iterator will become exhausted of elements after determining the size value. * * @param self an Iterator * @return the length of the Iterator * @since 1.5.5 */ public static int size(Iterator self) { int count = 0; while (self.hasNext()) { self.next(); count++; } return count; } /** * Provide the standard Groovy size() method for String. * * @param text a String * @return the length of the String * @since 1.0 */ public static int size(String text) { return text.length(); } /** * Provide the standard Groovy size() method for CharSequence. * * @param text a CharSequence * @return the length of the CharSequence * @since 1.8.2 */ public static int size(CharSequence text) { return text.length(); } /** * Provide the standard Groovy size() method for StringBuffer. * * @param buffer a StringBuffer * @return the length of the StringBuffer * @since 1.0 */ public static int size(StringBuffer buffer) { return buffer.length(); } /** * Provide the standard Groovy size() method for File. * * @param self a file object * @return the file's size (length) * @since 1.5.0 */ public static long size(File self) { return self.length(); } /** * Provide the standard Groovy size() method for Matcher. * * @param self a matcher object * @return the matcher's size (count) * @since 1.5.0 */ public static long size(Matcher self) { return getCount(self); } /** * Provide the standard Groovy size() method for an array. * * @param self an Array of objects * @return the size (length) of the Array * @since 1.0 */ public static int size(Object[] self) { return self.length; } /** * Support the subscript operator for CharSequence. * * @param text a CharSequence * @param index the index of the Character to get * @return the Character at the given index * @since 1.0 */ public static CharSequence getAt(CharSequence text, int index) { index = normaliseIndex(index, text.length()); return text.subSequence(index, index + 1); } /** * Support the subscript operator for String. * * @param text a String * @param index the index of the Character to get * @return the Character at the given index * @since 1.0 */ public static String getAt(String text, int index) { index = normaliseIndex(index, text.length()); return text.substring(index, index + 1); } /** * Support the range subscript operator for CharSequence * * @param text a CharSequence * @param range a Range * @return the subsequence CharSequence * @since 1.0 */ public static CharSequence getAt(CharSequence text, Range range) { int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), text.length()); int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), text.length()); boolean reverse = range.isReverse(); // If this is a backwards range, reverse the arguments to substring. if (from > to) { int tmp = from; from = to; to = tmp; reverse = !reverse; } CharSequence sequence = text.subSequence(from, to + 1); return reverse ? reverse((String) sequence) : sequence; } /** * Support the range subscript operator for CharSequence or StringBuffer with IntRange * * @param text a CharSequence * @param range an IntRange * @return the subsequence CharSequence * @since 1.0 */ public static CharSequence getAt(CharSequence text, IntRange range) { return getAt(text, (Range) range); } /** * Support the range subscript operator for CharSequence or StringBuffer with EmptyRange * * @param text a CharSequence * @param range an EmptyRange * @return the subsequence CharSequence * @since 1.5.0 */ public static CharSequence getAt(CharSequence text, EmptyRange range) { return ""; } /** * Support the range subscript operator for String with IntRange * * @param text a String * @param range an IntRange * @return the resulting String * @since 1.0 */ public static String getAt(String text, IntRange range) { return getAt(text, (Range) range); } /** * Support the range subscript operator for String with EmptyRange * * @param text a String * @param range an EmptyRange * @return the resulting String * @since 1.5.0 */ public static String getAt(String text, EmptyRange range) { return ""; } /** * Support the range subscript operator for String * * @param text a String * @param range a Range * @return a substring corresponding to the Range * @since 1.0 */ public static String getAt(String text, Range range) { int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), text.length()); int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), text.length()); // If this is a backwards range, reverse the arguments to substring. boolean reverse = range.isReverse(); if (from > to) { int tmp = to; to = from; from = tmp; reverse = !reverse; } String answer = text.substring(from, to + 1); if (reverse) { answer = reverse(answer); } return answer; } /** * Creates a new string which is the reverse (backwards) of this string * * @param self a String * @return a new string with all the characters reversed. * @since 1.0 * @see java.lang.StringBuilder#reverse() */ public static String reverse(String self) { return new StringBuilder(self).reverse().toString(); } /** * Creates a new CharSequence which is the reverse (backwards) of this string * * @param self a CharSequence * @return a new CharSequence with all the characters reversed. * @see #reverse(String) * @since 1.8.2 */ public static CharSequence reverse(CharSequence self) { return new StringBuilder(self).reverse().toString(); } /** *

      Strip leading whitespace/control characters followed by '|' from * every line in a String.

      *
           * assert 'ABC\n123\n456' == '''ABC
           *                             |123
           *                             |456'''.stripMargin()
           * 
      * * @param self The String to strip the margin from * @return the stripped String * @see #stripMargin(String, char) * @since 1.7.3 */ public static String stripMargin(String self) { return stripMargin(self, '|'); } /** *

      Strip leading whitespace/control characters followed by '|' from * every line in a CharSequence.

      * * @param self The CharSequence to strip the margin from * @return the stripped CharSequence * @see #stripMargin(CharSequence, char) * @since 1.8.2 */ public static CharSequence stripMargin(CharSequence self) { return stripMargin(self, '|'); } /** *

      Strip leading whitespace/control characters followed by marginChar from * every line in a String.

      * * @param self The String to strip the margin from * @param marginChar Any character that serves as margin delimiter * @return the stripped String * @see #stripMargin(String, char) * @since 1.7.3 */ public static String stripMargin(String self, String marginChar) { if (marginChar == null || marginChar.length() == 0) return stripMargin(self, '|'); // TODO IllegalArgumentException for marginChar.length() > 1 ? Or support String as marker? return stripMargin(self, marginChar.charAt(0)); } /** *

      Strip leading whitespace/control characters followed by marginChar from * every line in a CharSequence.

      * * @param self The CharSequence to strip the margin from * @param marginChar Any character that serves as margin delimiter * @return the stripped CharSequence * @see #stripMargin(String, String) * @since 1.8.2 */ public static String stripMargin(CharSequence self, CharSequence marginChar) { return stripMargin(self.toString(), marginChar.toString()); } /** *

      Strip leading whitespace/control characters followed by marginChar from * every line in a String.

      *
           * assert 'ABC\n123\n456' == '''ABC
           *                             *123
           *                             *456'''.stripMargin('*')
           * 
      * * @param self The String to strip the margin from * @param marginChar Any character that serves as margin delimiter * @return the stripped String * @since 1.7.3 */ public static String stripMargin(String self, char marginChar) { if (self.length() == 0) return self; try { StringBuilder builder = new StringBuilder(); for (String line : readLines(self)) { builder.append(stripMarginFromLine(line, marginChar)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!self.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return self; } /** *

      Strip leading whitespace/control characters followed by marginChar from * every line in a String.

      * * @param self The CharSequence to strip the margin from * @param marginChar Any character that serves as margin delimiter * @return the stripped CharSequence * @see #stripMargin(String, char) * @since 1.8.2 */ public static CharSequence stripMargin(CharSequence self, char marginChar) { return stripMargin(self.toString(), marginChar); } // TODO expose this for stream based stripping? private static String stripMarginFromLine(String line, char marginChar) { int length = line.length(); int index = 0; while (index < length && line.charAt(index) <= ' ') index++; return (index < length && line.charAt(index) == marginChar) ? line.substring(index + 1) : line; } /** *

      Strip leading spaces from every line in a String. The * line with the least number of leading spaces determines * the number to remove. Lines only containing whitespace are * ignored when calculating the number of leading spaces to strip.

      *
           * assert '  A\n B\nC' == '   A\n  B\n C'.stripIndent()
           * 
      * * @param self The String to strip the leading spaces from * @return the stripped String * @see #stripIndent(String, int) * @since 1.7.3 */ public static String stripIndent(String self) { if (self.length() == 0) return self; int runningCount = -1; try { for (String line : readLines(self)) { // don't take blank lines into account for calculating the indent if (isAllWhitespace(line)) continue; if (runningCount == -1) runningCount = line.length(); runningCount = findMinimumLeadingSpaces(line, runningCount); if (runningCount == 0) break; } } catch (IOException e) { /* ignore */ } return stripIndent(self, runningCount == -1 ? 0 : runningCount); } /** *

      Strip leading spaces from every line in a CharSequence. The * line with the least number of leading spaces determines * the number to remove. Lines only containing whitespace are * ignored when calculating the number of leading spaces to strip.

      * * @param self The CharSequence to strip the leading spaces from * @return the stripped CharSequence * @see #stripIndent(String) * @since 1.8.2 */ public static CharSequence stripIndent(CharSequence self) { return stripIndent(self.toString()); } /** * True if a String only contains whitespace characters. * * @param self The String to check the characters in * @return true If all characters are whitespace characters * @see Character#isWhitespace(char) * @since 1.6 */ public static boolean isAllWhitespace(String self) { for (int i = 0; i < self.length(); i++) { if (!Character.isWhitespace(self.charAt(i))) return false; } return true; } /** * True if a CharSequence only contains whitespace characters. * * @param self The CharSequence to check the characters in * @return true If all characters are whitespace characters * @see #isAllWhitespace(String) * @since 1.8.2 */ public static boolean isAllWhitespace(CharSequence self) { return isAllWhitespace(self.toString()); } // TODO expose this for stream based scenarios? private static int findMinimumLeadingSpaces(String line, int count) { int length = line.length(); int index = 0; while (index < length && index < count && Character.isWhitespace(line.charAt(index))) index++; return index; } /** *

      Strip numChar leading characters from * every line in a String.

      *
           * assert 'DEF\n456' == '''ABCDEF\n123456'''.stripIndent(3)
           * 
      * * @param self The String to strip the characters from * @param numChars The number of characters to strip * @return the stripped String * @since 1.7.3 */ public static String stripIndent(String self, int numChars) { if (self.length() == 0 || numChars <= 0) return self; try { StringBuilder builder = new StringBuilder(); for (String line : readLines(self)) { // normalize an empty or whitespace line to \n // or strip the indent for lines containing non-space characters if (!isAllWhitespace(line)) { builder.append(stripIndentFromLine(line, numChars)); } builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!self.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return self; } /** *

      Strip numChar leading characters from * every line in a CharSequence.

      * * @param self The CharSequence to strip the characters from * @param numChars The number of characters to strip * @return the stripped CharSequence * @since 1.8.2 */ public static CharSequence stripIndent(CharSequence self, int numChars) { return stripIndent(self); } // TODO expose this for stream based stripping? private static String stripIndentFromLine(String line, int numChars) { int length = line.length(); return numChars <= length ? line.substring(numChars) : ""; } /** * Transforms a String representing a URL into a URL object. * * @param self the String representing a URL * @return a URL * @throws MalformedURLException is thrown if the URL is not well formed. * @since 1.0 */ public static URL toURL(String self) throws MalformedURLException { return new URL(self); } /** * Transforms a CharSequence representing a URL into a URL object. * * @param self the CharSequence representing a URL * @return a URL * @throws MalformedURLException is thrown if the URL is not well formed. * @since 1.8.2 */ public static URL toURL(CharSequence self) throws MalformedURLException { return new URL(self.toString()); } /** * Transforms a String representing a URI into a URI object. * * @param self the String representing a URI * @return a URI * @throws URISyntaxException is thrown if the URI is not well formed. * @since 1.0 */ public static URI toURI(String self) throws URISyntaxException { return new URI(self); } /** * Transforms a CharSequence representing a URI into a URI object. * * @param self the CharSequence representing a URI * @return a URI * @throws URISyntaxException is thrown if the URI is not well formed. * @since 1.8.2 */ public static URI toURI(CharSequence self) throws URISyntaxException { return new URI(self.toString()); } /** * Turns a String into a regular expression Pattern * * @param self a String to convert into a regular expression * @return the regular expression pattern * @since 1.5.0 */ public static Pattern bitwiseNegate(String self) { return Pattern.compile(self); } /** * Turns a CharSequence into a regular expression Pattern * * @param self a String to convert into a regular expression * @return the regular expression pattern * @since 1.8.2 */ public static Pattern bitwiseNegate(CharSequence self) { return Pattern.compile(self.toString()); } /** * Replaces the first substring of a String that matches the given * compiled regular expression with the given replacement. *

      * Note that backslashes (\) and dollar signs ($) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceFirst}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. *

      *

           * assert "foo".replaceFirst('o', 'X') == 'fXo'
           * 
      * * @param self the string that is to be matched * @param pattern the regex Pattern to which the string of interest is to be matched * @param replacement the string to be substituted for the first match * @return The resulting String * @see java.lang.String#replaceFirst(java.lang.String, java.lang.String) * @since 1.6.1 */ public static String replaceFirst(String self, Pattern pattern, String replacement) { return pattern.matcher(self).replaceFirst(replacement); } /** * Replaces the first substring of a CharSequence that matches the given * compiled regular expression with the given replacement. * * @param self the CharSequence that is to be matched * @param pattern the regex Pattern to which the CharSequence of interest is to be matched * @param replacement the CharSequence to be substituted for the first match * @return The resulting CharSequence * @see #replaceFirst(String, Pattern, String) * @since 1.8.2 */ public static CharSequence replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement) { return pattern.matcher(self).replaceFirst(replacement.toString()); } /** * Replaces all substrings of a String that match the given * compiled regular expression with the given replacement. *

      * Note that backslashes (\) and dollar signs ($) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceAll}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. *

      *

           * assert "foo".replaceAll('o', 'X') == 'fXX'
           * 
      * * @param self the string that is to be matched * @param pattern the regex Pattern to which the string of interest is to be matched * @param replacement the string to be substituted for the first match * @return The resulting String * @see java.lang.String#replaceAll(java.lang.String, java.lang.String) * @since 1.6.1 */ public static String replaceAll(String self, Pattern pattern, String replacement) { return pattern.matcher(self).replaceAll(replacement); } /** * Replaces all substrings of a CharSequence that match the given * compiled regular expression with the given replacement. * * @param self the CharSequence that is to be matched * @param pattern the regex Pattern to which the CharSequence of interest is to be matched * @param replacement the CharSequence to be substituted for the first match * @return The resulting CharSequence * @see #replaceAll(String, Pattern, String) * @since 1.8.2 */ public static CharSequence replaceAll(CharSequence self, Pattern pattern, CharSequence replacement) { return pattern.matcher(self).replaceAll(replacement.toString()); } /** * Translates a string by replacing characters from the sourceSet with characters from replacementSet. * If the first character from sourceSet appears in the string, it will be replaced with the first character from replacementSet. * If the second character from sourceSet appears in the string, it will be replaced with the second character from replacementSet. * and so on for all provided replacement characters. *

      * Here is an example which converts the vowels in a word from lower to uppercase: *

           * assert 'hello'.tr('aeiou', 'AEIOU') == 'hEllO'
           * 
      * A character range using regex-style syntax can also be used, e.g. here is an example which converts a word from lower to uppercase: *
           * assert 'hello'.tr('a-z', 'A-Z') == 'HELLO'
           * 
      * Hyphens at the start or end of sourceSet or replacementSet are treated as normal hyphens and are not * considered to be part of a range specification. Similarly, a hyphen immediately after an earlier range * is treated as a normal hyphen. So, '-x', 'x-' have no ranges while 'a-c-e' has the range 'a-c' plus * the '-' character plus the 'e' character. *

      * Unlike the unix tr command, Groovy's tr command supports reverse ranges, e.g.: *

           * assert 'hello'.tr('z-a', 'Z-A') == 'HELLO'
           * 
      * If replacementSet is smaller than sourceSet, then the last character from replacementSet is used as the replacement for all remaining source characters as shown here: *
           * assert 'Hello World!'.tr('a-z', 'A') == 'HAAAA WAAAA!'
           * 
      * If sourceSet contains repeated characters, the last specified replacement is used as shown here: *
           * assert 'Hello World!'.tr('lloo', '1234') == 'He224 W4r2d!'
           * 
      * The functionality provided by tr can be achieved using regular expressions but tr provides a much more compact * notation and efficient implementation for certain scenarios. * * @param self the string that is to be translated * @param sourceSet the set of characters to translate from * @param replacementSet the set of replacement characters * @return The resulting translated String * @see org.codehaus.groovy.util.StringUtil#tr(String, String, String) * @since 1.7.3 */ public static String tr(final String self, String sourceSet, String replacementSet) throws ClassNotFoundException { return (String) InvokerHelper.invokeStaticMethod("org.codehaus.groovy.util.StringUtil", "tr", new Object[]{self, sourceSet, replacementSet}); } /** * Translates a string by replacing characters from the sourceSet with characters from replacementSet. * * @param self the CharSequence that is to be translated * @param sourceSet the set of characters to translate from * @param replacementSet the set of replacement characters * @return The resulting translated CharSequence * @see #tr(String, String, String) * @since 1.8.2 */ public static CharSequence tr(final CharSequence self, CharSequence sourceSet, CharSequence replacementSet) throws ClassNotFoundException { return tr(self.toString(), sourceSet.toString(), replacementSet.toString()); } /** * Tells whether or not self matches the given * compiled regular expression Pattern. * * @param self the string that is to be matched * @param pattern the regex Pattern to which the string of interest is to be matched * @return true if the string matches * @see java.lang.String#matches(java.lang.String) * @since 1.6.1 */ public static boolean matches(String self, Pattern pattern) { return pattern.matcher(self).matches(); } /** * Tells whether or not a CharSequence matches the given * compiled regular expression Pattern. * * @param self the CharSequence that is to be matched * @param pattern the regex Pattern to which the string of interest is to be matched * @return true if the CharSequence matches * @see java.lang.String#matches(java.lang.String) * @since 1.8.2 */ public static boolean matches(CharSequence self, Pattern pattern) { return pattern.matcher(self).matches(); } /** * Finds the first occurrence of a regular expression String within a String. * If the regex doesn't match, null will be returned. *

      *

      For example, if the regex doesn't match the result is null: *

           *     assert null == "New York, NY".find(/\d{5}/)
           * 
      *

      *

      If it does match, we get the matching string back: *

           *      assert "10292" == "New York, NY 10292-0098".find(/\d{5}/)
           * 
      *

      *

      If we have capture groups in our expression, we still get back the full match *

           *      assert "10292-0098" == "New York, NY 10292-0098".find(/(\d{5})-?(\d{4})/)
           * 
      *

      * * @param self a String * @param regex the capturing regex * @return a String containing the matched portion, or null if the regex doesn't match * @since 1.6.1 */ public static String find(String self, String regex) { return find(self, Pattern.compile(regex)); } /** * Finds the first occurrence of a regular expression CharSequence within a CharSequence. * * @param self a CharSequence * @param regex the capturing regex * @return a CharSequence containing the matched portion, or null if the regex doesn't match * @see #find(String, Pattern) * @since 1.8.2 */ public static CharSequence find(CharSequence self, CharSequence regex) { return find(self.toString(), Pattern.compile(regex.toString())); } /** * Finds the first occurrence of a compiled regular expression Pattern within a String. * If the pattern doesn't match, null will be returned. *

      *

      For example, if the pattern doesn't match the result is null: *

           *     assert null == "New York, NY".find(~/\d{5}/)
           * 
      *

      *

      If it does match, we get the matching string back: *

           *      assert "10292" == "New York, NY 10292-0098".find(~/\d{5}/)
           * 
      *

      *

      If we have capture groups in our expression, the groups are ignored and * we get back the full match: *

           *      assert "10292-0098" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/)
           * 
      * If you need to work with capture groups, then use the closure version * of this method or use Groovy's matcher operators or use eachMatch. *

      * * @param self a String * @param pattern the compiled regex Pattern * @return a String containing the matched portion, or null if the regex pattern doesn't match * @since 1.6.1 */ public static String find(String self, Pattern pattern) { Matcher matcher = pattern.matcher(self); if (matcher.find()) { return matcher.group(0); } return null; } /** * Finds the first occurrence of a compiled regular expression Pattern within a CharSequence. * * @param self a CharSequence * @param pattern the compiled regex Pattern * @return a CharSequence containing the matched portion, or null if the regex pattern doesn't match * @see #find(String, Pattern) * @since 1.8.2 */ public static CharSequence find(CharSequence self, Pattern pattern) { return find(self.toString(), pattern); } /** * Returns the result of calling a closure with the first occurrence of a regular expression found within a String. * If the regex doesn't match, the closure will not be called and find will return null. *

      *

      For example, if the regex doesn't match, the result is null: *

           *     assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
           * 
      *

      *

      If it does match and we don't have any capture groups in our regex, there is a single parameter * on the closure that the match gets passed to: *

           *      assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
           * 
      *

      *

      If we have capture groups in our expression, our closure has one parameter for the match, followed by * one for each of the capture groups: *

           *      assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
           *          assert match == "10292-0098"
           *          assert zip == "10292"
           *          assert plusFour == "0098"
           *          return zip
           *      }
           * 
      *

      If we have capture groups in our expression, and our closure has one parameter, * the closure will be passed an array with the first element corresponding to the whole match, * followed by an element for each of the capture groups: *

           *      assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
           *          assert array[0] == "10292-0098"
           *          assert array[1] == "10292"
           *          assert array[2] == "0098"
           *          return array[1]
           *      }
           * 
      *

      If a capture group is optional, and doesn't match, then the corresponding value * for that capture group passed to the closure will be null as illustrated here: *

           *      assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber ->
           *          assert "233-9999" == match
           *          assert null == areaCode
           *          assert "233" == exchange
           *          assert "9999" == stationNumber
           *          return "$exchange$stationNumber"
           *      }
           * 
      *

      * * @param self a String * @param regex the capturing regex string * @param closure the closure that will be passed the full match, plus each of the capturing groups * @return a String containing the result of the closure, or null if the regex pattern doesn't match * @since 1.6.1 */ public static String find(String self, String regex, Closure closure) { return find(self, Pattern.compile(regex), closure); } /** * Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence. * If the regex doesn't match, the closure will not be called and find will return null. * * @param self a CharSequence * @param regex the capturing regex CharSequence * @param closure the closure that will be passed the full match, plus each of the capturing groups * @return a CharSequence containing the result of the closure, or null if the regex pattern doesn't match * @see #find(String, Pattern, Closure) * @since 1.8.2 */ public static CharSequence find(CharSequence self, CharSequence regex, Closure closure) { return find(self.toString(), Pattern.compile(regex.toString()), closure); } /** * Returns the result of calling a closure with the first occurrence of a compiled regular expression found within a String. * If the regex doesn't match, the closure will not be called and find will return null. *

      *

      For example, if the pattern doesn't match, the result is null: *

           *     assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
           * 
      *

      *

      If it does match and we don't have any capture groups in our regex, there is a single parameter * on the closure that the match gets passed to: *

           *      assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
           * 
      *

      *

      If we have capture groups in our expression, our closure has one parameter for the match, followed by * one for each of the capture groups: *

           *      assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
           *          assert match == "10292-0098"
           *          assert zip == "10292"
           *          assert plusFour == "0098"
           *          return zip
           *      }
           * 
      *

      If we have capture groups in our expression, and our closure has one parameter, * the closure will be passed an array with the first element corresponding to the whole match, * followed by an element for each of the capture groups: *

           *      assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
           *          assert array[0] == "10292-0098"
           *          assert array[1] == "10292"
           *          assert array[2] == "0098"
           *          return array[1]
           *      }
           * 
      *

      If a capture group is optional, and doesn't match, then the corresponding value * for that capture group passed to the closure will be null as illustrated here: *

           *      assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber ->
           *          assert "233-9999" == match
           *          assert null == areaCode
           *          assert "233" == exchange
           *          assert "9999" == stationNumber
           *          return "$exchange$stationNumber"
           *      }
           * 
      *

      * * @param self a String * @param pattern the compiled regex Pattern * @param closure the closure that will be passed the full match, plus each of the capturing groups * @return a String containing the result of the closure, or null if the regex pattern doesn't match * @since 1.6.1 */ public static String find(String self, Pattern pattern, Closure closure) { Matcher matcher = pattern.matcher(self); if (matcher.find()) { if (hasGroup(matcher)) { int count = matcher.groupCount(); List groups = new ArrayList(count); for (int i = 0; i <= count; i++) { groups.add(matcher.group(i)); } return InvokerHelper.toString(closure.call(groups)); } else { return InvokerHelper.toString(closure.call(matcher.group(0))); } } return null; } /** * Returns the result of calling a closure with the first occurrence of a regular expression found within a * CharSequence. If the regex doesn't match, the closure will not be called and find will return null. * * @param self a CharSequence * @param pattern the compiled regex Pattern * @param closure the closure that will be passed the full match, plus each of the capturing groups * @return a CharSequence containing the result of the closure, or null if the regex pattern doesn't match * @see #find(String, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.8.2 */ public static CharSequence find(CharSequence self, Pattern pattern, Closure closure) { return find(self.toString(), pattern, closure); } /** * Returns a (possibly empty) list of all occurrences of a regular expression (in String format) found within a String. *

      *

      For example, if the regex doesn't match, it returns an empty list: *

           * assert [] == "foo".findAll(/(\w*) Fish/)
           * 
      *

      Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned: *

           * def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"]
           * assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(/(\w*) Fish/)
           * 
      * If you need to work with capture groups, then use the closure version * of this method or use Groovy's matcher operators or use eachMatch. *

      * * @param self a String * @param regex the capturing regex String * @return a List containing all full matches of the regex within the string, an empty list will be returned if there are no matches * @since 1.6.1 */ public static List findAll(String self, String regex) { return findAll(self, Pattern.compile(regex)); } /** * Returns a (possibly empty) list of all occurrences of a regular expression (in CharSequence format) found within a CharSequence. * * @param self a CharSequence * @param regex the capturing regex CharSequence * @return a List containing all full matches of the regex within the CharSequence, an empty list will be returned if there are no matches * @see #findAll(String, String) * @since 1.8.2 */ public static List findAll(CharSequence self, CharSequence regex) { return new ArrayList(findAll(self.toString(), regex.toString())); } /** * Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a String. *

      *

      For example, if the pattern doesn't match, it returns an empty list: *

           * assert [] == "foo".findAll(~/(\w*) Fish/)
           * 
      *

      Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned: *

           * def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"]
           * assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(~/(\w*) Fish/)
           * 
      * * @param self a String * @param pattern the compiled regex Pattern * @return a List containing all full matches of the Pattern within the string, an empty list will be returned if there are no matches * @since 1.6.1 */ public static List findAll(String self, Pattern pattern) { Matcher matcher = pattern.matcher(self); List list = new ArrayList(); for (Iterator iter = iterator(matcher); iter.hasNext();) { if (hasGroup(matcher)) { list.add((String) ((List) iter.next()).get(0)); } else { list.add((String) iter.next()); } } return list; } /** * Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a CharSequence. * * @param self a CharSequence * @param pattern the compiled regex Pattern * @return a List containing all full matches of the Pattern within the CharSequence, an empty list will be returned if there are no matches * @see #findAll(String, Pattern) * @since 1.8.2 */ public static List findAll(CharSequence self, Pattern pattern) { return new ArrayList(findAll(self.toString(), pattern)); } /** * Finds all occurrences of a regular expression string within a String. Any matches are passed to the specified closure. The closure * is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters. *

      * If there are no matches, the closure will not be called, and an empty List will be returned. *

      *

      For example, if the regex doesn't match, it returns an empty list: *

           * assert [] == "foo".findAll(/(\w*) Fish/) { match, firstWord -> return firstWord }
           * 
      *

      Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match: *

           * assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(/.ould/) { match -> "${match}n't"}
           * 
      *

      If there are capture groups, the first parameter will be the match followed by one parameter for each capture group: *

           * def orig = "There's a Wocket in my Pocket"
           * assert ["W > Wocket", "P > Pocket"] == orig.findAll(/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
           * 
      * * @param self a String * @param regex the capturing regex String * @param closure will be passed the full match plus each of the capturing groups * @return a List containing all full matches of the regex within the string, an empty list will be returned if there are no matches * @since 1.6.1 */ public static List findAll(String self, String regex, Closure closure) { return findAll(self, Pattern.compile(regex), closure); } /** * Finds all occurrences of a capturing regular expression CharSequence within a CharSequence. * * @param self a CharSequence * @param regex the capturing regex CharSequence * @param closure will be passed the full match plus each of the capturing groups * @return a List containing all full matches of the regex within the CharSequence, an empty list will be returned if there are no matches * @see #findAll(String, String, Closure) * @since 1.8.2 */ public static List findAll(CharSequence self, CharSequence regex, Closure closure) { return findAll(self.toString(), regex.toString(), closure); } /** * Finds all occurrences of a compiled regular expression Pattern within a String. Any matches are passed to the specified closure. The closure * is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters. *

      * If there are no matches, the closure will not be called, and an empty List will be returned. *

      *

      For example, if the pattern doesn't match, it returns an empty list: *

           * assert [] == "foo".findAll(~/(\w*) Fish/) { match, firstWord -> return firstWord }
           * 
      *

      Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match: *

           * assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(~/.ould/) { match -> "${match}n't"}
           * 
      *

      If there are capture groups, the first parameter will be the match followed by one parameter for each capture group: *

           * def orig = "There's a Wocket in my Pocket"
           * assert ["W > Wocket", "P > Pocket"] == orig.findAll(~/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
           * 
      * * @param self a String * @param pattern the compiled regex Pattern * @param closure will be passed the full match plus each of the capturing groups * @return a List containing all full matches of the regex Pattern within the string, an empty list will be returned if there are no matches * @since 1.6.1 */ public static List findAll(String self, Pattern pattern, Closure closure) { Matcher matcher = pattern.matcher(self); return collect(matcher, closure); } /** * Finds all occurrences of a compiled regular expression Pattern within a CharSequence. * * @param self a CharSequence * @param pattern the compiled regex Pattern * @param closure will be passed the full match plus each of the capturing groups * @return a List containing all full matches of the regex Pattern within the CharSequence, an empty list will be returned if there are no matches * @see #findAll(String, Pattern, Closure) * @since 1.8.2 */ public static List findAll(CharSequence self, Pattern pattern, Closure closure) { return findAll(self.toString(), pattern, closure); } /** * Replaces all occurrences of a captured group by the result of a closure on that text. *

      *

      For examples, *

           *     assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() }
           * 

      * assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) *

      * Here, * it[0] is the global string of the matched group * it[1] is the first string in the matched group * it[2] is the second string in the matched group *

      *

      * assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) *

      * Here, * x is the global string of the matched group * y is the first string in the matched group * z is the second string in the matched group *

      *

      Note that unlike String.replaceAll(String regex, String replacement), where the replacement string * treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string * and that value is used literally for the replacement.

      * * @param self a String * @param regex the capturing regex * @param closure the closure to apply on each captured group * @return a String with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @since 1.0 * @see java.util.regex.Matcher#quoteReplacement(java.lang.String) * @see #replaceAll(String, Pattern, Closure) */ public static String replaceAll(final String self, final String regex, final Closure closure) { return replaceAll(self, Pattern.compile(regex), closure); } /** * Replaces all occurrences of a captured group by the result of a closure on that text. * * @param self a CharSequence * @param regex the capturing regex * @param closure the closure to apply on each captured group * @return a CharSequence with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @since 1.8.2 * @see #replaceAll(String, Pattern, Closure) */ public static CharSequence replaceAll(final CharSequence self, final CharSequence regex, final Closure closure) { return replaceAll(self.toString(), Pattern.compile(regex.toString()), closure); } /** * Replaces each substring of this CharSequence that matches the given * regular expression with the given replacement. * * @param self a CharSequence * @param regex the capturing regex * @param replacement the capturing regex * @return a CharSequence with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @see String#replaceAll(String, String) * @since 1.8.2 */ public static CharSequence replaceAll(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceAll(regex.toString(), replacement.toString()); } /** * Replaces the first occurrence of a captured group by the result of a closure call on that text. *

      *

      For example (with some replaceAll variants thrown in for comparison purposes), *

           * assert "hellO world" == "hello world".replaceFirst("(o)") { it[0].toUpperCase() } // first match
           * assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() }   // all matches
           * 

      * assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } * assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } *

      * * @param self a String * @param regex the capturing regex * @param closure the closure to apply on the first captured group * @return a String with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @since 1.7.7 * @see java.util.regex.Matcher#quoteReplacement(java.lang.String) * @see #replaceFirst(String, Pattern, Closure) */ public static String replaceFirst(final String self, final String regex, final Closure closure) { return replaceFirst(self, Pattern.compile(regex), closure); } /** * Replaces the first substring of this CharSequence that matches the given * regular expression with the given replacement. * * @param self a CharSequence * @param regex the capturing regex * @param replacement the capturing regex * @return a CharSequence with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @see String#replaceAll(String, String) * @since 1.8.2 */ public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceFirst(regex.toString(), replacement.toString()); } /** * Replaces the first occurrence of a captured group by the result of a closure call on that text. * * @param self a CharSequence * @param regex the capturing regex * @param closure the closure to apply on the first captured group * @return a CharSequence with replaced content * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @see #replaceFirst(String, String, Closure) * @since 1.8.2 */ public static String replaceFirst(final CharSequence self, final CharSequence regex, final Closure closure) { return replaceFirst(self.toString(), regex.toString(), closure); } /** * Get a replacement corresponding to the matched pattern for {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#replaceAll(String, Pattern, Closure)}. * The closure take parameter: *
        *
      • Whole of match if the pattern include no capturing group
      • *
      • Object[] of capturing groups if the closure takes Object[] as parameter
      • *
      • List of capturing groups
      • *
      * * @param matcher the matcher object used for matching * @param closure specified with replaceAll() to get replacement * @return replacement correspond replacement for a match */ private static String getReplacement(Matcher matcher, Closure closure) { if (!hasGroup(matcher)) { return InvokerHelper.toString(closure.call(matcher.group())); } int count = matcher.groupCount(); List groups = new ArrayList(); for (int i = 0; i <= count; i++) { groups.add(matcher.group(i)); } if (closure.getParameterTypes().length == 1 && closure.getParameterTypes()[0] == Object[].class) { return InvokerHelper.toString(closure.call(groups.toArray())); } return InvokerHelper.toString(closure.call(groups)); } /** * Replaces all occurrences of a captured group by the result of a closure call on that text. *

      *

      For examples, *

           *     assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() }
           * 

      * assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { it[0].toUpperCase() }) *

      * Here, * it[0] is the global string of the matched group * it[1] is the first string in the matched group * it[2] is the second string in the matched group *

      *

      * assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) *

      * Here, * it[0] is the global string of the matched group * it[1] is the first string in the matched group * it[2] is the second string in the matched group *

      *

      * assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) *

      * Here, * x is the global string of the matched group * y is the first string in the matched group * z is the second string in the matched group *

      *

      Note that unlike String.replaceAll(String regex, String replacement), where the replacement string * treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string * and that value is used literally for the replacement.

      * * @param self a String * @param pattern the capturing regex Pattern * @param closure the closure to apply on each captured group * @return a String with replaced content * @since 1.6.8 * @see java.util.regex.Matcher#quoteReplacement(java.lang.String) */ public static String replaceAll(final String self, final Pattern pattern, final Closure closure) { final Matcher matcher = pattern.matcher(self); if (matcher.find()) { final StringBuffer sb = new StringBuffer(self.length() + 16); do { String replacement = getReplacement(matcher, closure); matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); } while (matcher.find()); matcher.appendTail(sb); return sb.toString(); } else { return self; } } /** * Replaces all occurrences of a captured group by the result of a closure call on that text. * * @param self a CharSequence * @param pattern the capturing regex Pattern * @param closure the closure to apply on each captured group * @return a CharSequence with replaced content * @since 1.8.2 * @see #replaceAll(String, Pattern, Closure) */ public static String replaceAll(final CharSequence self, final Pattern pattern, final Closure closure) { return replaceAll(self.toString(), pattern, closure); } /** * Replaces the first occurrence of a captured group by the result of a closure call on that text. *

      *

      For example (with some replaceAll variants thrown in for comparison purposes), *

           * assert "hellO world" == "hello world".replaceFirst(~"(o)") { it[0].toUpperCase() } // first match
           * assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() }   // all matches
           * 

      * assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } * assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } *

      * * @param self a String * @param pattern the capturing regex Pattern * @param closure the closure to apply on the first captured group * @return a String with replaced content * @since 1.7.7 * @see #replaceAll(String, Pattern, Closure) */ public static String replaceFirst(final String self, final Pattern pattern, final Closure closure) { final Matcher matcher = pattern.matcher(self); if (matcher.find()) { final StringBuffer sb = new StringBuffer(self.length() + 16); String replacement = getReplacement(matcher, closure); matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); matcher.appendTail(sb); return sb.toString(); } else { return self; } } /** * Replaces the first occurrence of a captured group by the result of a closure call on that text. * * @param self a CharSequence * @param pattern the capturing regex Pattern * @param closure the closure to apply on the first captured group * @return a CharSequence with replaced content * @see #replaceFirst(String, Pattern, Closure) * @since 1.8.2 */ public static String replaceFirst(final CharSequence self, final Pattern pattern, final Closure closure) { return replaceFirst(self.toString(), pattern, closure); } private static String getPadding(String padding, int length) { if (padding.length() < length) { return multiply(padding, length / padding.length() + 1).substring(0, length); } else { return padding.substring(0, length); } } /** * Pad a String to a minimum length specified by numberOfChars, adding the supplied padding String as many times as needed to the left. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * println 'Numbers:'
           * [1, 10, 100, 1000].each{ println it.toString().padLeft(5, '*') }
           * [2, 20, 200, 2000].each{ println it.toString().padLeft(5, '*_') }
           * 
      * will produce output like: *
           * Numbers:
           * ****1
           * ***10
           * **100
           * *1000
           * *_*_2
           * *_*20
           * *_200
           * *2000
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @param padding the characters used for padding * @return the String padded to the left * @since 1.0 */ public static String padLeft(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { return getPadding(padding, numChars - self.length()) + self; } } /** * Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the left. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting CharSequence * @param padding the characters used for padding * @return the CharSequence padded to the left * @see #padLeft(String, Number, String) * @since 1.8.2 */ public static CharSequence padLeft(CharSequence self, Number numberOfChars, CharSequence padding) { return padLeft(self.toString(), numberOfChars, padding.toString()); } /** * Pad a String to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * println 'Numbers:'
           * [1, 10, 100, 1000].each{ println it.toString().padLeft(5) }
           * 
      * will produce output like: *
           * Numbers:
           *     1
           *    10
           *   100
           *  1000
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @return the String padded to the left * @see #padLeft(String, Number, String) * @since 1.0 */ public static String padLeft(String self, Number numberOfChars) { return padLeft(self, numberOfChars, " "); } /** * Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting CharSequence * @return the CharSequence padded to the left * @see #padLeft(CharSequence, Number, CharSequence) * @since 1.8.2 */ public static CharSequence padLeft(CharSequence self, Number numberOfChars) { return padLeft(self, numberOfChars, " "); } /** * Pad a String to a minimum length specified by numberOfChars, adding the supplied padding String as many times as needed to the right. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * ['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5, '#') + it.size() }
           * 
      * will produce output like: *
           * A####1
           * BB###2
           * CCC##3
           * DDDD#4
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @param padding the characters used for padding * @return the String padded to the right * @since 1.0 */ public static String padRight(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { return self + getPadding(padding, numChars - self.length()); } } /** * Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the right. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting CharSequence * @param padding the characters used for padding * @return the CharSequence padded to the right * @see #padRight(String, Number, String) * @since 1.8.2 */ public static CharSequence padRight(CharSequence self, Number numberOfChars, CharSequence padding) { return padRight(self.toString(), numberOfChars, padding.toString()); } /** * Pad a String to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * ['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5) + it.size() }
           * 
      * will produce output like: *
           * A    1
           * BB   2
           * CCC  3
           * DDDD 4
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @return the String padded to the right * @since 1.0 */ public static String padRight(String self, Number numberOfChars) { return padRight(self, numberOfChars, " "); } /** * Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting string * @return the CharSequence padded to the right * @see #padRight(String, Number) * @since 1.8.2 */ public static CharSequence padRight(CharSequence self, Number numberOfChars) { return padRight(self.toString(), numberOfChars); } /** * Pad a String to a minimum length specified by numberOfChars, appending the supplied padding String around the original as many times as needed keeping it centered. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * ['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6, '+') + '|' }
           * 
      * will produce output like: *
           * |++A+++|
           * |++BB++|
           * |+CCC++|
           * |+DDDD+|
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @param padding the characters used for padding * @return the String centered with padded characters around it * @since 1.0 */ public static String center(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { int charsToAdd = numChars - self.length(); String semiPad = charsToAdd % 2 == 1 ? getPadding(padding, charsToAdd / 2 + 1) : getPadding(padding, charsToAdd / 2); if (charsToAdd % 2 == 0) return semiPad + self + semiPad; else return semiPad.substring(0, charsToAdd / 2) + self + semiPad; } } /** * Pad a CharSequence to a minimum length specified by numberOfChars, appending the supplied padding CharSequence around the original as many times as needed keeping it centered. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting CharSequence * @param padding the characters used for padding * @return the CharSequence centered with padded characters around it * @see #center(String, Number, String) * @since 1.8.2 */ public static CharSequence center(CharSequence self, Number numberOfChars, CharSequence padding) { return center(self.toString(), numberOfChars, padding.toString()); } /** * Pad a String to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered. * * If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example: *
           * ['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6) + '|' }
           * 
      * will produce output like: *
           * |  A   |
           * |  BB  |
           * | CCC  |
           * | DDDD |
           * 
      * * @param self a String object * @param numberOfChars the total minimum number of characters of the resulting string * @return the String centered with padded characters around it * @see #center(String, Number, String) * @since 1.0 */ public static String center(String self, Number numberOfChars) { return center(self, numberOfChars, " "); } /** * Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered. * * @param self a CharSequence object * @param numberOfChars the total minimum number of characters of the resulting CharSequence * @return the CharSequence centered with padded characters around it * @see #center(String, Number) * @since 1.8.2 */ public static CharSequence center(CharSequence self, Number numberOfChars) { return center(self.toString(), numberOfChars); } /** * Support the subscript operator, e.g. matcher[index], for a regex Matcher. *

      * For an example using no group match, *

           *    def p = /ab[d|f]/
           *    def m = "abcabdabeabf" =~ p
           *    assert 2 == m.count
           *    assert 2 == m.size() // synonym for m.getCount()
           *    assert ! m.hasGroup()
           *    assert 0 == m.groupCount()
           *    def matches = ["abd", "abf"]
           *    for (i in 0..<m.count) {
           *      assert m[i] == matches[i]
           *    }
           * 
      *

      * For an example using group matches, *

           *    def p = /(?:ab([c|d|e|f]))/
           *    def m = "abcabdabeabf" =~ p
           *    assert 4 == m.count
           *    assert m.hasGroup()
           *    assert 1 == m.groupCount()
           *    def matches = [["abc", "c"], ["abd", "d"], ["abe", "e"], ["abf", "f"]]
           *    for (i in 0..<m.count) {
           *      assert m[i] == matches[i]
           *    }
           * 
      *

      * For another example using group matches, *

           *    def m = "abcabdabeabfabxyzabx" =~ /(?:ab([d|x-z]+))/
           *    assert 3 == m.count
           *    assert m.hasGroup()
           *    assert 1 == m.groupCount()
           *    def matches = [["abd", "d"], ["abxyz", "xyz"], ["abx", "x"]]
           *    for (i in 0..<m.count) {
           *      assert m[i] == matches[i]
           *    }
           * 
      * * @param matcher a Matcher * @param idx an index * @return object a matched String if no groups matched, list of matched groups otherwise. * @since 1.0 */ public static Object getAt(Matcher matcher, int idx) { try { int count = getCount(matcher); if (idx < -count || idx >= count) { throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")"); } idx = normaliseIndex(idx, count); Iterator iter = iterator(matcher); Object result = null; for (int i = 0; i <= idx; i++) { result = iter.next(); } return result; } catch (IllegalStateException ex) { return null; } } /** * Set the position of the given Matcher to the given index. * * @param matcher a Matcher * @param idx the index number * @since 1.0 */ public static void setIndex(Matcher matcher, int idx) { int count = getCount(matcher); if (idx < -count || idx >= count) { throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")"); } if (idx == 0) { matcher.reset(); } else if (idx > 0) { matcher.reset(); for (int i = 0; i < idx; i++) { matcher.find(); } } else if (idx < 0) { matcher.reset(); idx += getCount(matcher); for (int i = 0; i < idx; i++) { matcher.find(); } } } /** * Find the number of Strings matched to the given Matcher. * * @param matcher a Matcher * @return int the number of Strings matched to the given matcher. * @since 1.0 */ public static int getCount(Matcher matcher) { int counter = 0; matcher.reset(); while (matcher.find()) { counter++; } return counter; } /** * Check whether a Matcher contains a group or not. * * @param matcher a Matcher * @return boolean true if matcher contains at least one group. * @since 1.0 */ public static boolean hasGroup(Matcher matcher) { return matcher.groupCount() > 0; } /** * Support the range subscript operator for a List. *
      def list = [1, "a", 4.5, true]
           * assert list[1..2] == ["a", 4.5]
      * * @param self a List * @param range a Range indicating the items to get * @return a sublist based on range borders or a new list if range is reversed * @see java.util.List#subList(int,int) * @since 1.0 */ public static List getAt(List self, Range range) { RangeInfo info = subListBorders(self.size(), range); List answer = self.subList(info.from, info.to); // sublist is always exclusive, but Ranges are not if (info.reverse) { answer = reverse(answer); } return answer; } /** * Support the range subscript operator for a List. *
      def list = [true, 1, 3.4]
           * assert list[0..<0] == []
      * * @param self a List * @param range a Range indicating the items to get * @return a sublist based on range borders or a new list if range is reversed * @see java.util.List#subList(int,int) * @since 1.0 */ public static List getAt(List self, EmptyRange range) { return new ArrayList (); } /** * Select a List of items from a List using a Collection to * identify the indices to be selected. *
      def list = [true, 1, 3.4, false]
           * assert list[1,0,2] == [1, true, 3.4]
      * * @param self a List * @param indices a Collection of indices * @return a new list of the values at the given indices * @since 1.0 */ public static List getAt(List self, Collection indices) { List answer = new ArrayList(indices.size()); for (Object value : indices) { if (value instanceof Range) { answer.addAll(getAt(self, (Range) value)); } else if (value instanceof List) { answer.addAll(getAt(self, (List) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); answer.add(getAt(self, idx)); } } return answer; } /** * Select a List of items from an Object array using a Collection to * identify the indices to be selected. * * @param self an Array of Objects * @param indices a Collection of indices * @return a new list of the values at the given indices * @since 1.0 */ public static List getAt(T[] self, Collection indices) { List answer = new ArrayList(indices.size()); for (Object value : indices) { if (value instanceof Range) { answer.addAll(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.addAll(getAt(self, (Collection) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); answer.add(getAtImpl(self, idx)); } } return answer; } /** * Select a List of characters from a CharSequence using a Collection * to identify the indices to be selected. * * @param self a CharSequence * @param indices a Collection of indices * @return a CharSequence consisting of the characters at the given indices * @since 1.0 */ public static CharSequence getAt(CharSequence self, Collection indices) { StringBuilder answer = new StringBuilder(); for (Object value : indices) { if (value instanceof Range) { answer.append(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.append(getAt(self, (Collection) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); answer.append(getAt(self, idx)); } } return answer.toString(); } /** * Select a List of characters from a String using a Collection * to identify the indices to be selected. * * @param self a String * @param indices a Collection of indices * @return a String consisting of the characters at the given indices * @since 1.0 */ public static String getAt(String self, Collection indices) { return (String) getAt((CharSequence) self, indices); } /** * Select a List of values from a Matcher using a Collection * to identify the indices to be selected. * * @param self a Matcher * @param indices a Collection of indices * @return a String of the values at the given indices * @since 1.6.0 */ public static List getAt(Matcher self, Collection indices) { List result = new ArrayList(); for (Object value : indices) { if (value instanceof Range) { result.addAll(getAt(self, (Range) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); result.add(getAt(self, idx)); } } return result; } /** * Creates a sub-Map containing the given keys. This method is similar to * List.subList() but uses keys rather than index ranges. *
      assert [1:10, 2:20, 4:40].subMap( [2, 4] ) == [2:20, 4:40]
      * * @param map a Map * @param keys a Collection of keys * @return a new Map containing the given keys * @since 1.0 */ public static Map subMap(Map map, Collection keys) { Map answer = new LinkedHashMap(keys.size()); for (K key : keys) { answer.put(key, map.get(key)); } return answer; } /** * Looks up an item in a Map for the given key and returns the value - unless * there is no entry for the given key in which case add the default value * to the map and return that. *
      def map=[:]
           * map.get("a", []) << 5
           * assert map == [a:[5]]
      * * @param map a Map * @param key the key to lookup the value of * @param defaultValue the value to return and add to the map for this key if * there is no entry for the given key * @return the value of the given key or the default value, added to the map if the * key did not exist * @since 1.0 */ public static V get(Map map, K key, V defaultValue) { if (!map.containsKey(key)) { map.put(key, defaultValue); } return map.get(key); } /** * Support the range subscript operator for an Array * * @param array an Array of Objects * @param range a Range * @return a range of a list from the range's from index up to but not * including the range's to value * @since 1.0 */ public static List getAt(T[] array, Range range) { List list = Arrays.asList(array); return getAt(list, range); } /** * * @param array an Array of Objects * @param range an IntRange * @return a range of a list from the range's from index up to but not * including the range's to value * @since 1.0 */ public static List getAt(T[] array, IntRange range) { List list = Arrays.asList(array); return getAt(list, range); } /** * * @param array an Array of Objects * @param range an EmptyRange * @return an empty Range * @since 1.5.0 */ public static List getAt(T[] array, EmptyRange range) { return new ArrayList(); } /** * * @param array an Array of Objects * @param range an ObjectRange * @return a range of a list from the range's from index up to but not * including the range's to value * @since 1.0 */ public static List getAt(T[] array, ObjectRange range) { List list = Arrays.asList(array); return getAt(list, range); } private static T getAtImpl(T[] array, int idx) { return array[normaliseIndex(idx, array.length)]; } /** * Allows conversion of arrays into a mutable List. * * @param array an Array of Objects * @return the array as a List * @since 1.0 */ public static List toList(T[] array) { return new ArrayList(Arrays.asList(array)); } /** * Support the subscript operator for a List. *
      def list = [2, "a", 5.3]
           * assert list[1] == "a"
      * * @param self a List * @param idx an index * @return the value at the given index * @since 1.0 */ public static T getAt(List self, int idx) { int size = self.size(); int i = normaliseIndex(idx, size); if (i < size) { return self.get(i); } else { return null; } } /** * Support the subscript operator for an Iterator. The iterator * will be partially exhausted up until the idx entry after returning * if a +ve or 0 idx is used, or fully exhausted if a -ve idx is used * or no corresponding entry was found. Typical usage: *
           * def iter = [2, "a", 5.3].iterator()
           * assert iter[1] == "a"
           * 
      * A more elaborate example: *
           * def items = [2, "a", 5.3]
           * def iter = items.iterator()
           * assert iter[-1] == 5.3
           * // iter exhausted, so reset
           * iter = items.iterator()
           * assert iter[1] == "a"
           * // iter partially exhausted so now idx starts after "a"
           * assert iter[0] == 5.3
           * 
      * * @param self an Iterator * @param idx an index value (-self.size() <= idx < self.size()) * @return the value at the given index (after normalisation) or null if no corresponding value was found * @since 1.7.2 */ public static T getAt(Iterator self, int idx) { if (idx < 0) { // calculate whole list in this case // recommend avoiding -ve's as this is not as efficient List list = toList(self); int adjustedIndex = idx + list.size(); if (adjustedIndex < 0 || adjustedIndex >= list.size()) return null; return list.get(adjustedIndex); } int count = 0; while (self.hasNext()) { if (count == idx) { return self.next(); } else { count++; self.next(); } } return null; } /** * A helper method to allow lists to work with subscript operators. *
      def list = [2, 3]
           * list[0] = 1
           * assert list == [1, 3]
      * * @param self a List * @param idx an index * @param value the value to put at the given index * @since 1.0 */ public static void putAt(List self, int idx, T value) { int size = self.size(); idx = normaliseIndex(idx, size); if (idx < size) { self.set(idx, value); } else { while (size < idx) { self.add(size++, null); } self.add(idx, value); } } /** * Support the range subscript operator for StringBuffer. Index values are * treated as characters within the buffer. * * @param self a StringBuffer * @param range a Range * @param value the object that's toString() will be inserted * @since 1.0 */ public static void putAt(StringBuffer self, IntRange range, Object value) { RangeInfo info = subListBorders(self.length(), range); self.replace(info.from, info.to, value.toString()); } /** * Support the range subscript operator for StringBuffer. * * @param self a StringBuffer * @param range a Range * @param value the object that's toString() will be inserted * @since 1.0 */ public static void putAt(StringBuffer self, EmptyRange range, Object value) { RangeInfo info = subListBorders(self.length(), range); self.replace(info.from, info.to, value.toString()); } /** * A helper method to allow lists to work with subscript operators. *
      def list = ["a", true]
           * list[1..<1] = 5
           * assert list == ["a", 5, true]
      * * @param self a List * @param range the (in this case empty) subset of the list to set * @param value the values to put at the given sublist or a Collection of values * @since 1.0 */ public static void putAt(List self, EmptyRange range, Object value) { RangeInfo info = subListBorders(self.size(), range); List sublist = self.subList(info.from, info.to); sublist.clear(); if (value instanceof Collection) { Collection col = (Collection) value; if (col.isEmpty()) return; sublist.addAll(col); } else { sublist.add(value); } } /** * A helper method to allow lists to work with subscript operators. *
      def list = ["a", true]
           * list[1..<1] = [4, 3, 2]
           * assert list == ["a", 4, 3, 2, true]
      * * @param self a List * @param range the (in this case empty) subset of the list to set * @param value the Collection of values * @since 1.0 * @see #putAt(java.util.List, groovy.lang.EmptyRange, java.lang.Object) */ public static void putAt(List self, EmptyRange range, Collection value) { putAt(self, range, (Object)value); } private static List resizeListWithRangeAndGetSublist(List self, IntRange range) { RangeInfo info = subListBorders(self.size(), range); int size = self.size(); if (info.to >= size) { while (size < info.to) { self.add(size++, null); } } List sublist = self.subList(info.from, info.to); sublist.clear(); return sublist; } /** * List subscript assignment operator when given a range as the index and * the assignment operand is a collection. * Example:
      def myList = [4, 3, 5, 1, 2, 8, 10]
           * myList[3..5] = ["a", true]
           * assert myList == [4, 3, 5, "a", true, 10]
      * * Items in the given * range are replaced with items from the collection. * * @param self a List * @param range the subset of the list to set * @param col the collection of values to put at the given sublist * @since 1.5.0 */ public static void putAt(List self, IntRange range, Collection col) { List sublist = resizeListWithRangeAndGetSublist(self, range); if (col.isEmpty()) return; sublist.addAll(col); } /** * List subscript assignment operator when given a range as the index. * Example:
      def myList = [4, 3, 5, 1, 2, 8, 10]
           * myList[3..5] = "b"
           * assert myList == [4, 3, 5, "b", 10]
      * * Items in the given * range are replaced with the operand. The value operand is * always treated as a single value. * * @param self a List * @param range the subset of the list to set * @param value the value to put at the given sublist * @since 1.0 */ public static void putAt(List self, IntRange range, Object value) { List sublist = resizeListWithRangeAndGetSublist(self, range); sublist.add(value); } /** * A helper method to allow lists to work with subscript operators. *
      def list = ["a", true, 42, 9.4]
           * list[1, 4] = ["x", false]
           * assert list == ["a", "x", 42, 9.4, false]
      * * @param self a List * @param splice the subset of the list to set * @param values the value to put at the given sublist * @since 1.0 */ public static void putAt(List self, List splice, List values) { if (splice.isEmpty()) { if ( ! values.isEmpty() ) throw new IllegalArgumentException("Trying to replace 0 elements with "+values.size()+" elements"); return; } Object first = splice.iterator().next(); if (first instanceof Integer) { if (values.size() != splice.size()) throw new IllegalArgumentException("Trying to replace "+splice.size()+" elements with "+values.size()+" elements"); Iterator valuesIter = values.iterator(); for (Object index : splice) { putAt(self, (Integer) index, valuesIter.next()); } } else { throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName()); } } /** * A helper method to allow lists to work with subscript operators. *
      def list = ["a", true, 42, 9.4]
           * list[1, 3] = 5
           * assert list == ["a", 5, 42, 5]
      * * @param self a List * @param splice the subset of the list to set * @param value the value to put at the given sublist * @since 1.0 */ public static void putAt(List self, List splice, Object value) { if (splice.isEmpty()) { return; } Object first = splice.get(0); if (first instanceof Integer) { for (Object index : splice) { self.set((Integer) index, value); } } else { throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName()); } } // helper method for putAt(Splice) // todo: remove after putAt(Splice) gets deleted protected static List getSubList(List self, List splice) { int left /* = 0 */; int right = 0; boolean emptyRange = false; if (splice.size() == 2) { left = DefaultTypeTransformation.intUnbox(splice.get(0)); right = DefaultTypeTransformation.intUnbox(splice.get(1)); } else if (splice instanceof IntRange) { IntRange range = (IntRange) splice; left = range.getFromInt(); right = range.getToInt(); } else if (splice instanceof EmptyRange) { RangeInfo info = subListBorders(self.size(), (EmptyRange) splice); left = info.from; emptyRange = true; } else { throw new IllegalArgumentException("You must specify a list of 2 indexes to create a sub-list"); } int size = self.size(); left = normaliseIndex(left, size); right = normaliseIndex(right, size); List sublist /* = null */; if (!emptyRange) { sublist = self.subList(left, right + 1); } else { sublist = self.subList(left, left); } return sublist; } /** * Support the subscript operator for a Map. *
      def map = [a:10]
           * assert map["a"] == 10
      * * @param self a Map * @param key an Object as a key for the map * @return the value corresponding to the given key * @since 1.0 */ public static V getAt(Map self, K key) { return self.get(key); } /** * Returns a new Map containing all entries from left and right, * giving precedence to right. Any keys appearing in both Maps * will appear in the resultant map with values from the right * operand. If the left map is one of TreeMap, LinkedHashMap, Hashtable * or Properties, the returned Map will preserve that type, otherwise a HashMap will * be returned. *

      *

      * Roughly equivalent to Map m = new HashMap(); m.putAll(left); m.putAll(right); return m; * but with some additional logic to preserve the left Map type for common cases as * described above. *

      *
      assert [a:10, b:20] + [a:5, c:7] == [a:5, b:20, c:7]
      * * @param left a Map * @param right a Map * @return a new Map containing all entries from left and right * @since 1.5.0 */ public static Map plus(Map left, Map right) { Map map = cloneSimilarMap(left); map.putAll(right); return map; } /** * A helper method to allow maps to work with subscript operators * * @param self a Map * @param key an Object as a key for the map * @param value the value to put into the map * @return the value corresponding to the given key * @since 1.0 */ public static V putAt(Map self, K key, V value) { self.put(key, value); return value; } /** * Support the subscript operator for Collection. *
      assert [String, Long, Integer] == ["a",5L,2]["class"]
      * * @param coll a Collection * @param property a String * @return a List * @since 1.0 */ public static List getAt(Collection coll, String property) { List answer = new ArrayList(coll.size()); for (Object item : coll) { if (item == null) continue; Object value; try { value = InvokerHelper.getProperty(item, property); } catch (MissingPropertyExceptionNoStack mpe) { String causeString = new MissingPropertyException(mpe.getProperty(), mpe.getType()).toString(); throw new MissingPropertyException("Exception evaluating property '" + property + "' for " + coll.getClass().getName() + ", Reason: " + causeString); } answer.add(value); } return answer; } /** * A convenience method for creating an immutable map. * * @param self a Map * @return an immutable Map * @see java.util.Collections#unmodifiableMap(java.util.Map) * @since 1.0 */ public static Map asImmutable(Map self) { return Collections.unmodifiableMap(self); } /** * A convenience method for creating an immutable sorted map. * * @param self a SortedMap * @return an immutable SortedMap * @see java.util.Collections#unmodifiableSortedMap(java.util.SortedMap) * @since 1.0 */ public static SortedMap asImmutable(SortedMap self) { return Collections.unmodifiableSortedMap(self); } /** * A convenience method for creating an immutable list * * @param self a List * @return an immutable List * @see java.util.Collections#unmodifiableList(java.util.List) * @since 1.0 */ public static List asImmutable(List self) { return Collections.unmodifiableList(self); } /** * A convenience method for creating an immutable list. * * @param self a Set * @return an immutable Set * @see java.util.Collections#unmodifiableSet(java.util.Set) * @since 1.0 */ public static Set asImmutable(Set self) { return Collections.unmodifiableSet(self); } /** * A convenience method for creating an immutable sorted set. * * @param self a SortedSet * @return an immutable SortedSet * @see java.util.Collections#unmodifiableSortedSet(java.util.SortedSet) * @since 1.0 */ public static SortedSet asImmutable(SortedSet self) { return Collections.unmodifiableSortedSet(self); } /** * A convenience method for creating an immutable Collection. *
      def mutable = [1,2,3]
           * def immutable = mutable.asImmutable()
           * mutable << 4
           * try {
           *   immutable << 4
           *   assert false
           * } catch (UnsupportedOperationException) {
           *   assert true
           * }
      * * @param self a Collection * @return an immutable Collection * @see java.util.Collections#unmodifiableCollection(java.util.Collection) * @since 1.5.0 */ public static Collection asImmutable(Collection self) { return Collections.unmodifiableCollection(self); } /** * A convenience method for creating a synchronized Map. * * @param self a Map * @return a synchronized Map * @see java.util.Collections#synchronizedMap(java.util.Map) * @since 1.0 */ public static Map asSynchronized(Map self) { return Collections.synchronizedMap(self); } /** * A convenience method for creating a synchronized SortedMap. * * @param self a SortedMap * @return a synchronized SortedMap * @see java.util.Collections#synchronizedSortedMap(java.util.SortedMap) * @since 1.0 */ public static SortedMap asSynchronized(SortedMap self) { return Collections.synchronizedSortedMap(self); } /** * A convenience method for creating a synchronized Collection. * * @param self a Collection * @return a synchronized Collection * @see java.util.Collections#synchronizedCollection(java.util.Collection) * @since 1.0 */ public static Collection asSynchronized(Collection self) { return Collections.synchronizedCollection(self); } /** * A convenience method for creating a synchronized List. * * @param self a List * @return a synchronized List * @see java.util.Collections#synchronizedList(java.util.List) * @since 1.0 */ public static List asSynchronized(List self) { return Collections.synchronizedList(self); } /** * A convenience method for creating a synchronized Set. * * @param self a Set * @return a synchronized Set * @see java.util.Collections#synchronizedSet(java.util.Set) * @since 1.0 */ public static Set asSynchronized(Set self) { return Collections.synchronizedSet(self); } /** * A convenience method for creating a synchronized SortedSet. * * @param self a SortedSet * @return a synchronized SortedSet * @see java.util.Collections#synchronizedSortedSet(java.util.SortedSet) * @since 1.0 */ public static SortedSet asSynchronized(SortedSet self) { return Collections.synchronizedSortedSet(self); } /** * Synonym for {@link #toSpreadMap(java.util.Map)}. * @param self a map * @return a newly created SpreadMap * @since 1.0 */ public static SpreadMap spread(Map self) { return toSpreadMap(self); } /** * Returns a new SpreadMap from this map. *

      * The example below shows the various possible use cases: *

           * def fn(Map m) { return m.a + m.b + m.c + m.d }
           *
           * assert fn(a:1, b:2, c:3, d:4) == 10
           * assert fn(a:1, *:[b:2, c:3], d:4) == 10
           * assert fn([a:1, b:2, c:3, d:4].toSpreadMap()) == 10
           * assert fn((['a', 1, 'b', 2, 'c', 3, 'd', 4] as Object[]).toSpreadMap()) == 10
           * assert fn(['a', 1, 'b', 2, 'c', 3, 'd', 4].toSpreadMap()) == 10
           * assert fn(['abcd'.toList(), 1..4].transpose().flatten().toSpreadMap()) == 10
           * 
      * Note that toSpreadMap() is not normally used explicitly but under the covers by Groovy. * * @param self a map to be converted into a SpreadMap * @return a newly created SpreadMap if this map is not null and its size is positive. * @see groovy.lang.SpreadMap#SpreadMap(java.util.Map) * @since 1.0 */ public static SpreadMap toSpreadMap(Map self) { if (self == null) throw new GroovyRuntimeException("Fail to convert Map to SpreadMap, because it is null."); else return new SpreadMap(self); } /** * Creates a spreadable map from this array. *

      * @param self an object array * @return a newly created SpreadMap * @see groovy.lang.SpreadMap#SpreadMap(java.lang.Object[]) * @see #toSpreadMap(java.util.Map) * @since 1.0 */ public static SpreadMap toSpreadMap(Object[] self) { if (self == null) throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it is null."); else if (self.length % 2 != 0) throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it's size is not even."); else return new SpreadMap(self); } /** * Creates a spreadable map from this list. *

      * @param self a list * @return a newly created SpreadMap * @see groovy.lang.SpreadMap#SpreadMap(java.util.List) * @see #toSpreadMap(java.util.Map) * @since 1.8.0 */ public static SpreadMap toSpreadMap(List self) { if (self == null) throw new GroovyRuntimeException("Fail to convert List to SpreadMap, because it is null."); else if (self.size() % 2 != 0) throw new GroovyRuntimeException("Fail to convert List to SpreadMap, because it's size is not even."); else return new SpreadMap(self); } /** * Wraps a map using the delegate pattern with a wrapper that intercepts all calls * to get(key). If an unknown key is found, a default value will be * stored into the Map before being returned. The default value stored will be the * result of calling the supplied Closure with the key as the parameter to the Closure. * Example usage: *

           * def map = [a:1, b:2].withDefault{ k -> k.toCharacter().isLowerCase() ? 10 : -10 }
           * def expected = [a:1, b:2, c:10, D:-10]
           * assert expected.every{ e -> e.value == map[e.key] }
           *
           * def constMap = [:].withDefault{ 42 }
           * assert constMap.foo == 42
           * assert constMap.size() == 1
           * 
      * * @param self a Map * @param init a Closure which is passed the unknown key * @return the wrapped Map * @since 1.7.1 */ public static Map withDefault(Map self, Closure init) { return MapWithDefault.newInstance(self, init); } /** * Sorts the Collection. Assumes that the collection items are comparable * and uses their natural ordering to determine the resulting order. * If the Collection is a List, it is sorted in place and returned. * Otherwise, the elements are first placed into a new list which is then * sorted and returned - leaving the original Collection unchanged. *
      assert [1,2,3] == [3,1,2].sort()
      * * @param self the collection to be sorted * @return the sorted collection as a List * @see #sort(Collection, boolean) * @since 1.0 */ public static List sort(Collection self) { return sort(self, true); } /** * Sorts the Collection. Assumes that the collection items are * comparable and uses their natural ordering to determine the resulting order. * If the Collection is a List and mutate is true, * it is sorted in place and returned. Otherwise, the elements are first placed * into a new list which is then sorted and returned - leaving the original Collection unchanged. *
      assert [1,2,3] == [3,1,2].sort()
      *
           * def orig = [1, 3, 2]
           * def sorted = orig.sort(false)
           * assert orig == [1, 3, 2]
           * assert sorted == [1, 2, 3]
           * 
      * * @param self the collection to be sorted * @param mutate false will always cause a new list to be created, true will mutate lists in place * @return the sorted collection as a List * @since 1.8.1 */ public static List sort(Collection self, boolean mutate) { List answer = mutate ? asList(self) : toList(self); Collections.sort(answer, new NumberAwareComparator()); return answer; } /** * Sorts the elements from the given map into a new ordered map using * the closure as a comparator to determine the ordering. * The original map is unchanged. *
      def map = [a:5, b:3, c:6, d:4].sort { a, b -> a.value <=> b.value }
           * assert map == [b:3, d:4, a:5, c:6]
      * * @param self the original unsorted map * @param closure a Closure used as a comparator * @return the sorted map * @since 1.6.0 */ public static Map sort(Map self, Closure closure) { Map result = new LinkedHashMap(); List> entries = asList(self.entrySet()); sort(entries, closure); for (Map.Entry entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } /** * Sorts the elements from the given map into a new ordered Map using * the specified key comparator to determine the ordering. * The original map is unchanged. *
      def map = [ba:3, cz:6, ab:5].sort({ a, b -> a[-1] <=> b[-1] } as Comparator)
           * assert map*.value == [3, 5, 6]
      * * @param self the original unsorted map * @param comparator a Comparator * @return the sorted map * @since 1.7.2 */ public static Map sort(Map self, Comparator comparator) { Map result = new TreeMap(comparator); result.putAll(self); return result; } /** * Sorts the elements from the given map into a new ordered Map using * the natural ordering of the keys to determine the ordering. * The original map is unchanged. *
      map = [ba:3, cz:6, ab:5].sort()
           * assert map*.value == [5, 3, 6]
           * 
      * * @param self the original unsorted map * @return the sorted map * @since 1.7.2 */ public static Map sort(Map self) { return new TreeMap(self); } /** * Modifies this array so that its elements are in sorted order. * The array items are assumed to be comparable. * * @param self the array to be sorted * @return the sorted array * @since 1.5.5 */ public static T[] sort(T[] self) { Arrays.sort(self, new NumberAwareComparator()); return self; } /** * Sorts the given array into sorted order. * The array items are assumed to be comparable. * If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted * array is returned and the original array remains unchanged. *
           * def orig = ["hello","hi","Hey"] as String[]
           * def sorted = orig.sort(false)
           * assert orig == ["hello","hi","Hey"] as String[]
           * assert sorted == ["Hey","hello","hi"] as String[]
           * orig.sort(true)
           * assert orig == ["Hey","hello","hi"] as String[]
           * 
      * * @param self the array to be sorted * @param mutate false will always cause a new array to be created, true will mutate the array in place * @return the sorted array * @since 1.8.1 */ public static T[] sort(T[] self, boolean mutate) { T[] answer = mutate ? self : self.clone(); Arrays.sort(answer, new NumberAwareComparator()); return answer; } /** * Sorts the given iterator items into a sorted iterator. The items are * assumed to be comparable. The original iterator will become * exhausted of elements after completing this method call. * A new iterator is produced that traverses the items in sorted order. * * @param self the Iterator to be sorted * @return the sorted items as an Iterator * @since 1.5.5 */ public static Iterator sort(Iterator self) { return sort(toList(self)).listIterator(); } /** * Sorts the given iterator items into a sorted iterator using the comparator. The * original iterator will become exhausted of elements after completing this method call. * A new iterator is produced that traverses the items in sorted order. * * @param self the Iterator to be sorted * @param comparator a Comparator used for comparing items * @return the sorted items as an Iterator * @since 1.5.5 */ public static Iterator sort(Iterator self, Comparator comparator) { return sort(toList(self), comparator).listIterator(); } /** * Sorts the Collection using the given Comparator. If the Collection is a List, * it is sorted in place and returned. Otherwise, the elements are first placed * into a new list which is then sorted and returned - leaving the original Collection unchanged. *
           * assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
           * 
      *
           * assert ["hello","Hey","hi"] == ["hello","hi","Hey"].sort(String.CASE_INSENSITIVE_ORDER)
           * 
      * * @param self a collection to be sorted * @param comparator a Comparator used for the comparison * @return a sorted List * @see #sort(Collection, boolean, Comparator) * @since 1.0 */ public static List sort(Collection self, Comparator comparator) { return sort(self, true, comparator); } /** * Sorts the Collection using the given Comparator. If the Collection is a List and mutate * is true, it is sorted in place and returned. Otherwise, the elements are first placed * into a new list which is then sorted and returned - leaving the original Collection unchanged. *
           * assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
           * 
      *
           * def orig = ["hello","hi","Hey"]
           * def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER)
           * assert orig == ["hello","hi","Hey"]
           * assert sorted == ["hello","Hey","hi"]
           * 
      * * @param self a collection to be sorted * @param mutate false will always cause a new list to be created, true will mutate lists in place * @param comparator a Comparator used for the comparison * @return a sorted List * @since 1.8.1 */ public static List sort(Collection self, boolean mutate, Comparator comparator) { List list = mutate ? asList(self) : toList(self); Collections.sort(list, comparator); return list; } /** * Sorts the given array into sorted order using the given comparator. * * @param self the array to be sorted * @param comparator a Comparator used for the comparison * @return the sorted array * @since 1.5.5 */ public static T[] sort(T[] self, Comparator comparator) { return sort(self, true, comparator); } /** * Modifies this array so that its elements are in sorted order as determined by the given comparator. * If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted * array is returned and the original array remains unchanged. *
           * def orig = ["hello","hi","Hey"] as String[]
           * def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER)
           * assert orig == ["hello","hi","Hey"] as String[]
           * assert sorted == ["hello","Hey","hi"] as String[]
           * orig.sort(true, String.CASE_INSENSITIVE_ORDER)
           * assert orig == ["hello","Hey","hi"] as String[]
           * 
      * * @param self the array containing elements to be sorted * @param mutate false will always cause a new array to be created, true will mutate arrays in place * @param comparator a Comparator used for the comparison * @return a sorted array * @since 1.8.1 */ public static T[] sort(T[] self, boolean mutate, Comparator comparator) { T[] answer = mutate ? self : self.clone(); Arrays.sort(answer, comparator); return answer; } /** * Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering. * The original iterator will be fully processed after the method call. *

      * If the closure has two parameters it is used like a traditional Comparator. * I.e. it should compare its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, equal to, * or greater than the second respectively. Otherwise, the Closure is assumed * to take a single parameter and return a Comparable (typically an Integer) * which is then used for further comparison. * * @param self the Iterator to be sorted * @param closure a Closure used to determine the correct ordering * @return the sorted items as an Iterator * @since 1.5.5 */ public static Iterator sort(Iterator self, Closure closure) { return sort(toList(self), closure).listIterator(); } /** * Sorts the elements from this array into a newly created array using * the Closure to determine the correct ordering. *

      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, zero, or a positive integer when the * first parameter is less than, equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) * which is then used for further comparison. * * @param self the array containing the elements to be sorted * @param closure a Closure used to determine the correct ordering * @return the sorted array * @since 1.5.5 */ @SuppressWarnings("unchecked") public static T[] sort(T[] self, Closure closure) { return sort(self, false, closure); } /** * Modifies this array so that its elements are in sorted order using the Closure to determine the correct ordering. * If mutate is false, a new array is returned and the original array remains unchanged. * Otherwise, the original array is sorted in place and returned. *

      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, zero, or a positive integer when the * first parameter is less than, equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) * which is then used for further comparison. *
           * def orig = ["hello","hi","Hey"] as String[]
           * def sorted = orig.sort(false) { it.size() }
           * assert orig == ["hello","hi","Hey"] as String[]
           * assert sorted == ["hi","Hey","hello"] as String[]
           * orig.sort(true) { it.size() }
           * assert orig == ["hi","Hey","hello"] as String[]
           * 
      * * @param self the array to be sorted * @param mutate false will always cause a new array to be created, true will mutate arrays in place * @param closure a Closure used to determine the correct ordering * @return the sorted array * @since 1.8.1 */ @SuppressWarnings("unchecked") public static T[] sort(T[] self, boolean mutate, Closure closure) { T[] answer = (T[]) sort(toList(self), closure).toArray(); if (mutate) { System.arraycopy(answer, 0, self, 0, answer.length); } return mutate ? self : answer; } /** * Sorts this Collection using the given Closure to determine the correct ordering. If the Collection is a List, * it is sorted in place and returned. Otherwise, the elements are first placed * into a new list which is then sorted and returned - leaving the original Collection unchanged. *

      * If the Closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. *
      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
      *
      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
      * * @param self a Collection to be sorted * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return a newly created sorted List * @see #sort(Collection, boolean, Closure) * @since 1.0 */ public static List sort(Collection self, Closure closure) { return sort(self, true, closure); } /** * Sorts this Collection using the given Closure to determine the correct ordering. If the Collection is a List * and mutate is true, it is sorted in place and returned. Otherwise, the elements are first placed * into a new list which is then sorted and returned - leaving the original Collection unchanged. *

      * If the closure has two parameters * it is used like a traditional Comparator. I.e. it should compare * its two parameters for order, returning a negative integer, * zero, or a positive integer when the first parameter is less than, * equal to, or greater than the second respectively. Otherwise, * the Closure is assumed to take a single parameter and return a * Comparable (typically an Integer) which is then used for * further comparison. *
      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
      *
      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
      *
           * def orig = ["hello","hi","Hey"]
           * def sorted = orig.sort(false) { it.toUpperCase() }
           * assert orig == ["hello","hi","Hey"]
           * assert sorted == ["hello","Hey","hi"]
           * 
      * * @param self a Collection to be sorted * @param mutate false will always cause a new list to be created, true will mutate lists in place * @param closure a 1 or 2 arg Closure used to determine the correct ordering * @return a newly created sorted List * @since 1.8.1 */ public static List sort(Collection self, boolean mutate, Closure closure) { List list = mutate ? asList(self) : toList(self); // use a comparator of one item or two int params = closure.getMaximumNumberOfParameters(); if (params == 1) { Collections.sort(list, new OrderBy(closure)); } else { Collections.sort(list, new ClosureComparator(closure)); } return list; } /** * Avoids doing unnecessary work when sorting an already sorted set (i.e. an identity function for an already sorted set). * * @param self an already sorted set * @return the set * @since 1.0 */ public static SortedSet sort(SortedSet self) { return self; } /** * Avoids doing unnecessary work when sorting an already sorted map (i.e. an identity function for an already sorted map). * * @param self an already sorted map * @return the map * @since 1.8.1 */ public static SortedMap sort(SortedMap self) { return self; } /** * Removes the last item from the List. Using add() and pop() * is similar to push and pop on a Stack. *
      def list = ["a", false, 2]
           * assert list.pop() == 2
           * assert list == ["a", false]
      * * @param self a List * @return the item removed from the List * @throws NoSuchElementException if the list is empty and you try to pop() it. * @since 1.0 */ public static T pop(List self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot pop() an empty List"); } return self.remove(self.size() - 1); } /** * Provides an easy way to append multiple Map.Entry values to a Map. * * @param self a Map * @param entries a Collection of Map.Entry items to be added to the Map. * @return the same map, after the items have been added to it. * @since 1.6.1 */ public static Map putAll(Map self, Collection> entries) { for (Map.Entry entry : entries) { self.put(entry.getKey(), entry.getValue()); } return self; } /** * Returns a new Map containing all entries from self and entries, * giving precedence to entries. Any keys appearing in both Maps * will appear in the resultant map with values from the entries * operand. If self map is one of TreeMap, LinkedHashMap, Hashtable * or Properties, the returned Map will preserve that type, otherwise a HashMap will * be returned. *

      * * @param self a Map * @param entries a Collection of Map.Entry items to be added to the Map. * @return a new Map containing all key, value pairs from self and entries * @since 1.6.1 */ public static Map plus(Map self, Collection> entries) { Map map = cloneSimilarMap(self); putAll(map, entries); return map; } /** * Appends an item to the List. Synonym for add(). *
      def list = [3, 4, 2]
           * list.push("x")
           * assert list == [3, 4, 2, "x"]
      * * @param self a List * @param value element to be appended to this list. * @return true (as per the general contract of the * Collection.add method). * @throws NoSuchElementException if the list is empty and you try to pop() it. * @since 1.5.5 */ public static boolean push(List self, T value) { return self.add(value); } /** * Returns the last item from the List. *
      def list = [3, 4, 2]
           * assert list.last() == 2
           * assert list == [3, 4, 2]
      * * @param self a List * @return the last item from the List * @throws NoSuchElementException if the list is empty and you try to access the last() item. * @since 1.5.5 */ public static T last(List self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot access last() element from an empty List"); } return self.get(self.size() - 1); } /** * Returns the last item from the Object array. *
      def array = [3, 4, 2].toArray()
           * assert array.last() == 2
      * * @param self an ObjectArray * @return the last item from the Object array * @throws NoSuchElementException if the array is empty and you try to access the last() item. * @since 1.7.3 */ public static T last(T[] self) { if (self.length == 0) { throw new NoSuchElementException("Cannot access last() element from an empty Array"); } return self[self.length - 1]; } /** * Returns the first item from the List. *
      def list = [3, 4, 2]
           * assert list.first() == 3
           * assert list == [3, 4, 2]
      * * @param self a List * @return the first item from the List * @throws NoSuchElementException if the list is empty and you try to access the first() item. * @since 1.5.5 */ public static T first(List self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot access first() element from an empty List"); } return self.get(0); } /** * Returns the first item from the Object array. *
      def array = [3, 4, 2].toArray()
           * assert array.first() == 3
      * * @param self an Object array * @return the first item from the Object array * @throws NoSuchElementException if the array is empty and you try to access the first() item. * @since 1.7.3 */ public static T first(T[] self) { if (self.length == 0) { throw new NoSuchElementException("Cannot access first() element from an empty List"); } return self[0]; } /** * Returns the first item from the List. *
      def list = [3, 4, 2]
           * assert list.head() == 3
           * assert list == [3, 4, 2]
      * * @param self a List * @return the first item from the List * @throws NoSuchElementException if the list is empty and you try to access the head() item. * @since 1.5.5 */ public static T head(List self) { return first(self); } /** * Returns the first item from the Object array. *
      def array = [3, 4, 2].toArray()
           * assert array.head() == 3
      * * @param self an Object array * @return the first item from the Object array * @throws NoSuchElementException if the array is empty and you try to access the head() item. * @since 1.7.3 */ public static T head(T[] self) { return first(self); } /** * Returns the items from the List excluding the first item. *
      def list = [3, 4, 2]
           * assert list.tail() == [4, 2]
           * assert list == [3, 4, 2]
      * * @param self a List * @return a list without its first element * @throws NoSuchElementException if the list is empty and you try to access the tail() item. * @since 1.5.6 */ public static List tail(List self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot access tail() for an empty List"); } List result = new ArrayList(self); result.remove(0); return result; } /** * Returns the items from the Object array excluding the first item. *
           *     String[] strings = ["a", "b", "c"]
           *     def result = strings.tail()
           *     assert strings.class.componentType == String
           * 
      * * @param self an Object array * @return an Object array without its first element * @throws NoSuchElementException if the list is empty and you try to access the tail() item. * @since 1.7.3 */ public static T[] tail(T[] self) { if (self.length == 0) { throw new NoSuchElementException("Cannot access tail() for an empty Object array"); } Class componentType = (Class) self.getClass().getComponentType(); T[] result = (T[]) Array.newInstance(componentType, self.length - 1); System.arraycopy(self, 1, result, 0, self.length - 1); return result; } /** * Returns the first num elements from the head of this list. *
           *     def strings = [ 'a', 'b', 'c' ]
           *     assert strings.take( 0 ) == []
           *     assert strings.take( 2 ) == [ 'a', 'b' ]
           *     assert strings.take( 5 ) == [ 'a', 'b', 'c' ]
           * 
      * * @param self the original list * @param num the number of elements to take from this list * @return a list consisting of the first num elements of this list, * or else the whole list if it has less then num elements. * @since 1.8.1 */ public static List take( List self, int num ) { if( self.isEmpty() || num <= 0 ) { return createSimilarList( self, 0 ) ; } if( self.size() <= num ) { List ret = createSimilarList( self, self.size() ) ; ret.addAll( self ) ; return ret ; } List ret = createSimilarList( self, num ) ; ret.addAll( self.subList( 0, num ) ) ; return ret ; } /** * Returns the first num elements from the head of this array. *
           *     String[] strings = [ 'a', 'b', 'c' ]
           *     assert strings.take( 0 ) == [] as String[]
           *     assert strings.take( 2 ) == [ 'a', 'b' ] as String[]
           *     assert strings.take( 5 ) == [ 'a', 'b', 'c' ] as String[]
           * 
      * * @param self the original array * @param num the number of elements to take from this array * @return an array consisting of the first num elements of this array, * or else the whole array if it has less then num elements. * @since 1.8.1 */ public static T[] take( T[] self, int num ) { Class componentType = (Class) self.getClass().getComponentType(); if( self.length == 0 || num <= 0 ) { return (T[]) Array.newInstance(componentType, 0); } if( self.length <= num ) { T[] ret = (T[]) Array.newInstance(componentType, self.length); System.arraycopy(self, 0, ret, 0, self.length); return ret; } T[] ret = (T[]) Array.newInstance(componentType, num); System.arraycopy(self, 0, ret, 0, num); return ret; } /** * Returns a new map containing the first num elements from the head of this map. * If the map instance does not have ordered keys, then this function could return a random num * entries. Groovy by default used LinkedHashMap, so this shouldn't be an issue in the main. *
           *     def strings = [ 'a':10, 'b':20, 'c':30 ]
           *     assert strings.take( 0 ) == [:]
           *     assert strings.take( 2 ) == [ 'a':10, 'b':20 ]
           *     assert strings.take( 5 ) == [ 'a':10, 'b':20, 'c':30 ]
           * 
      * * @param self the original map * @param num the number of elements to take from this map * @return a new map consisting of the first num elements of this map, * or else the whole map if it has less then num elements. * @since 1.8.1 */ public static Map take( Map self, int num ) { if( self.isEmpty() || num <= 0 ) { return createSimilarMap( self ) ; } Map ret = createSimilarMap( self ) ; for( K key : self.keySet() ) { ret.put( key, self.get( key ) ) ; if( --num <= 0 ) { break ; } } return ret ; } /** * Returns an iterator to up to the first num elements from this iterator. * The original iterator is stepped along by num elements. *
           *     def a = 0
           *     def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator
           *
           *     def iteratorCompare( Iterator a, List b ) {
           *       a.collect { it } == b
           *     }
           *     assert iteratorCompare( iter.take( 0 ), [] )
           *     assert iteratorCompare( iter.take( 2 ), [ 0, 1 ] )
           *     assert iteratorCompare( iter.take( 5 ), [ 2, 3, 4, 5, 6 ] )
           * 
      * * @param self the Iterator * @param num the number of elements to take from this iterator * @return a list consisting of up to the first num elements of this iterator. * @since 1.8.1 */ public static Iterator take( Iterator self, int num ) { List ret = new ArrayList() ; while( num-- > 0 && self.hasNext() ) { ret.add( self.next() ) ; } return ret.listIterator() ; } /** * Returns the first num elements from this CharSequence. *
           *     def text = "Groovy"
           *     assert text.take( 0 ) == ''
           *     assert text.take( 2 ) == 'Gr'
           *     assert text.take( 7 ) == 'Groovy'
           * 
      * * @param self the original CharSequence * @param num the number of chars to take from this CharSequence * @return a CharSequence consisting of the first num chars, * or else the whole CharSequence if it has less then num elements. * @since 1.8.1 */ public static CharSequence take( CharSequence self, int num ) { if( num < 0 ) { return self.subSequence( 0, 0 ) ; } if( self.length() <= num ) { return self ; } return self.subSequence( 0, num ) ; } /** * Drops the given number of elements from the head of this list * if they are available. *
           *     def strings = [ 'a', 'b', 'c' ]
           *     assert strings.drop( 0 ) == [ 'a', 'b', 'c' ]
           *     assert strings.drop( 2 ) == [ 'c' ]
           *     assert strings.drop( 5 ) == []
           * 
      * * @param self the original list * @param num the number of elements to drop from this list * @return a list consisting of all elements of this list except the first * num ones, or else the empty list, if this list has * less than num elements. * @since 1.8.1 */ public static List drop(List self, int num) { if (self.size() <= num) { return createSimilarList( self, 0 ) ; } if (num <= 0) { List ret = createSimilarList( self, self.size() ) ; ret.addAll( self ) ; return ret ; } List ret = createSimilarList( self, self.size() - num ) ; ret.addAll(self.subList(num, self.size())) ; return ret ; } /** * Drops the given number of elements from the head of this array * if they are available. *
           *     String[] strings = [ 'a', 'b', 'c' ]
           *     assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] as String[]
           *     assert strings.drop( 2 ) == [ 'c' ] as String[]
           *     assert strings.drop( 5 ) == [] as String[]
           * 
      * * @param self the original array * @param num the number of elements to drop from this array * @return an array consisting of all elements of this array except the * first num ones, or else the empty array, if this * array has less than num elements. * @since 1.8.1 */ public static T[] drop(T[] self, int num) { Class componentType = (Class) self.getClass().getComponentType(); if (self.length <= num) { return (T[]) Array.newInstance(componentType, 0); } if (num <= 0) { T[] ret = (T[]) Array.newInstance(componentType, self.length); System.arraycopy(self, 0, ret, 0, self.length); return ret; } T[] ret = (T[]) Array.newInstance(componentType, self.length - num); System.arraycopy(self, num, ret, 0, self.length - num); return ret; } /** * Drops the given number of key/value pairs from the head of this map if they are available. * If the map instance does not have ordered keys, then this function could drop a random num * entries. Groovy by default used LinkedHashMap, so this shouldn't be an issue in the main. *
           *     def strings = [ 'a':10, 'b':20, 'c':30 ]
           *     assert strings.drop( 0 ) == [ 'a':10, 'b':20, 'c':30 ]
           *     assert strings.drop( 2 ) == [ 'c':30 ]
           *     assert strings.drop( 5 ) == [:]
           * 
      * * @param self the original map * @param num the number of elements to drop from this map * @return a map consisting of all key/value pairs of this map except the first * num ones, or else the empty map, if this map has * less than num elements. * @since 1.8.1 */ public static Map drop( Map self, int num ) { if( self.size() <= num ) { return createSimilarMap( self ) ; } if( num == 0 ) { return cloneSimilarMap( self ) ; } Map ret = createSimilarMap( self ) ; for( K key : self.keySet() ) { if( num-- <= 0 ) { ret.put( key, self.get( key ) ) ; } } return ret ; } /** * Drops the given number of elements from the head of this iterator if they are available. * The original iterator is stepped along by num elements. *
           *     def iteratorCompare( Iterator a, List b ) {
           *       a.collect { it } == b
           *     }
           *     def iter = [ 1, 2, 3, 4, 5 ].listIterator()
           *     assert iteratorCompare( iter.drop( 0 ), [ 1, 2, 3, 4, 5 ] )
           *     iter = [ 1, 2, 3, 4, 5 ].listIterator()
           *     assert iteratorCompare( iter.drop( 2 ), [ 3, 4, 5 ] )
           *     iter = [ 1, 2, 3, 4, 5 ].listIterator()
           *     assert iteratorCompare( iter.drop( 5 ), [] )
           * 
      * * @param self the original iterator * @param num the number of elements to drop from this iterator * @return The iterator stepped along by num elements if they exist. * @since 1.8.1 */ public static Iterator drop(Iterator self, int num) { while (num-- > 0 && self.hasNext()) { self.next(); } return self ; } /** * Drops the given number of chars from the head of this CharSequence * if they are available. *
           *     def text = "Groovy"
           *     assert text.drop( 0 ) == 'Groovy'
           *     assert text.drop( 2 ) == 'oovy'
           *     assert text.drop( 7 ) == ''
           * 
      * * @param self the original CharSequence * @param num the number of characters to drop from this iterator * @return a CharSequence consisting of all characters except the first num ones, * or else an empty String, if this CharSequence has less than num characters. * @since 1.8.1 */ public static CharSequence drop(CharSequence self, int num) { if( num <= 0 ) { return self ; } if( self.length() <= num ) { return self.subSequence( 0, 0 ) ; } return self.subSequence( num, self.length() ) ; } /** * Converts this Collection to a List. Returns the original Collection * if it is already a List. *

      * Example usage: *

      assert new HashSet().asList() instanceof List
      * * @param self a collection to be converted into a List * @return a newly created List if this collection is not already a List * @since 1.0 */ public static List asList(Collection self) { if (self instanceof List) { return (List) self; } else { return toList(self); } } /** * Coerce an object instance to a boolean value. * An object is coerced to true if it's not null, to false if it is null. * * @param object the object to coerce * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Object object) { return object != null; } /** * Coerce an Boolean instance to a boolean value. * * @param bool the Boolean * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Boolean bool) { return bool; } /** * Coerce a Matcher instance to a boolean value. * * @param matcher the matcher * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Matcher matcher) { RegexSupport.setLastMatcher(matcher); return matcher.find(); } /** * Coerce a collection instance to a boolean value. * A collection is coerced to false if it's empty, and to true otherwise. *
      assert [1,2].asBoolean() == true
      *
      assert [].asBoolean() == false
      * * @param collection the collection * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Collection collection) { return !collection.isEmpty(); } /** * Coerce a map instance to a boolean value. * A map is coerced to false if it's empty, and to true otherwise. *
      assert [:] as Boolean == false
           * assert [a:2] as Boolean == true
      * * @param map the map * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Map map) { return !map.isEmpty(); } /** * Coerce an iterator instance to a boolean value. * An iterator is coerced to false if there are no more elements to iterate over, * and to true otherwise. * * @param iterator the iterator * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Iterator iterator) { return iterator.hasNext(); } /** * Coerce an enumeration instance to a boolean value. * An enumeration is coerced to false if there are no more elements to enumerate, * and to true otherwise. * * @param enumeration the enumeration * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Enumeration enumeration) { return enumeration.hasMoreElements(); } /** * Coerce a string (an instance of CharSequence) to a boolean value. * A string is coerced to false if it is of length 0, * and to true otherwise. * * @param string the character sequence * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(CharSequence string) { return string.length() > 0; } /** * Coerce an Object array to a boolean value. * An Object array is false if the array is of length 0. * and to true otherwise * * @param array the array * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Object[] array) { return array.length > 0; } /** * Coerces a byte array to a boolean value. * A byte array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(byte[] array) { return array.length > 0; } /** * Coerces a short array to a boolean value. * A short array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(short[] array) { return array.length > 0; } /** * Coerces an int array to a boolean value. * An int array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(int[] array) { return array.length > 0; } /** * Coerces a long array to a boolean value. * A long array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(long[] array) { return array.length > 0; } /** * Coerces a float array to a boolean value. * A float array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(float[] array) { return array.length > 0; } /** * Coerces a double array to a boolean value. * A double array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(double[] array) { return array.length > 0; } /** * Coerces a boolean array to a boolean value. * A boolean array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(boolean[] array) { return array.length > 0; } /** * Coerces a char array to a boolean value. * A char array is false if the array is of length 0, * and true otherwise. * * @param array an array * @return the array's boolean value * @since 1.7.4 */ public static boolean asBoolean(char[] array) { return array.length > 0; } /** * Coerce a character to a boolean value. * A character is coerced to false if it's character value is equal to 0, * and to true otherwise. * * @param character the character * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Character character) { return character != 0; } /** * Coerce a number to a boolean value. * A number is coerced to false if its double value is equal to 0, and to true otherwise, * and to true otherwise. * * @param number the number * @return the boolean value * @since 1.7.0 */ public static boolean asBoolean(Number number) { return number.doubleValue() != 0; } /** * Converts the given collection to another type. A default concrete * type is used for List, Set, or SortedSet. If the given type has * a constructor taking a collection, that is used. Otherwise, the * call is deferred to {link #asType(Object,Class)}. If this * collection is already of the given type, the same instance is * returned. * * @param col a collection * @param clazz the desired class * @return the object resulting from this type conversion * @see #asType(java.lang.Object, java.lang.Class) * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(Collection col, Class clazz) { if (col.getClass() == clazz) { return (T) col; } if (clazz == List.class) { return (T) asList(col); } if (clazz == Set.class) { if (col instanceof Set) return (T) col; return (T) new LinkedHashSet(col); } if (clazz == SortedSet.class) { if (col instanceof SortedSet) return (T) col; return (T) new TreeSet(col); } if (clazz == Queue.class) { if (col instanceof Queue) return (T) col; return (T) new LinkedList(col); } if (clazz == Stack.class) { if (col instanceof Stack) return (T) col; final Stack stack = new Stack(); stack.addAll(col); return (T) stack; } if (clazz!=String[].class && ReflectionCache.isArray(clazz)) { try { return (T) asArrayType(col, clazz); } catch (GroovyCastException e) { /* ignore */ } } Object[] args = {col}; try { return (T) InvokerHelper.invokeConstructorOf(clazz, args); } catch (Exception e) { // ignore, the constructor that takes a Collection as an argument may not exist } if (Collection.class.isAssignableFrom(clazz)) { try { Collection result = (Collection) InvokerHelper.invokeConstructorOf(clazz, null); result.addAll(col); return (T)result; } catch (Exception e) { // ignore, the no arg constructor might not exist. } } return asType((Object) col, clazz); } /** * Converts the given array to either a List, Set, or * SortedSet. If the given class is something else, the * call is deferred to {link #asType(Object,Class)}. * * @param ary an array * @param clazz the desired class * @return the object resulting from this type conversion * @see #asType(java.lang.Object, java.lang.Class) * @since 1.5.1 */ @SuppressWarnings("unchecked") public static T asType(Object[] ary, Class clazz) { if (clazz == List.class) { return (T) new ArrayList(Arrays.asList(ary)); } if (clazz == Set.class) { return (T) new HashSet(Arrays.asList(ary)); } if (clazz == SortedSet.class) { return (T) new TreeSet(Arrays.asList(ary)); } return asType((Object) ary, clazz); } /** * Coerces the closure to an implementation of the given class. The class * is assumed to be an interface or class with a single method definition. * The closure is used as the implementation of that single method. * * @param cl the implementation of the single method * @param clazz the target type * @return a Proxy of the given type which wraps this closure. * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(Closure cl, Class clazz) { if (clazz.isInterface() && !(clazz.isInstance(cl))) { return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{clazz}, new ConvertedClosure(cl)); } try { return asType((Object) cl, clazz); } catch (GroovyCastException ce) { try { return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(cl, clazz); } catch (GroovyRuntimeException cause) { throw new GroovyCastException("Error casting closure to " + clazz.getName() + ", Reason: " + cause.getMessage()); } } } /** * Coerces this map to the given type, using the map's keys as the public * method names, and values as the implementation. Typically the value * would be a closure which behaves like the method implementation. * * @param map this map * @param clazz the target type * @return a Proxy of the given type, which defers calls to this map's elements. * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(Map map, Class clazz) { if (!(clazz.isInstance(map)) && clazz.isInterface()) { return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{clazz}, new ConvertedMap(map)); } try { return asType((Object) map, clazz); } catch (GroovyCastException ce) { try { return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(map, clazz); } catch (GroovyRuntimeException cause) { throw new GroovyCastException("Error casting map to " + clazz.getName() + ", Reason: " + cause.getMessage()); } } } /** * Creates a new List with the identical contents to this list * but in reverse order. *
           * def list = ["a", 4, false]
           * assert list.reverse() == [false, 4, "a"]
           * assert list == ["a", 4, false]
           * 
      * * @param self a List * @return a reversed List * @see #reverse(List, boolean) * @since 1.0 */ public static List reverse(List self) { return reverse(self, false); } /** * Reverses the elements in a list. If mutate is true, the original list is modified in place and returned. * Otherwise, a new list containing the reversed items is produced. *
           * def list = ["a", 4, false]
           * assert list.reverse(false) == [false, 4, "a"]
           * assert list == ["a", 4, false]
           * assert list.reverse(true) == [false, 4, "a"]
           * assert list == [false, 4, "a"]
           * 
      * * @param self a List * @param mutate true if the list itself should be reversed in place and returned, false if a new list should be created * @return a reversed List * @since 1.8.1 */ public static List reverse(List self, boolean mutate) { if (mutate) { Collections.reverse(self); return self; } int size = self.size(); List answer = new ArrayList(size); ListIterator iter = self.listIterator(size); while (iter.hasPrevious()) { answer.add(iter.previous()); } return answer; } /** * Creates a new array containing items which are the same as this array but in reverse order. * * @param self an array * @return an array containing the reversed items * @see #reverse(Object[], boolean) * @since 1.5.5 */ @SuppressWarnings("unchecked") public static T[] reverse(T[] self) { return reverse(self, false); } /** * Reverse the items in an array. If mutate is true, the original array is modified in place and returned. * Otherwise, a new array containing the reversed items is produced. * * @param self an array * @param mutate true if the array itself should be reversed in place and returned, false if a new array should be created * @return an array containing the reversed items * @since 1.8.1 */ @SuppressWarnings("unchecked") public static T[] reverse(T[] self, boolean mutate) { if (!mutate) { return (T[]) toList(new ReverseListIterator(Arrays.asList(self))).toArray(); } List items = Arrays.asList(self); Collections.reverse(items); System.arraycopy((T[])items.toArray(), 0, self, 0, items.size()); return self; } /** * Reverses the iterator. The original iterator will become * exhausted of elements after determining the reversed values. * A new iterator for iterating through the reversed values is returned. * * @param self an Iterator * @return a reversed Iterator * @since 1.5.5 */ public static Iterator reverse(Iterator self) { return new ReverseListIterator(toList(self)); } /** * Create a Collection as a union of two collections. If the left collection * is a Set, then the returned collection will be a Set otherwise a List. * This operation will always create a new object for the result, * while the operands remain unchanged. *
      assert [1,2,3,4] == [1,2] + [3,4]
      * * @param left the left Collection * @param right the right Collection * @return the merged Collection * @since 1.5.0 */ public static Collection plus(Collection left, Collection right) { final Collection answer = cloneSimilarCollection(left, left.size() + right.size()); answer.addAll(right); return answer; } /** * Creates a new list by adding all of the elements in the specified array to the elements from the original list at the specified index. * Shifts the element currently at that index (if any) and any subsequent * elements to the right (increasing their indices). The new elements * will appear in this list in the order that they occur in the array. * The behavior of this operation is undefined if the specified array * is modified while the operation is in progress. The original list remains unchanged. * *
           * def items = [1, 2, 3]
           * def newItems = items.plus(2, 'a'..'c' as String[])
           * assert newItems == [1, 2, 'a', 'b', 'c', 3]
           * assert items == [1, 2, 3]
           * 
      * * See also addAll for similar functionality with modify semantics, i.e. which performs * the changes on the original list itself. * * @param self an original list * @param items array containing elements to be merged with elements from the original list * @param index index at which to insert the first element from the specified array * @return the new list * @see #plus(List, int, List) * @since 1.8.1 */ public static List plus(List self, int index, T[] items) { return plus(self, index, Arrays.asList(items)); } /** * Creates a new list by adding all of the elements in the specified list * to the elements from this list at the specified index. * Shifts the element currently at that index (if any) and any subsequent * elements to the right (increasing their indices). The new elements * will appear in this list in the order that they occur in the array. * The behavior of this operation is undefined if the specified array * is modified while the operation is in progress. The original list remains unchanged. * *
           * def items = [1, 2, 3]
           * def newItems = items.plus(2, 'a'..'c')
           * assert newItems == [1, 2, 'a', 'b', 'c', 3]
           * assert items == [1, 2, 3]
           * 
      * * See also addAll for similar functionality with modify semantics, i.e. which performs * the changes on the original list itself. * * @param self an original list * @param additions array containing elements to be merged with elements from the original list * @param index index at which to insert the first element from the specified list * @return the new list * @since 1.8.1 */ public static List plus(List self, int index, List additions) { final List answer = new ArrayList(self); answer.addAll(index, additions); return answer; } /** * Create a collection as a union of a Collection and an Object. If the collection * is a Set, then the returned collection will be a Set otherwise a List. * This operation will always create a new object for the result, * while the operands remain unchanged. *
      assert [1,2,3] == [1,2] + 3
      * * @param left a Collection * @param right an object to add/append * @return the resulting Collection * @since 1.5.0 */ public static Collection plus(Collection left, T right) { final Collection answer = cloneSimilarCollection(left, left.size() + 1); answer.add(right); return answer; } /** * Create a List composed of the elements of this list, repeated * a certain number of times. Note that for non-primitive * elements, multiple references to the same instance will be added. *
      assert [1,2,3,1,2,3] == [1,2,3] * 2
      * * @param self a Collection * @param factor the number of times to append * @return the multiplied list * @since 1.0 */ public static List multiply(Collection self, Number factor) { int size = factor.intValue(); List answer = new ArrayList(self.size() * size); for (int i = 0; i < size; i++) { answer.addAll(self); } return answer; } /** * Create a Collection composed of the intersection of both collections. Any * elements that exist in both collections are added to the resultant collection. *
      assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])
      * * @param left a Collection * @param right a Collection * @return a Collection as an intersection of both collections * @since 1.5.6 */ public static Collection intersect(Collection left, Collection right) { if (left.isEmpty()) return createSimilarCollection(left, 0); if (left.size() < right.size()) { Collection swaptemp = left; left = right; right = swaptemp; } // TODO optimise if same type? // boolean nlgnSort = sameType(new Collection[]{left, right}); Collection result = createSimilarCollection(left, left.size()); //creates the collection to look for values. Collection pickFrom = new TreeSet(new NumberAwareComparator()); pickFrom.addAll(left); for (final T t : right) { if (pickFrom.contains(t)) result.add(t); } return result; } /** * Create a Map composed of the intersection of both maps. * Any entries that exist in both maps are added to the resultant map. *
      assert [4:4,5:5] == [1:1,2:2,3:3,4:4,5:5].intersect([4:4,5:5,6:6,7:7,8:8])
      *
      assert [1: 1, 2: 2, 3: 3, 4: 4].intersect( [1: 1.0, 2: 2, 5: 5] ) == [1:1, 2:2]
      * * @param left a map * @param right a map * @return a Map as an intersection of both maps * @since 1.7.4 */ public static Map intersect(Map left, Map right) { final Map ansMap = createSimilarMap(left); if (right != null && right.size() > 0) { final Iterator> it1 = left.entrySet().iterator(); while (it1.hasNext()) { final Map.Entry e1 = it1.next(); final Iterator> it2 = right.entrySet().iterator(); while (it2.hasNext()) { final Map.Entry e2 = it2.next(); if (DefaultTypeTransformation.compareEqual(e1, e2)) { ansMap.put(e1.getKey(), e1.getValue()); } } } } return ansMap; } /** * Returns true if the intersection of two collections is empty. *
      assert [1,2,3].disjoint([3,4,5]) == false
      *
      assert [1,2].disjoint([3,4]) == true
      * * @param left a Collection * @param right a Collection * @return boolean true if the intersection of two collections * is empty, false otherwise. * @since 1.0 */ public static boolean disjoint(Collection left, Collection right) { if (left.isEmpty() || right.isEmpty()) return true; Collection pickFrom = new TreeSet(new NumberAwareComparator()); pickFrom.addAll(right); for (final Object o : left) { if (pickFrom.contains(o)) return false; } return true; } /** * Compare the contents of this array to the contents of the given array. * * @param left an int array * @param right the operand array. * @return true if the contents of both arrays are equal. * @since 1.5.0 */ public static boolean equals(int[] left, int[] right) { if (left == null) { return right == null; } if (right == null) { return false; } if (left == right) { return true; } if (left.length != right.length) { return false; } for (int i = 0; i < left.length; i++) { if (left[i] != right[i]) return false; } return true; } /** * Determines if the contents of this array are equal to the * contents of the given list, in the same order. This returns * false if either collection is null. * * @param left this array * @param right the list being compared * @return true if the contents of both collections are equal * @since 1.5.0 */ public static boolean equals(Object[] left, List right) { return coercedEquals(left, right); } /** * Determines if the contents of this list are equal to the * contents of the given array in the same order. This returns * false if either collection is null. *
      assert [1, "a"].equals( [ 1, "a" ] as Object[] )
      * * @param left this List * @param right this Object[] being compared to * @return true if the contents of both collections are equal * @since 1.5.0 */ public static boolean equals(List left, Object[] right) { return coercedEquals(right, left); } private static boolean coercedEquals(Object[] left, List right) { if (left == null) { return right == null; } if (right == null) { return false; } if (left.length != right.size()) { return false; } for (int i = left.length - 1; i >= 0; i--) { final Object o1 = left[i]; final Object o2 = right.get(i); if (o1 == null) { if (o2 != null) return false; } else if (!coercedEquals(o1, o2)) { return false; } } return true; } private static boolean coercedEquals(Object o1, Object o2) { if (o1 instanceof Comparable) { if (!(o2 instanceof Comparable && numberAwareCompareTo((Comparable) o1, (Comparable) o2) == 0)) { return false; } } return DefaultTypeTransformation.compareEqual(o1, o2); } /** * Compare the contents of two Lists. Order matters. * If numbers exist in the Lists, then they are compared as numbers, * for example 2 == 2L. If both lists are null, the result * is true; otherwise if either list is null, the result * is false. *
      assert ["a", 2].equals(["a", 2])
           * assert ![2, "a"].equals("a", 2)
           * assert [2.0, "a"].equals(2L, "a") // number comparison at work
      * * @param left this List * @param right the List being compared to. * @return boolean true if the contents of both lists are identical, * false otherwise. * @since 1.0 */ public static boolean equals(List left, List right) { if (left == null) { return right == null; } if (right == null) { return false; } if (left == right) { return true; } if (left.size() != right.size()) { return false; } final Iterator it1 = left.iterator(), it2 = right.iterator(); while (it1.hasNext()) { final Object o1 = it1.next(); final Object o2 = it2.next(); if (o1 == null) { if (o2 != null) return false; } else if (!coercedEquals(o1, o2)) { return false; } } return true; } /** * Compare the contents of two Sets for equality using Groovy's coercion rules. *

      * Returns true if the two sets have the same size, and every member * of the specified set is contained in this set (or equivalently, every member * of this set is contained in the specified set). * If numbers exist in the sets, then they are compared as numbers, * for example 2 == 2L. If both sets are null, the result * is true; otherwise if either set is null, the result * is false. Example usage: *

           * Set s1 = ["a", 2]
           * def s2 = [2, 'a'] as Set
           * Set s3 = [3, 'a']
           * def s4 = [2.0, 'a'] as Set
           * def s5 = [2L, 'a'] as Set
           * assert s1.equals(s2)
           * assert !s1.equals(s3)
           * assert s1.equals(s4)
           * assert s1.equals(s5)
      * * @param self this Set * @param other the Set being compared to * @return true if the contents of both sets are identical * @since 1.8.0 */ public static boolean equals(Set self, Set other) { if (self == null) { return other == null; } if (other == null) { return false; } if (self == other) { return true; } if (self.size() != other.size()) { return false; } final Iterator it1 = self.iterator(); Collection otherItems = new HashSet(other); while (it1.hasNext()) { final Object o1 = it1.next(); final Iterator it2 = otherItems.iterator(); T foundItem = null; boolean found = false; while (it2.hasNext() && foundItem == null) { final T o2 = it2.next(); if (coercedEquals(o1, o2)) { foundItem = o2; found = true; } } if (!found) return false; otherItems.remove(foundItem); } return otherItems.size() == 0; } /** * Compares two Maps treating coerced numerical values as identical. *

      * Example usage: *

      assert [a:2, b:3] == [a:2L, b:3.0]
      * * @param self this Map * @param other the Map being compared to * @return true if the contents of both maps are identical * @since 1.8.0 */ public static boolean equals(Map self, Map other) { if (self == null) { return other == null; } if (other == null) { return false; } if (self == other) { return true; } if (self.size() != other.size()) { return false; } if (!self.keySet().equals(other.keySet())) { return false; } for (Object key : self.keySet()) { if (!coercedEquals(self.get(key), other.get(key))) { return false; } } return true; } /** * Create a Set composed of the elements of the first set minus the * elements of the given collection. *

      * * @param self a set object * @param operands the items to remove from the set * @return the resulting set * @since 1.5.0 */ public static Set minus(Set self, Collection operands) { Comparator comparator = (self instanceof SortedSet) ? ((SortedSet) self).comparator() : null; final Set ansSet = createSimilarSet(self); ansSet.addAll(self); if (operands != null && operands.size() > 0) { final Iterator it1 = self.iterator(); while (it1.hasNext()) { final Object o1 = it1.next(); final Iterator it2 = operands.iterator(); while (it2.hasNext()) { final Object o2 = it2.next(); boolean areEqual = (comparator != null)? (comparator.compare(o1, o2) == 0) : coercedEquals(o1, o2); if (areEqual) { ansSet.remove(o1); } } } } return ansSet; } /** * Create a Set composed of the elements of the first set minus the operand. * * @param self a set object * @param operand the operand to remove from the set * @return the resulting set * @since 1.5.0 */ public static Set minus(Set self, Object operand) { Comparator comparator = (self instanceof SortedSet) ? ((SortedSet) self).comparator() : null; final Set ansSet = createSimilarSet(self); for (T t : self) { boolean areEqual = (comparator != null)? (comparator.compare(t, operand) == 0) : coercedEquals(t, operand); if (!areEqual) ansSet.add(t); } return ansSet; } /** * Create an array composed of the elements of the first array minus the * elements of the given collection. * * @param self an object array * @param removeMe a Collection of elements to remove * @return an array with the supplied elements removed * @since 1.5.5 */ @SuppressWarnings("unchecked") public static T[] minus(T[] self, Collection removeMe) { return (T[]) minus(toList(self), removeMe).toArray(); } /** * Create an array composed of the elements of the first array minus the * elements of the given array. * * @param self an object array * @param removeMe an array of elements to remove * @return an array with the supplied elements removed * @since 1.5.5 */ @SuppressWarnings("unchecked") public static T[] minus(T[] self, T[] removeMe) { return (T[]) minus(toList(self), toList(removeMe)).toArray(); } /** * Create a List composed of the elements of the first list minus * every occurrence of elements of the given collection. *

      assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]
      * * @param self a List * @param removeMe a Collection of elements to remove * @return a List with the supplied elements removed * @since 1.0 */ public static List minus(List self, Collection removeMe) { if (self.size() == 0) return new ArrayList(); boolean nlgnSort = sameType(new Collection[]{self, removeMe}); // We can't use the same tactic as for intersection // since AbstractCollection only does a remove on the first // element it encounters. Comparator numberComparator = new NumberAwareComparator(); if (nlgnSort && (self.get(0) instanceof Comparable)) { //n*LOG(n) version Set answer; if (Number.class.isInstance(self.get(0))) { answer = new TreeSet(numberComparator); answer.addAll(self); for (T t : self) { if (Number.class.isInstance(t)) { for (T t2 : removeMe) { if (Number.class.isInstance(t2)) { if (numberComparator.compare(t, t2) == 0) answer.remove(t); } } } else { if (removeMe.contains(t)) answer.remove(t); } } } else { answer = new TreeSet(numberComparator); answer.addAll(self); answer.removeAll(removeMe); } List ansList = new ArrayList(); for (T o : self) { if (answer.contains(o)) ansList.add(o); } return ansList; } else { //n*n version List tmpAnswer = new LinkedList(self); for (Iterator iter = tmpAnswer.iterator(); iter.hasNext();) { T element = iter.next(); boolean elementRemoved = false; for (Iterator iterator = removeMe.iterator(); iterator.hasNext() && !elementRemoved;) { T elt = iterator.next(); if (numberComparator.compare(element, elt) == 0) { iter.remove(); elementRemoved = true; } } } //remove duplicates //can't use treeset since the base classes are different return new ArrayList(tmpAnswer); } } /** * Create a new List composed of the elements of the first list minus every occurrence of the * operand. *
      assert ["a", 5, 5, true] - 5 == ["a", true]
      * * @param self a List object * @param operand an element to remove from the list * @return the resulting List with the operand removed * @since 1.0 */ public static List minus(List self, Object operand) { List ansList = new ArrayList(); for (T t : self) { if (!coercedEquals(t, operand)) ansList.add(t); } return ansList; } /** * Create a new object array composed of the elements of the first array * minus the operand. * * @param self an object array * @param operand an element to remove from the array * @return a new array with the operand removed * @since 1.5.5 */ public static T[] minus(T[] self, Object operand) { return (T[]) minus(toList(self), operand).toArray(); } /** * Create a Map composed of the entries of the first map minus the * entries of the given map. * * @param self a map object * @param operands the entries to remove from the map * @return the resulting map * @since 1.7.4 */ public static Map minus(Map self, Map operands) { final Map ansMap = createSimilarMap(self); ansMap.putAll(self); if (operands != null && operands.size() > 0) { final Iterator> it1 = self.entrySet().iterator(); while (it1.hasNext()) { final Map.Entry e1 = it1.next(); final Iterator> it2 = operands.entrySet().iterator(); while (it2.hasNext()) { final Map.Entry e2 = it2.next(); if (DefaultTypeTransformation.compareEqual(e1, e2)) { ansMap.remove(e1.getKey()); } } } } return ansMap; } /** * Flatten a collection. This collection and any nested arrays or * collections have their contents (recursively) added to the new collection. *
      assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()
      * * @param self a Collection to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(Collection self) { return flatten(self, createSimilarCollection(self)); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self an Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(Object[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a boolean Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(boolean[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a byte Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(byte[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a char Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(char[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a short Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(short[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self an int Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(int[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a long Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(long[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a float Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(float[] self) { return flatten(toList(self), new ArrayList()); } /** * Flatten an array. This array and any nested arrays or * collections have their contents (recursively) added to the new collection. * * @param self a double Array to flatten * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(double[] self) { return flatten(toList(self), new ArrayList()); } private static Collection flatten(Collection elements, Collection addTo) { for (Object element : elements) { if (element instanceof Collection) { flatten((Collection) element, addTo); } else if (element != null && element.getClass().isArray()) { flatten(DefaultTypeTransformation.arrayAsCollection(element), addTo); } else { // found a leaf addTo.add(element); } } return addTo; } /** * Flatten a collection. This collection and any nested arrays or * collections have their contents (recursively) added to the new collection. * For any non-Array, non-Collection object which represents some sort * of collective type, the supplied closure should yield the contained items; * otherwise, the closure should just return any element which corresponds to a leaf. * * @param self a Collection * @param flattenUsing a closure to determine how to flatten non-Array, non-Collection elements * @return a flattened Collection * @since 1.6.0 */ public static Collection flatten(Collection self, Closure flattenUsing) { return flatten(self, createSimilarCollection(self), flattenUsing); } private static Collection flatten(Collection elements, Collection addTo, Closure flattenUsing) { for (Object element : elements) { if (element instanceof Collection) { flatten((Collection) element, addTo, flattenUsing); } else if (element != null && element.getClass().isArray()) { flatten(DefaultTypeTransformation.arrayAsCollection(element), addTo, flattenUsing); } else { T flattened = flattenUsing.call(new Object[]{element}); boolean returnedSelf = flattened == element; if (!returnedSelf && flattened instanceof Collection) { List list = toList((Collection) flattened); if (list.size() == 1 && list.get(0) == element) { returnedSelf = true; } } if (flattened instanceof Collection && !returnedSelf) { flatten((Collection) flattened, addTo, flattenUsing); } else { addTo.add(flattened); } } } return addTo; } /** * Overloads the left shift operator to provide an easy way to append * objects to a Collection. *
      def list = [1,2]
           * list << 3
           * assert list == [1,2,3]
      * * @param self a Collection * @param value an Object to be added to the collection. * @return same collection, after the value was added to it. * @since 1.0 */ public static Collection leftShift(Collection self, T value) { self.add(value); return self; } /** * Overloads the left shift operator to provide an easy way to append * objects to a BlockingQueue. * In case of bounded queue the method will block till space in the queue become available *
      def list = new java.util.concurrent.LinkedBlockingQueue ()
           * list << 3 << 2 << 1
           * assert list.iterator().collect{it} == [3,2,1]
      * * @param self a Collection * @param value an Object to be added to the collection. * @return same collection, after the value was added to it. * @since 1.7.1 */ public static BlockingQueue leftShift(BlockingQueue self, T value) throws InterruptedException { self.put(value); return self; } /** * Overloads the left shift operator to provide an easy way to append * Map.Entry values to a Map. * * @param self a Map * @param entry a Map.Entry to be added to the Map. * @return same map, after the value has been added to it. * @since 1.6.0 */ public static Map leftShift(Map self, Map.Entry entry) { self.put(entry.getKey(), entry.getValue()); return self; } /** * Overloads the left shift operator to provide an easy way to put * one maps entries into another map. This allows the compact syntax * map1 << map2; otherwise it's just a synonym for * putAll though it returns the original map rather than * being a void method. Example usage: *
      def map = [a:1, b:2]
           * map << [c:3, d:4]
           * assert map == [a:1, b:2, c:3, d:4]
      * * @param self a Map * @param other another Map whose entries should be added to the original Map. * @return same map, after the values have been added to it. * @since 1.7.2 */ public static Map leftShift(Map self, Map other) { self.putAll(other); return self; } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a String. * * @param self a String * @param value an Object * @return a StringBuffer built from this string * @since 1.0 */ public static StringBuffer leftShift(String self, Object value) { return new StringBuffer(self).append(value); } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a CharSequence. * * @param self a CharSequence * @param value an Object * @return a StringBuilder built from this CharSequence * @since 1.8.2 */ public static StringBuilder leftShift(CharSequence self, Object value) { return new StringBuilder(self).append(value); } /** * Overloads the left shift operator to provide syntactic sugar for appending to a StringBuilder. * * @param self a StringBuilder * @param value an Object * @return the original StringBuilder * @since 1.8.2 */ public static StringBuilder leftShift(StringBuilder self, Object value) { self.append(value); return self; } protected static StringWriter createStringWriter(String self) { StringWriter answer = new StringWriter(); answer.write(self); return answer; } protected static StringBufferWriter createStringBufferWriter(StringBuffer self) { return new StringBufferWriter(self); } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a StringBuffer. * * @param self a StringBuffer * @param value a value to append * @return the StringBuffer on which this operation was invoked * @since 1.0 */ public static StringBuffer leftShift(StringBuffer self, Object value) { self.append(value); return self; } /** * Overloads the left shift operator to provide a mechanism to append * values to a writer. * * @param self a Writer * @param value a value to append * @return the writer on which this operation was invoked * @throws IOException if an I/O error occurs. * @since 1.0 */ public static Writer leftShift(Writer self, Object value) throws IOException { InvokerHelper.write(self, value); return self; } /** * Implementation of the left shift operator for integral types. Non integral * Number types throw UnsupportedOperationException. * * @param self a Number object * @param operand the shift distance by which to left shift the number * @return the resulting number * @since 1.5.0 */ public static Number leftShift(Number self, Number operand) { return NumberMath.leftShift(self, operand); } /** * Implementation of the right shift operator for integral types. Non integral * Number types throw UnsupportedOperationException. * * @param self a Number object * @param operand the shift distance by which to right shift the number * @return the resulting number * @since 1.5.0 */ public static Number rightShift(Number self, Number operand) { return NumberMath.rightShift(self, operand); } /** * Implementation of the right shift (unsigned) operator for integral types. Non integral * Number types throw UnsupportedOperationException. * * @param self a Number object * @param operand the shift distance by which to right shift (unsigned) the number * @return the resulting number * @since 1.5.0 */ public static Number rightShiftUnsigned(Number self, Number operand) { return NumberMath.rightShiftUnsigned(self, operand); } /** * A helper method so that dynamic dispatch of the writer.write(object) method * will always use the more efficient Writable.writeTo(writer) mechanism if the * object implements the Writable interface. * * @param self a Writer * @param writable an object implementing the Writable interface * @throws IOException if an I/O error occurs. * @since 1.0 */ public static void write(Writer self, Writable writable) throws IOException { writable.writeTo(self); } /** * Overloads the leftShift operator to provide an append mechanism to add values to a stream. * * @param self an OutputStream * @param value a value to append * @return a Writer * @throws IOException if an I/O error occurs. * @since 1.0 */ public static Writer leftShift(OutputStream self, Object value) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter(self); leftShift(writer, value); return writer; } /** * Overloads the leftShift operator to add objects to an ObjectOutputStream. * * @param self an ObjectOutputStream * @param value an object to write to the stream * @throws IOException if an I/O error occurs. * @since 1.5.0 */ public static void leftShift(ObjectOutputStream self, Object value) throws IOException { self.writeObject(value); } /** * Pipe an InputStream into an OutputStream for efficient stream copying. * * @param self stream on which to write * @param in stream to read from * @return the outputstream itself * @throws IOException if an I/O error occurs. * @since 1.0 */ public static OutputStream leftShift(OutputStream self, InputStream in) throws IOException { byte[] buf = new byte[1024]; while (true) { int count = in.read(buf, 0, buf.length); if (count == -1) break; if (count == 0) { Thread.yield(); continue; } self.write(buf, 0, count); } self.flush(); return self; } /** * Overloads the leftShift operator to provide an append mechanism to add bytes to a stream. * * @param self an OutputStream * @param value a value to append * @return an OutputStream * @throws IOException if an I/O error occurs. * @since 1.0 */ public static OutputStream leftShift(OutputStream self, byte[] value) throws IOException { self.write(value); self.flush(); return self; } // Primitive type array methods //------------------------------------------------------------------------- /** * Support the subscript operator with a range for a byte array * * @param array a byte array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved bytes * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(byte[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a char array * * @param array a char array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved chars * @since 1.5.0 */ @SuppressWarnings("unchecked") public static List getAt(char[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a short array * * @param array a short array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved shorts * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(short[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for an int array * * @param array an int array * @param range a range indicating the indices for the items to retrieve * @return list of the ints at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(int[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a long array * * @param array a long array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved longs * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(long[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a float array * * @param array a float array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved floats * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(float[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a double array * * @param array a double array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved doubles * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(double[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a range for a boolean array * * @param array a boolean array * @param range a range indicating the indices for the items to retrieve * @return list of the retrieved booleans * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(boolean[] array, Range range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a byte array * * @param array a byte array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved bytes * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(byte[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a char array * * @param array a char array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved chars * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(char[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a short array * * @param array a short array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved shorts * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(short[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for an int array * * @param array an int array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved ints * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(int[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a long array * * @param array a long array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved longs * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(long[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a float array * * @param array a float array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved floats * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(float[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a double array * * @param array a double array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved doubles * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(double[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an IntRange for a boolean array * * @param array a boolean array * @param range an IntRange indicating the indices for the items to retrieve * @return list of the retrieved booleans * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(boolean[] array, IntRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a byte array * * @param array a byte array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved bytes * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(byte[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a char array * * @param array a char array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved chars * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(char[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a short array * * @param array a short array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved shorts * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(short[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for an int array * * @param array an int array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved ints * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(int[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a long array * * @param array a long array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved longs * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(long[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a float array * * @param array a float array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved floats * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(float[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a double array * * @param array a double array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved doubles * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(double[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with an ObjectRange for a byte array * * @param array a byte array * @param range an ObjectRange indicating the indices for the items to retrieve * @return list of the retrieved bytes * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(boolean[] array, ObjectRange range) { return primitiveArrayGet(array, range); } /** * Support the subscript operator with a collection for a byte array * * @param array a byte array * @param indices a collection of indices for the items to retrieve * @return list of the bytes at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(byte[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a char array * * @param array a char array * @param indices a collection of indices for the items to retrieve * @return list of the chars at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(char[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a short array * * @param array a short array * @param indices a collection of indices for the items to retrieve * @return list of the shorts at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(short[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for an int array * * @param array an int array * @param indices a collection of indices for the items to retrieve * @return list of the ints at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(int[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a long array * * @param array a long array * @param indices a collection of indices for the items to retrieve * @return list of the longs at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(long[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a float array * * @param array a float array * @param indices a collection of indices for the items to retrieve * @return list of the floats at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(float[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a double array * * @param array a double array * @param indices a collection of indices for the items to retrieve * @return list of the doubles at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(double[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator with a collection for a boolean array * * @param array a boolean array * @param indices a collection of indices for the items to retrieve * @return list of the booleans at the given indices * @since 1.0 */ @SuppressWarnings("unchecked") public static List getAt(boolean[] array, Collection indices) { return primitiveArrayGet(array, indices); } /** * Support the subscript operator for a Bitset * * @param self a BitSet * @param index index to retrieve * @return value of the bit at the given index * @see java.util.BitSet * @since 1.5.0 */ public static boolean getAt(BitSet self, int index) { return self.get(index); } /** * Support retrieving a subset of a BitSet using a Range * * @param self a BitSet * @param range a Range defining the desired subset * @return a new BitSet that represents the requested subset * @see java.util.BitSet * @see groovy.lang.IntRange * @since 1.5.0 */ public static BitSet getAt(BitSet self, IntRange range) { int from = DefaultTypeTransformation.intUnbox(range.getFrom()); int to = DefaultTypeTransformation.intUnbox(range.getTo()); BitSet result = new BitSet(); int numberOfBits = to - from + 1; int adjuster = 1; int offset = from; if (range.isReverse()) { adjuster = -1; offset = to; } for (int i = 0; i < numberOfBits; i++) { result.set(i, self.get(offset + (adjuster * i))); } return result; } // public static Boolean putAt(boolean[] array, int idx, Boolean newValue) { // return (Boolean) primitiveArrayPut(array, idx, newValue); // } // // public static Byte putAt(byte[] array, int idx, Object newValue) { // if (!(newValue instanceof Byte)) { // Number n = (Number) newValue; // newValue = new Byte(n.byteValue()); // } // return (Byte) primitiveArrayPut(array, idx, newValue); // } // // public static Character putAt(char[] array, int idx, Object newValue) { // if (newValue instanceof String) { // String s = (String) newValue; // if (s.length() != 1) throw new IllegalArgumentException("String of length 1 expected but got a bigger one"); // char c = s.charAt(0); // newValue = new Character(c); // } // return (Character) primitiveArrayPut(array, idx, newValue); // } // // public static Short putAt(short[] array, int idx, Object newValue) { // if (!(newValue instanceof Short)) { // Number n = (Number) newValue; // newValue = new Short(n.shortValue()); // } // return (Short) primitiveArrayPut(array, idx, newValue); // } // // public static Integer putAt(int[] array, int idx, Object newValue) { // if (!(newValue instanceof Integer)) { // Number n = (Number) newValue; // newValue = Integer.valueOf(n.intValue()); // } // array [normaliseIndex(idx,array.length)] = ((Integer)newValue).intValue(); // return (Integer) newValue; // } // // public static Long putAt(long[] array, int idx, Object newValue) { // if (!(newValue instanceof Long)) { // Number n = (Number) newValue; // newValue = new Long(n.longValue()); // } // return (Long) primitiveArrayPut(array, idx, newValue); // } // // public static Float putAt(float[] array, int idx, Object newValue) { // if (!(newValue instanceof Float)) { // Number n = (Number) newValue; // newValue = new Float(n.floatValue()); // } // return (Float) primitiveArrayPut(array, idx, newValue); // } // // public static Double putAt(double[] array, int idx, Object newValue) { // if (!(newValue instanceof Double)) { // Number n = (Number) newValue; // newValue = new Double(n.doubleValue()); // } // return (Double) primitiveArrayPut(array, idx, newValue); // } /** * Support assigning a range of values with a single assignment statement. * * @param self a BitSet * @param range the range of values to set * @param value value * @see java.util.BitSet * @see groovy.lang.Range * @since 1.5.0 */ public static void putAt(BitSet self, IntRange range, boolean value) { int from = DefaultTypeTransformation.intUnbox(range.getFrom()); int to = DefaultTypeTransformation.intUnbox(range.getTo()); // If this is a backwards range, reverse the arguments to set. if (from > to) { int tmp = to; to = from; from = tmp; } self.set(from, to + 1, value); } /** * Support subscript-style assignment for a BitSet. * * @param self a BitSet * @param index index of the entry to set * @param value value * @see java.util.BitSet * @since 1.5.0 */ public static void putAt(BitSet self, int index, boolean value) { self.set(index, value); } /** * Allows arrays to behave similar to collections. * @param array a boolean array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.5.0 */ public static int size(boolean[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a byte array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(byte[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a char array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(char[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a short array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(short[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array an int array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(int[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a long array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(long[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a float array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(float[] array) { return Array.getLength(array); } /** * Allows arrays to behave similar to collections. * @param array a double array * @return the length of the array * @see java.lang.reflect.Array#getLength(java.lang.Object) * @since 1.0 */ public static int size(double[] array) { return Array.getLength(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a byte array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(byte[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a boolean array * @return a list containing the contents of this array. * @since 1.6.0 */ @SuppressWarnings("unchecked") public static List toList(boolean[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a char array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(char[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a short array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(short[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array an int array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(int[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a long array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(long[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a float array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(float[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a List of the same size, with each element * added to the list. * * @param array a double array * @return a list containing the contents of this array. * @since 1.0 */ @SuppressWarnings("unchecked") public static List toList(double[] array) { return DefaultTypeTransformation.primitiveArrayToList(array); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a byte array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(byte[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a boolean array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(boolean[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a char array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(char[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a short array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(short[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array an int array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(int[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a long array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(long[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a float array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(float[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Converts this array to a Set, with each unique element * added to the set. * * @param array a double array * @return a set containing the unique contents of this array. * @since 1.8.0 */ @SuppressWarnings("unchecked") public static Set toSet(double[] array) { return toSet(DefaultTypeTransformation.primitiveArrayToList(array)); } /** * Convert a Collection to a Set. Always returns a new Set * even if the Collection is already a Set. *

      * Example usage: *

           * def result = [1, 2, 2, 2, 3].toSet()
           * assert result instanceof Set
           * assert result == [1, 2, 3] as Set
           * 
      * * @param self a collection * @return a Set * @since 1.8.0 */ public static Set toSet(Collection self) { Set answer = new HashSet(self.size()); answer.addAll(self); return answer; } /** * Convert an iterator to a Set. The iterator will become * exhausted of elements after making this conversion. * * @param self an iterator * @return a Set * @since 1.8.0 */ public static Set toSet(Iterator self) { Set answer = new HashSet(); while (self.hasNext()) { answer.add(self.next()); } return answer; } /** * Convert an enumeration to a Set. * * @param self an enumeration * @return a Set * @since 1.8.0 */ public static Set toSet(Enumeration self) { Set answer = new HashSet(); while (self.hasMoreElements()) { answer.add(self.nextElement()); } return answer; } /** * Implements the getAt(int) method for primitive type arrays. * * @param self an array object * @param idx the index of interest * @return the returned value from the array * @since 1.5.0 */ protected static Object primitiveArrayGet(Object self, int idx) { return Array.get(self, normaliseIndex(idx, Array.getLength(self))); } /** * Implements the getAt(Range) method for primitive type arrays. * * @param self an array object * @param range the range of indices of interest * @return the returned values from the array corresponding to the range * @since 1.5.0 */ protected static List primitiveArrayGet(Object self, Range range) { List answer = new ArrayList(); for (Object next : range) { int idx = DefaultTypeTransformation.intUnbox(next); answer.add(primitiveArrayGet(self, idx)); } return answer; } /** * Implements the getAt(Collection) method for primitive type arrays. Each * value in the collection argument is assumed to be a valid array index. * The value at each index is then added to a list which is returned. * * @param self an array object * @param indices the indices of interest * @return the returned values from the array * @since 1.0 */ protected static List primitiveArrayGet(Object self, Collection indices) { List answer = new ArrayList(); for (Object value : indices) { if (value instanceof Range) { answer.addAll(primitiveArrayGet(self, (Range) value)); } else if (value instanceof List) { answer.addAll(primitiveArrayGet(self, (List) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); answer.add(primitiveArrayGet(self, idx)); } } return answer; } /** * Implements the setAt(int idx) method for primitive type arrays. * * @param self an object * @param idx the index of interest * @param newValue the new value to be put into the index of interest * @return the added value * @since 1.5.0 */ protected static Object primitiveArrayPut(Object self, int idx, Object newValue) { Array.set(self, normaliseIndex(idx, Array.getLength(self)), newValue); return newValue; } // String methods //------------------------------------------------------------------------- /** * Converts the given string into a Character object * using the first character in the string. * * @param self a String * @return the first Character * @since 1.0 */ public static Character toCharacter(String self) { return self.charAt(0); } /** * Converts the given string into a Boolean object. * If the trimmed string is "true", "y" or "1" (ignoring case) * then the result is true otherwise it is false. * * @param self a String * @return The Boolean value * @since 1.0 */ public static Boolean toBoolean(String self) { final String trimmed = self.trim(); if ("true".equalsIgnoreCase(trimmed) || "y".equalsIgnoreCase(trimmed) || "1".equals(trimmed)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } /** * Identity conversion which returns Boolean.TRUE for a true Boolean and Boolean.FALSE for a false Boolean. * * @param self a Boolean * @return the original Boolean * @since 1.7.6 */ public static Boolean toBoolean(Boolean self) { return self; } /** * Convenience method to split a string (with whitespace as delimiter) * Like tokenize, but returns an Array of Strings instead of a List * * @param self the string to split * @return String[] result of split * @since 1.5.0 */ public static String[] split(String self) { StringTokenizer st = new StringTokenizer(self); String[] strings = new String[st.countTokens()]; for (int i = 0; i < strings.length; i++) { strings[i] = st.nextToken(); } return strings; } /** * Convenience method to split a CharSequence (with whitespace as delimiter). * Similar to tokenize, but returns an Array of CharSequence instead of a List. * * @param self the CharSequence to split * @return CharSequence[] result of split * @see #split(String) * @since 1.8.2 */ public static CharSequence[] split(CharSequence self) { return split(self.toString()); } /** * Convenience method to capitalize the first letter of a string * (typically the first letter of a word). Example usage: *
           * assert 'h'.capitalize() == 'H'
           * assert 'hello'.capitalize() == 'Hello'
           * assert 'hello world'.capitalize() == 'Hello world'
           * assert 'Hello World' ==
           *     'hello world'.split(' ').collect{ it.capitalize() }.join(' ')
           * 
      * * @param self The string to capitalize * @return The capitalized String * @since 1.7.3 */ public static String capitalize(String self) { if (self == null || self.length() == 0) return self; return Character.toUpperCase(self.charAt(0)) + self.substring(1); } /** * Convenience method to capitalize the first letter of a CharSequence. * * @param self The CharSequence to capitalize * @return The capitalized CharSequence * @see #capitalize(String) * @since 1.8.2 */ public static CharSequence capitalize(CharSequence self) { return capitalize(self.toString()); } /** * Expands all tabs into spaces with tabStops of size 8. * * @param self A String to expand * @return The expanded String * @since 1.7.3 * @see #expand(java.lang.String, int) */ public static String expand(String self) { return expand(self, 8); } /** * Expands all tabs into spaces with tabStops of size 8. * * @param self A CharSequence to expand * @return The expanded CharSequence * @see #expand(java.lang.String) * @since 1.8.2 */ public static CharSequence expand(CharSequence self) { return expand(self.toString(), 8); } /** * Expands all tabs into spaces. If the String has multiple * lines, expand each line - restarting tab stops at the start * of each line. * * @param self A String to expand * @param tabStop The number of spaces a tab represents * @return The expanded String * @since 1.7.3 */ public static String expand(String self, int tabStop) { if (self.length() == 0) return self; try { StringBuilder builder = new StringBuilder(); for (String line : readLines(self)) { builder.append(expandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!self.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return self; } /** * Expands all tabs into spaces. If the CharSequence has multiple * lines, expand each line - restarting tab stops at the start * of each line. * * @param self A CharSequence to expand * @param tabStop The number of spaces a tab represents * @return The expanded CharSequence * @see #expand(String, int) * @since 1.8.2 */ public static CharSequence expand(CharSequence self, int tabStop) { return expand(self.toString(), tabStop); } /** * Expands all tabs into spaces. Assumes the String represents a single line of text. * * @param self A line to expand * @param tabStop The number of spaces a tab represents * @return The expanded String * @since 1.7.3 */ public static String expandLine(String self, int tabStop) { int index; while ((index = self.indexOf('\t')) != -1) { StringBuilder builder = new StringBuilder(self); int count = tabStop - index % tabStop; builder.deleteCharAt(index); for (int i = 0; i < count; i++) builder.insert(index, " "); self = builder.toString(); } return self; } /** * Expands all tabs into spaces. Assumes the CharSequence represents a single line of text. * * @param self A line to expand * @param tabStop The number of spaces a tab represents * @return The expanded CharSequence * @see #expandLine(String, int) * @since 1.8.2 */ public static CharSequence expandLine(CharSequence self, int tabStop) { return expandLine(self.toString(), tabStop); } /** * Replaces sequences of whitespaces with tabs using tabStops of size 8. * * @param self A String to unexpand * @return The unexpanded String * @since 1.7.3 * @see #unexpand(java.lang.String, int) */ public static String unexpand(String self) { return unexpand(self, 8); } /** * Replaces sequences of whitespaces with tabs using tabStops of size 8. * * @param self A CharSequence to unexpand * @return The unexpanded CharSequence * @see #unexpand(java.lang.String) * @since 1.8.2 */ public static CharSequence unexpand(CharSequence self) { return unexpand(self.toString()); } /** * Replaces sequences of whitespaces with tabs. * * @param self A String to unexpand * @param tabStop The number of spaces a tab represents * @return The unexpanded String * @since 1.7.3 */ public static String unexpand(String self, int tabStop) { if (self.length() == 0) return self; try { StringBuilder builder = new StringBuilder(); for (String line : readLines(self)) { builder.append(unexpandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!self.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return self; } /** * Replaces sequences of whitespaces with tabs. * * @param self A CharSequence to unexpand * @param tabStop The number of spaces a tab represents * @return The unexpanded CharSequence * @see #unexpand(String, int) * @since 1.8.2 */ public static CharSequence unexpand(CharSequence self, int tabStop) { return unexpand(self.toString(), tabStop); } /** * Replaces sequences of whitespaces with tabs within a line. * * @param self A line to unexpand * @param tabStop The number of spaces a tab represents * @return The unexpanded String * @since 1.7.3 */ public static String unexpandLine(String self, int tabStop) { StringBuilder builder = new StringBuilder(self); int index = 0; while (index + tabStop < builder.length()) { // cut original string in tabstop-length pieces String piece = builder.substring(index, index + tabStop); // count trailing whitespace characters int count = 0; while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1))))) count++; // replace if whitespace was found if (count > 0) { piece = piece.substring(0, tabStop - count) + '\t'; builder.replace(index, index + tabStop, piece); index = index + tabStop - (count - 1); } else index = index + tabStop; } return builder.toString(); } /** * Replaces sequences of whitespaces with tabs within a line. * * @param self A line to unexpand * @param tabStop The number of spaces a tab represents * @return The unexpanded CharSequence * @see #unexpandLine(String, int) * @since 1.8.2 */ public static CharSequence unexpandLine(CharSequence self, int tabStop) { return unexpandLine(self.toString(), tabStop); } /** * Convenience method to split a GString (with whitespace as delimiter). * * @param self the GString to split * @return String[] result of split * @see #split(java.lang.String) * @since 1.6.1 */ public static String[] split(GString self) { return split(self.toString()); } /** * Tokenize a String based on the given string delimiter. * * @param self a String * @param token the delimiter * @return a List of tokens * @see java.util.StringTokenizer#StringTokenizer(java.lang.String, java.lang.String) * @since 1.0 */ @SuppressWarnings("unchecked") public static List tokenize(String self, String token) { return InvokerHelper.asList(new StringTokenizer(self, token)); } /** * Tokenize a CharSequence based on the given CharSequence delimiter. * * @param self a CharSequence * @param token the delimiter * @return a List of tokens * @see #tokenize(String, String) * @since 1.8.2 */ public static List tokenize(CharSequence self, CharSequence token) { return new ArrayList(tokenize(self.toString(), token.toString())); } /** * Tokenize a String based on the given character delimiter. * For example: *
           * char pathSep = ':'
           * assert "/tmp:/usr".tokenize(pathSep) == ["/tmp", "/usr"]
           * 
      * * @param self a String * @param token the delimiter * @return a List of tokens * @see java.util.StringTokenizer#StringTokenizer(java.lang.String, java.lang.String) * @since 1.7.2 */ public static List tokenize(String self, Character token) { return tokenize(self, token.toString()); } /** * Tokenize a CharSequence based on the given character delimiter. * * @param self a CharSequence * @param token the delimiter * @return a List of tokens * @see #tokenize(String, Character) * @since 1.8.2 */ public static List tokenize(CharSequence self, Character token) { return tokenize(self, token.toString()); } /** * Tokenize a String (with a whitespace as the delimiter). * * @param self a String * @return a List of tokens * @see java.util.StringTokenizer#StringTokenizer(java.lang.String) * @since 1.0 */ @SuppressWarnings("unchecked") public static List tokenize(String self) { return InvokerHelper.asList(new StringTokenizer(self)); } /** * Tokenize a CharSequence (with a whitespace as the delimiter). * * @param self a CharSequence * @return a List of tokens * @see #tokenize(String) * @since 1.8.2 */ public static List tokenize(CharSequence self) { return new ArrayList(tokenize(self.toString())); } /** * Appends the String representation of the given operand to this string. * * @param left a String * @param value any Object * @return the new string with the object appended * @since 1.0 */ public static String plus(String left, Object value) { return left + toString(value); } /** * Appends the String representation of the given operand to this string. * * @param left a CharSequence * @param value any Object * @return the new CharSequence with the object appended * @since 1.8.2 */ public static CharSequence plus(CharSequence left, Object value) { return left + toString(value); } /** * Appends a String to the string representation of this number. * * @param value a Number * @param right a String * @return a String * @since 1.0 */ public static String plus(Number value, String right) { return toString(value) + right; } /** * Appends a String to this StringBuffer. * * @param left a StringBuffer * @param value a String * @return a String * @since 1.0 */ public static String plus(StringBuffer left, String value) { return left + value; } /** * Remove a part of a String. This replaces the first occurrence * of target within self with '' and returns the result. If * target is a regex Pattern, the first occurrence of that * pattern will be removed (using regex matching), otherwise * the first occurrence of target.toString() will be removed. * * @param self a String * @param target an object representing the part to remove * @return a String minus the part to be removed * @since 1.0 */ public static String minus(String self, Object target) { if (target instanceof Pattern) { return ((Pattern)target).matcher(self).replaceFirst(""); } String text = toString(target); int index = self.indexOf(text); if (index == -1) return self; int end = index + text.length(); if (self.length() > end) { return self.substring(0, index) + self.substring(end); } return self.substring(0, index); } /** * Remove a part of a CharSequence by replacing the first occurrence * of target within self with '' and returns the result. * * @param self a CharSequence * @param target an object representing the part to remove * @return a CharSequence minus the part to be removed * @see #minus(String, Object) * @since 1.8.2 */ public static CharSequence minus(CharSequence self, Object target) { return minus(self.toString(), target); } /** * Provide an implementation of contains() like * {@link java.util.Collection#contains(java.lang.Object)} to make Strings more polymorphic. * This method is not required on JDK 1.5 onwards * * @param self a String * @param text a String to look for * @return true if this string contains the given text * @since 1.0 */ public static boolean contains(String self, String text) { int idx = self.indexOf(text); return idx >= 0; } /** * Provide an implementation of contains() like * {@link java.util.Collection#contains(java.lang.Object)} to make CharSequences more polymorphic. * * @param self a CharSequence * @param text the CharSequence to look for * @return true if this CharSequence contains the given text * @see #contains(String, String) * @since 1.8.2 */ public static boolean contains(CharSequence self, CharSequence text) { return contains(self.toString(), text.toString()); } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(int[] self, Object value) { for (int next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(long[] self, Object value) { for (long next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(short[] self, Object value) { for (short next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(char[] self, Object value) { for (char next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array within which we count the number of occurrences * @param value the value being searched for * @return the number of occurrences * @since 1.8.6 */ public static boolean contains(boolean[] self, Object value) { for (boolean next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(double[] self, Object value) { for (double next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(float[] self, Object value) { for (float next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(byte[] self, Object value) { for (byte next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Checks whether the array contains the given value. * * @param self the array we are searching * @param value the value being searched for * @return true if the array contains the value * @since 1.8.6 */ public static boolean contains(Object[] self, Object value) { for (Object next : self) { if (DefaultTypeTransformation.compareEqual(value, next)) return true; } return false; } /** * Count the number of occurrences of a substring. * * @param self a String * @param text a substring * @return the number of occurrences of the given string inside this String * @since 1.0 */ public static int count(String self, String text) { int answer = 0; for (int idx = 0; true; idx++) { idx = self.indexOf(text, idx); if (idx >= 0) { ++answer; } else { break; } } return answer; } /** * Count the number of occurrences of a sub CharSequence. * * @param self a CharSequence * @param text a sub CharSequence * @return the number of occurrences of the given CharSequence inside this CharSequence * @see #count(String, String) * @since 1.8.2 */ public static int count(CharSequence self, CharSequence text) { return count(self.toString(), text.toString()); } /** * This method is called by the ++ operator for the class String. * It increments the last character in the given string. If the * character in the string is Character.MAX_VALUE a Character.MIN_VALUE * will be appended. The empty string is incremented to a string * consisting of the character Character.MIN_VALUE. * * @param self a String * @return an incremented String * @since 1.0 */ public static String next(String self) { StringBuilder buffer = new StringBuilder(self); if (buffer.length() == 0) { buffer.append(Character.MIN_VALUE); } else { char last = buffer.charAt(buffer.length() - 1); if (last == Character.MAX_VALUE) { buffer.append(Character.MIN_VALUE); } else { char next = last; next++; buffer.setCharAt(buffer.length() - 1, next); } } return buffer.toString(); } /** * This method is called by the ++ operator for the class CharSequence. * * @param self a CharSequence * @return an incremented CharSequence * @see #next(String) * @since 1.8.2 */ public static CharSequence next(CharSequence self) { return next(self.toString()); } /** * This method is called by the -- operator for the class String. * It decrements the last character in the given string. If the * character in the string is Character.MIN_VALUE it will be deleted. * The empty string can't be decremented. * * @param self a String * @return a String with a decremented digit at the end * @since 1.0 */ public static String previous(String self) { StringBuilder buffer = new StringBuilder(self); if (buffer.length() == 0) throw new IllegalArgumentException("the string is empty"); char last = buffer.charAt(buffer.length() - 1); if (last == Character.MIN_VALUE) { buffer.deleteCharAt(buffer.length() - 1); } else { char next = last; next--; buffer.setCharAt(buffer.length() - 1, next); } return buffer.toString(); } /** * This method is called by the -- operator for the class CharSequence. * * @param self a CharSequence * @return a CharSequence with a decremented digit at the end * @see #previous(String) * @since 1.8.2 */ public static CharSequence previous(CharSequence self) { return previous(self.toString()); } /** * Executes the command specified by self as a command-line process. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param self a command line String * @return the Process which has just started for this command line representation * @throws IOException if an IOException occurs. * @since 1.0 */ public static Process execute(final String self) throws IOException { return Runtime.getRuntime().exec(self); } /** * Executes the command specified by self with environment defined by envp * and under the working directory dir. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param self a command line String to be executed. * @param envp an array of Strings, each element of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.0 */ public static Process execute(final String self, final String[] envp, final File dir) throws IOException { return Runtime.getRuntime().exec(self, envp, dir); } /** * Executes the command specified by self with environment defined * by envp and under the working directory dir. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param self a command line String to be executed. * @param envp a List of Objects (converted to Strings using toString), each member of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.0 */ public static Process execute(final String self, final List envp, final File dir) throws IOException { return execute(self, stringify(envp), dir); } /** * Executes the command specified by the given String array. * The first item in the array is the command; the others are the parameters. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commandArray an array of String containing the command name and * parameters as separate items in the array. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.0 */ public static Process execute(final String[] commandArray) throws IOException { return Runtime.getRuntime().exec(commandArray); } /** * Executes the command specified by the String array given in the first parameter, * with the environment defined by envp and under the working directory dir. * The first item in the array is the command; the others are the parameters. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commandArray an array of String containing the command name and * parameters as separate items in the array. * @param envp an array of Strings, each member of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static Process execute(final String[] commandArray, final String[] envp, final File dir) throws IOException { return Runtime.getRuntime().exec(commandArray, envp, dir); } /** * Executes the command specified by the String array given in the first parameter, * with the environment defined by envp and under the working directory dir. * The first item in the array is the command; the others are the parameters. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commandArray an array of String containing the command name and * parameters as separate items in the array. * @param envp a List of Objects (converted to Strings using toString), each member of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static Process execute(final String[] commandArray, final List envp, final File dir) throws IOException { return Runtime.getRuntime().exec(commandArray, stringify(envp), dir); } /** * Executes the command specified by the given list. The toString() method is called * for each item in the list to convert into a resulting String. * The first item in the list is the command the others are the parameters. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commands a list containing the command name and * parameters as separate items in the list. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.0 */ public static Process execute(final List commands) throws IOException { return execute(stringify(commands)); } /** * Executes the command specified by the given list, * with the environment defined by envp and under the working directory dir. * The first item in the list is the command; the others are the parameters. The toString() * method is called on items in the list to convert them to Strings. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commands a List containing the command name and * parameters as separate items in the list. * @param envp an array of Strings, each member of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static Process execute(final List commands, final String[] envp, final File dir) throws IOException { return Runtime.getRuntime().exec(stringify(commands), envp, dir); } /** * Executes the command specified by the given list, * with the environment defined by envp and under the working directory dir. * The first item in the list is the command; the others are the parameters. The toString() * method is called on items in the list to convert them to Strings. *

      For more control over Process construction you can use * java.lang.ProcessBuilder (JDK 1.5+).

      * * @param commands a List containing the command name and * parameters as separate items in the list. * @param envp a List of Objects (converted to Strings using toString), each member of which * has environment variable settings in the format * name=value, or * null if the subprocess should inherit * the environment of the current process. * @param dir the working directory of the subprocess, or * null if the subprocess should inherit * the working directory of the current process. * @return the Process which has just started for this command line representation. * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static Process execute(final List commands, final List envp, final File dir) throws IOException { return Runtime.getRuntime().exec(stringify(commands), stringify(envp), dir); } private static String[] stringify(final List orig) { if (orig == null) return null; String[] result = new String[orig.size()]; for (int i = 0; i < orig.size(); i++) { result[i] = orig.get(i).toString(); } return result; } /** * Repeat a String a certain number of times. * * @param self a String to be repeated * @param factor the number of times the String should be repeated * @return a String composed of a repetition * @throws IllegalArgumentException if the number of repetitions is < 0 * @since 1.0 */ public static String multiply(String self, Number factor) { int size = factor.intValue(); if (size == 0) return ""; else if (size < 0) { throw new IllegalArgumentException("multiply() should be called with a number of 0 or greater not: " + size); } StringBuilder answer = new StringBuilder(self); for (int i = 1; i < size; i++) { answer.append(self); } return answer.toString(); } /** * Repeat a CharSequence a certain number of times. * * @param self a CharSequence to be repeated * @param factor the number of times the CharSequence should be repeated * @return a CharSequence composed of a repetition * @throws IllegalArgumentException if the number of repetitions is < 0 * @since 1.8.2 */ public static CharSequence multiply(CharSequence self, Number factor) { return multiply(self.toString(), factor); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(boolean[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(byte[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(char[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(short[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(int[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(long[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(float[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given array. * * @param self an array * @return the string representation * @since 1.6.0 */ public static String toString(double[] self) { return InvokerHelper.toString(self); } /** * Returns the string representation of the given map. * * @param self a Map * @return the string representation * @see #toMapString(java.util.Map) * @since 1.0 */ public static String toString(AbstractMap self) { return toMapString(self); } /** * Returns the string representation of this map. The string displays the * contents of the map, i.e. [one:1, two:2, three:3]. * * @param self a Map * @return the string representation * @since 1.0 */ public static String toMapString(Map self) { return toMapString(self, -1); } /** * Returns the string representation of this map. The string displays the * contents of the map, i.e. [one:1, two:2, three:3]. * * @param self a Map * @param maxSize stop after approximately this many characters and append '...' * @return the string representation * @since 1.0 */ public static String toMapString(Map self, int maxSize) { return (self == null) ? "null" : InvokerHelper.toMapString(self, maxSize); } /** * Returns the string representation of the given collection. The string * displays the contents of the collection, i.e. * [1, 2, a]. * * @param self a Collection * @return the string representation * @see #toListString(java.util.Collection) * @since 1.0 */ public static String toString(AbstractCollection self) { return toListString(self); } /** * Returns the string representation of the given list. The string * displays the contents of the list, similar to a list literal, i.e. * [1, 2, a]. * * @param self a Collection * @return the string representation * @since 1.0 */ public static String toListString(Collection self) { return toListString(self, -1); } /** * Returns the string representation of the given list. The string * displays the contents of the list, similar to a list literal, i.e. * [1, 2, a]. * * @param self a Collection * @param maxSize stop after approximately this many characters and append '...' * @return the string representation * @since 1.7.3 */ public static String toListString(Collection self, int maxSize) { return (self == null) ? "null" : InvokerHelper.toListString(self, maxSize); } /** * Returns the string representation of this array's contents. * * @param self an Object[] * @return the string representation * @see #toArrayString(java.lang.Object[]) * @since 1.0 */ public static String toString(Object[] self) { return toArrayString(self); } /** * Returns the string representation of the given array. The string * displays the contents of the array, similar to an array literal, i.e. * {1, 2, "a"}. * * @param self an Object[] * @return the string representation * @since 1.0 */ public static String toArrayString(Object[] self) { return (self == null) ? "null" : InvokerHelper.toArrayString(self); } /** * Create a String representation of this object. * @param value an object * @return a string. * @since 1.0 */ public static String toString(Object value) { return InvokerHelper.toString(value); } // Number based methods //------------------------------------------------------------------------- /** * Increment a Character by one. * * @param self a Character * @return an incremented Character * @since 1.5.7 */ public static Character next(Character self) { return (char) (self + 1); } /** * Increment a Number by one. * * @param self a Number * @return an incremented Number * @since 1.0 */ public static Number next(Number self) { return NumberNumberPlus.plus(self, ONE); } /** * Decrement a Character by one. * * @param self a Character * @return a decremented Character * @since 1.5.7 */ public static Character previous(Character self) { return (char) (self - 1); } /** * Decrement a Number by one. * * @param self a Number * @return a decremented Number * @since 1.0 */ public static Number previous(Number self) { return NumberNumberMinus.minus(self, ONE); } /** * Add a Character and a Number. The ordinal value of the Character * is used in the addition (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * This operation will always create a new object for the result, * while the operands remain unchanged. * * @see java.lang.Integer#valueOf(int) * @param left a Character * @param right a Number * @return the Number corresponding to the addition of left and right * @since 1.0 */ public static Number plus(Character left, Number right) { return NumberNumberPlus.plus(Integer.valueOf(left), right); } /** * Add a Number and a Character. The ordinal value of the Character * is used in the addition (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @see java.lang.Integer#valueOf(int) * @param left a Number * @param right a Character * @return The Number corresponding to the addition of left and right * @since 1.0 */ public static Number plus(Number left, Character right) { return NumberNumberPlus.plus(left, Integer.valueOf(right)); } /** * Add one Character to another. The ordinal values of the Characters * are used in the addition (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * This operation will always create a new object for the result, * while the operands remain unchanged. * * @see #plus(java.lang.Number, java.lang.Character) * @param left a Character * @param right a Character * @return the Number corresponding to the addition of left and right * @since 1.0 */ public static Number plus(Character left, Character right) { return plus(Integer.valueOf(left), right); } /** * Compare a Character and a Number. The ordinal value of the Character * is used in the comparison (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Number * @return the result of the comparison * @since 1.0 */ public static int compareTo(Character left, Number right) { return compareTo(Integer.valueOf(left), right); } /** * Compare a Number and a Character. The ordinal value of the Character * is used in the comparison (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Number * @param right a Character * @return the result of the comparison * @since 1.0 */ public static int compareTo(Number left, Character right) { return compareTo(left, Integer.valueOf(right)); } /** * Compare two Characters. The ordinal values of the Characters * are compared (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Character * @return the result of the comparison * @since 1.0 */ public static int compareTo(Character left, Character right) { return compareTo(Integer.valueOf(left), right); } /** * Compare two Numbers. Equality (==) for numbers dispatches to this. * * @param left a Number * @param right another Number to compare to * @return the comparison of both numbers * @since 1.0 */ public static int compareTo(Number left, Number right) { /** @todo maybe a double dispatch thing to handle new large numbers? */ return NumberMath.compareTo(left, right); } /** * Subtract a Number from a Character. The ordinal value of the Character * is used in the subtraction (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Number * @return the Number corresponding to the subtraction of right from left * @since 1.0 */ public static Number minus(Character left, Number right) { return NumberNumberMinus.minus(Integer.valueOf(left), right); } /** * Subtract a Character from a Number. The ordinal value of the Character * is used in the subtraction (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Number * @param right a Character * @return the Number corresponding to the subtraction of right from left * @since 1.0 */ public static Number minus(Number left, Character right) { return NumberNumberMinus.minus(left, Integer.valueOf(right)); } /** * Subtract one Character from another. The ordinal values of the Characters * is used in the comparison (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Character * @return the Number corresponding to the subtraction of right from left * @since 1.0 */ public static Number minus(Character left, Character right) { return minus(Integer.valueOf(left), right); } /** * Multiply a Character by a Number. The ordinal value of the Character * is used in the multiplication (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Number * @return the Number corresponding to the multiplication of left by right * @since 1.0 */ public static Number multiply(Character left, Number right) { return NumberNumberMultiply.multiply(Integer.valueOf(left), right); } /** * Multiply a Number by a Character. The ordinal value of the Character * is used in the multiplication (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Number * @param right a Character * @return the multiplication of left by right * @since 1.0 */ public static Number multiply(Number left, Character right) { return NumberNumberMultiply.multiply(Integer.valueOf(right), left); } /** * Multiply two Characters. The ordinal values of the Characters * are used in the multiplication (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right another Character * @return the Number corresponding to the multiplication of left by right * @since 1.0 */ public static Number multiply(Character left, Character right) { return multiply(Integer.valueOf(left), right); } /** * Multiply a BigDecimal and a Double. * Note: This method was added to enforce the Groovy rule of * BigDecimal*Double == Double. Without this method, the * multiply(BigDecimal) method in BigDecimal would respond * and return a BigDecimal instead. Since BigDecimal is preferred * over Number, the Number*Number method is not chosen as in older * versions of Groovy. * * @param left a BigDecimal * @param right a Double * @return the multiplication of left by right * @since 1.0 */ public static Number multiply(BigDecimal left, Double right) { return NumberMath.multiply(left, right); } /** * Multiply a BigDecimal and a BigInteger. * Note: This method was added to enforce the Groovy rule of * BigDecimal*long == long. Without this method, the * multiply(BigDecimal) method in BigDecimal would respond * and return a BigDecimal instead. Since BigDecimal is preferred * over Number, the Number*Number method is not chosen as in older * versions of Groovy. BigInteger is the fallback for all integer * types in Groovy * * @param left a BigDecimal * @param right a BigInteger * @return the multiplication of left by right * @since 1.0 */ public static Number multiply(BigDecimal left, BigInteger right) { return NumberMath.multiply(left, right); } /** * Power of a Number to a certain exponent. Called by the '**' operator. * * @param self a Number * @param exponent a Number exponent * @return a Number to the power of a certain exponent * @since 1.0 */ public static Number power(Number self, Number exponent) { double base, exp, answer; base = self.doubleValue(); exp = exponent.doubleValue(); answer = Math.pow(base, exp); if ((double) ((int) answer) == answer) { return (int) answer; } else if ((double) ((long) answer) == answer) { return (long) answer; } else { return answer; } } /** * Power of a BigDecimal to an integer certain exponent. If the * exponent is positive, call the BigDecimal.pow(int) method to * maintain precision. Called by the '**' operator. * * @param self a BigDecimal * @param exponent an Integer exponent * @return a Number to the power of a the exponent */ public static Number power(BigDecimal self, Integer exponent) { if (exponent >= 0) { return self.pow(exponent); } else { return power(self, (double) exponent); } } /** * Power of a BigInteger to an integer certain exponent. If the * exponent is positive, call the BigInteger.pow(int) method to * maintain precision. Called by the '**' operator. * * @param self a BigInteger * @param exponent an Integer exponent * @return a Number to the power of a the exponent */ public static Number power(BigInteger self, Integer exponent) { if (exponent >= 0) { return self.pow(exponent); } else { return power(self, (double) exponent); } } /** * Power of an integer to an integer certain exponent. If the * exponent is positive, convert to a BigInteger and call * BigInteger.pow(int) method to maintain precision. Called by the * '**' operator. * * @param self an Integer * @param exponent an Integer exponent * @return a Number to the power of a the exponent */ public static Number power(Integer self, Integer exponent) { if (exponent >= 0) { BigInteger answer = BigInteger.valueOf(self).pow(exponent); if (answer.compareTo(BI_INT_MIN) >= 0 && answer.compareTo(BI_INT_MAX) <= 0) { return answer.intValue(); } else { return answer; } } else { return power(self, (double) exponent); } } /** * Power of a long to an integer certain exponent. If the * exponent is positive, convert to a BigInteger and call * BigInteger.pow(int) method to maintain precision. Called by the * '**' operator. * * @param self a Long * @param exponent an Integer exponent * @return a Number to the power of a the exponent */ public static Number power(Long self, Integer exponent) { if (exponent >= 0) { BigInteger answer = BigInteger.valueOf(self).pow(exponent); if (answer.compareTo(BI_LONG_MIN) >= 0 && answer.compareTo(BI_LONG_MAX) <= 0) { return answer.longValue(); } else { return answer; } } else { return power(self, (double) exponent); } } /** * Divide a Character by a Number. The ordinal value of the Character * is used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Number * @return the Number corresponding to the division of left by right * @since 1.0 */ public static Number div(Character left, Number right) { return NumberNumberDiv.div(Integer.valueOf(left), right); } /** * Divide a Number by a Character. The ordinal value of the Character * is used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Number * @param right a Character * @return the Number corresponding to the division of left by right * @since 1.0 */ public static Number div(Number left, Character right) { return NumberNumberDiv.div(left, Integer.valueOf(right)); } /** * Divide one Character by another. The ordinal values of the Characters * are used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right another Character * @return the Number corresponding to the division of left by right * @since 1.0 */ public static Number div(Character left, Character right) { return div(Integer.valueOf(left), right); } /** * Integer Divide a Character by a Number. The ordinal value of the Character * is used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right a Number * @return a Number (an Integer) resulting from the integer division operation * @since 1.0 */ public static Number intdiv(Character left, Number right) { return intdiv(Integer.valueOf(left), right); } /** * Integer Divide a Number by a Character. The ordinal value of the Character * is used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Number * @param right a Character * @return a Number (an Integer) resulting from the integer division operation * @since 1.0 */ public static Number intdiv(Number left, Character right) { return intdiv(left, Integer.valueOf(right)); } /** * Integer Divide two Characters. The ordinal values of the Characters * are used in the division (the ordinal value is the unicode * value which for simple character sets is the ASCII value). * * @param left a Character * @param right another Character * @return a Number (an Integer) resulting from the integer division operation * @since 1.0 */ public static Number intdiv(Character left, Character right) { return intdiv(Integer.valueOf(left), right); } /** * Integer Divide two Numbers. * * @param left a Number * @param right another Number * @return a Number (an Integer) resulting from the integer division operation * @since 1.0 */ public static Number intdiv(Number left, Number right) { return NumberMath.intdiv(left, right); } /** * Bitwise OR together two numbers. * * @param left a Number * @param right another Number to bitwise OR * @return the bitwise OR of both Numbers * @since 1.0 */ public static Number or(Number left, Number right) { return NumberMath.or(left, right); } /** * Bitwise AND together two Numbers. * * @param left a Number * @param right another Number to bitwise AND * @return the bitwise AND of both Numbers * @since 1.0 */ public static Number and(Number left, Number right) { return NumberMath.and(left, right); } /** * Bitwise AND together two BitSets. * * @param left a BitSet * @param right another BitSet to bitwise AND * @return the bitwise AND of both BitSets * @since 1.5.0 */ public static BitSet and(BitSet left, BitSet right) { BitSet result = (BitSet) left.clone(); result.and(right); return result; } /** * Bitwise XOR together two BitSets. Called when the '^' operator is used * between two bit sets. * * @param left a BitSet * @param right another BitSet to bitwise AND * @return the bitwise XOR of both BitSets * @since 1.5.0 */ public static BitSet xor(BitSet left, BitSet right) { BitSet result = (BitSet) left.clone(); result.xor(right); return result; } /** * Bitwise NEGATE a BitSet. * * @param self a BitSet * @return the bitwise NEGATE of the BitSet * @since 1.5.0 */ public static BitSet bitwiseNegate(BitSet self) { BitSet result = (BitSet) self.clone(); result.flip(0, result.size() - 1); return result; } /** * Bitwise OR together two BitSets. Called when the '|' operator is used * between two bit sets. * * @param left a BitSet * @param right another BitSet to bitwise AND * @return the bitwise OR of both BitSets * @since 1.5.0 */ public static BitSet or(BitSet left, BitSet right) { BitSet result = (BitSet) left.clone(); result.or(right); return result; } /** * Bitwise XOR together two Numbers. Called when the '|' operator is used. * * @param left a Number * @param right another Number to bitwse XOR * @return the bitwise XOR of both Numbers * @since 1.0 */ public static Number xor(Number left, Number right) { return NumberMath.xor(left, right); } /** * Performs a division modulus operation. Called by the '%' operator. * * @param left a Number * @param right another Number to mod * @return the modulus result * @since 1.0 */ public static Number mod(Number left, Number right) { return NumberMath.mod(left, right); } /** * Negates the number. Equivalent to the '-' operator when it preceeds * a single operand, i.e. -10 * * @param left a Number * @return the negation of the number * @since 1.5.0 */ public static Number unaryMinus(Number left) { return NumberMath.unaryMinus(left); } /** * Executes the closure this many times, starting from zero. The current * index is passed to the closure each time. * Example: *
      10.times {
           *   println it
           * }
      * Prints the numbers 0 through 9. * * @param self a Number * @param closure the closure to call a number of times * @since 1.0 */ public static void times(Number self, Closure closure) { for (int i = 0, size = self.intValue(); i < size; i++) { closure.call(i); if (closure.getDirective() == Closure.DONE) { break; } } } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a Number * @param to another Number to go up to * @param closure the closure to call * @since 1.0 */ public static void upto(Number self, Number to, Closure closure) { int self1 = self.intValue(); int to1 = to.intValue(); if (self1 <= to1) { for (int i = self1; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a long * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(long self, Number to, Closure closure) { long to1 = to.longValue(); if (self <= to1) { for (long i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a Long * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(Long self, Number to, Closure closure) { long to1 = to.longValue(); if (self <= to1) { for (long i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a float * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(float self, Number to, Closure closure) { float to1 = to.floatValue(); if (self <= to1) { for (float i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a Float * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(Float self, Number to, Closure closure) { float to1 = to.floatValue(); if (self <= to1) { for (float i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a double * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(double self, Number to, Closure closure) { double to1 = to.doubleValue(); if (self <= to1) { for (double i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. * * @param self a Double * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(Double self, Number to, Closure closure) { double to1 = to.doubleValue(); if (self <= to1) { for (double i = self; i <= to1; i++) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. Example: *
      0.upto( 10 ) {
           *   println it
           * }
      * Prints numbers 0 to 10 * * @param self a BigInteger * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(BigInteger self, Number to, Closure closure) { if (to instanceof BigDecimal) { final BigDecimal one = BigDecimal.valueOf(10, 1); BigDecimal self1 = new BigDecimal(self); BigDecimal to1 = (BigDecimal) to; if (self1.compareTo(to1) <= 0) { for (BigDecimal i = self1; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } else if (to instanceof BigInteger) { final BigInteger one = BigInteger.valueOf(1); BigInteger to1 = (BigInteger) to; if (self.compareTo(to1) <= 0) { for (BigInteger i = self; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } else { final BigInteger one = BigInteger.valueOf(1); BigInteger to1 = new BigInteger(to.toString()); if (self.compareTo(to1) <= 0) { for (BigInteger i = self; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } } /** * Iterates from this number up to the given number, inclusive, * incrementing by one each time. *
      0.1.upto( 10 ) {
           *   println it
           * }
      * Prints numbers 0.1, 1.1, 2.1... to 9.1 * * @param self a BigDecimal * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void upto(BigDecimal self, Number to, Closure closure) { final BigDecimal one = BigDecimal.valueOf(10, 1); // That's what you get for "1.0". if (to instanceof BigDecimal) { BigDecimal to1 = (BigDecimal) to; if (self.compareTo(to1) <= 0) { for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } else if (to instanceof BigInteger) { BigDecimal to1 = new BigDecimal((BigInteger) to); if (self.compareTo(to1) <= 0) { for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } else { BigDecimal to1 = new BigDecimal(to.toString()); if (self.compareTo(to1) <= 0) { for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")"); } } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a Number * @param to another Number to go down to * @param closure the closure to call * @since 1.0 */ public static void downto(Number self, Number to, Closure closure) { int self1 = self.intValue(); int to1 = to.intValue(); if (self1 >= to1) { for (int i = self1; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a long * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(long self, Number to, Closure closure) { long to1 = to.longValue(); if (self >= to1) { for (long i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a Long * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(Long self, Number to, Closure closure) { long to1 = to.longValue(); if (self >= to1) { for (long i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a float * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(float self, Number to, Closure closure) { float to1 = to.floatValue(); if (self >= to1) { for (float i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a Float * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(Float self, Number to, Closure closure) { float to1 = to.floatValue(); if (self >= to1) { for (float i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a double * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(double self, Number to, Closure closure) { double to1 = to.doubleValue(); if (self >= to1) { for (double i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a Double * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(Double self, Number to, Closure closure) { double to1 = to.doubleValue(); if (self >= to1) { for (double i = self; i >= to1; i--) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. * * @param self a BigInteger * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(BigInteger self, Number to, Closure closure) { if (to instanceof BigDecimal) { final BigDecimal one = BigDecimal.valueOf(10, 1); // That's what you get for "1.0". final BigDecimal to1 = (BigDecimal) to; final BigDecimal selfD = new BigDecimal(self); if (selfD.compareTo(to1) >= 0) { for (BigDecimal i = selfD; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i.toBigInteger()); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } else if (to instanceof BigInteger) { final BigInteger one = BigInteger.valueOf(1); final BigInteger to1 = (BigInteger) to; if (self.compareTo(to1) >= 0) { for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } else { final BigInteger one = BigInteger.valueOf(1); final BigInteger to1 = new BigInteger(to.toString()); if (self.compareTo(to1) >= 0) { for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } } /** * Iterates from this number down to the given number, inclusive, * decrementing by one each time. Each number is passed to the closure. * Example: *
      10.5.downto(0) {
           *   println it
           * }
      * Prints numbers 10.5, 9.5 ... to 0.5. * * @param self a BigDecimal * @param to the end number * @param closure the code to execute for each number * @since 1.0 */ public static void downto(BigDecimal self, Number to, Closure closure) { final BigDecimal one = BigDecimal.valueOf(10, 1); // Quick way to get "1.0". if (to instanceof BigDecimal) { BigDecimal to1 = (BigDecimal) to; if (self.compareTo(to1) >= 0) { for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } else if (to instanceof BigInteger) { BigDecimal to1 = new BigDecimal((BigInteger) to); if (self.compareTo(to1) >= 0) { for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } else { BigDecimal to1 = new BigDecimal(to.toString()); if (self.compareTo(to1) >= 0) { for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) { closure.call(i); } } else throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")"); } } /** * Iterates from this number up to the given number using a step increment. * Each intermediate number is passed to the given closure. Example: *
      0.step( 10, 2 ) {
           *   println it
           * }
      * Prints even numbers 0 through 8. * * @param self a Number to start with * @param to a Number to go up to, exclusive * @param stepNumber a Number representing the step increment * @param closure the closure to call * @since 1.0 */ public static void step(Number self, Number to, Number stepNumber, Closure closure) { if (self instanceof BigDecimal || to instanceof BigDecimal || stepNumber instanceof BigDecimal) { final BigDecimal zero = BigDecimal.valueOf(0, 1); // Same as "0.0". BigDecimal self1 = (self instanceof BigDecimal) ? (BigDecimal) self : new BigDecimal(self.toString()); BigDecimal to1 = (to instanceof BigDecimal) ? (BigDecimal) to : new BigDecimal(to.toString()); BigDecimal stepNumber1 = (stepNumber instanceof BigDecimal) ? (BigDecimal) stepNumber : new BigDecimal(stepNumber.toString()); if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) { for (BigDecimal i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) { closure.call(i); } } else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) { for (BigDecimal i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) { closure.call(i); } } else if(self1.compareTo(to1) != 0) throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")"); } else if (self instanceof BigInteger || to instanceof BigInteger || stepNumber instanceof BigInteger) { final BigInteger zero = BigInteger.valueOf(0); BigInteger self1 = (self instanceof BigInteger) ? (BigInteger) self : new BigInteger(self.toString()); BigInteger to1 = (to instanceof BigInteger) ? (BigInteger) to : new BigInteger(to.toString()); BigInteger stepNumber1 = (stepNumber instanceof BigInteger) ? (BigInteger) stepNumber : new BigInteger(stepNumber.toString()); if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) { for (BigInteger i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) { closure.call(i); } } else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) { for (BigInteger i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) { closure.call(i); } } else if(self1.compareTo(to1) != 0) throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")"); } else { int self1 = self.intValue(); int to1 = to.intValue(); int stepNumber1 = stepNumber.intValue(); if (stepNumber1 > 0 && to1 > self1) { for (int i = self1; i < to1; i += stepNumber1) { closure.call(i); } } else if (stepNumber1 < 0 && to1 < self1) { for (int i = self1; i > to1; i += stepNumber1) { closure.call(i); } } else if(self1 != to1) throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")"); } } /** * Get the absolute value * * @param number a Number * @return the absolute value of that Number * @since 1.0 */ //Note: This method is NOT called if number is a BigInteger or BigDecimal because //those classes implement a method with a better exact match. public static int abs(Number number) { return Math.abs(number.intValue()); } /** * Get the absolute value * * @param number a Long * @return the absolute value of that Long * @since 1.0 */ public static long abs(Long number) { return Math.abs(number.longValue()); } /** * Get the absolute value * * @param number a Float * @return the absolute value of that Float * @since 1.0 */ public static float abs(Float number) { return Math.abs(number.floatValue()); } /** * Get the absolute value * * @param number a Double * @return the absolute value of that Double * @since 1.0 */ public static double abs(Double number) { return Math.abs(number); } /** * Round the value * * @param number a Float * @return the rounded value of that Float * @since 1.0 */ public static int round(Float number) { return Math.round(number.floatValue()); } /** * Round the value * * @param number a Float * @param precision the number of decimal places to keep * @return the Float rounded to the number of decimal places specified by precision * @since 1.6.0 */ public static float round(Float number, int precision) { return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision)+0.5)/Math.pow(10,precision)); } /** * Truncate the value * * @param number a Float * @param precision the number of decimal places to keep * @return the Float truncated to the number of decimal places specified by precision * @since 1.6.0 */ public static float trunc(Float number, int precision) { return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision))/Math.pow(10,precision)); } /** * Truncate the value * * @param number a Double * @return the Double truncated to 0 decimal places (i.e. a synonym for floor) * @since 1.6.0 */ public static float trunc(Float number) { return (float)Math.floor(number.doubleValue()); } /** * Round the value * * @param number a Double * @return the rounded value of that Double * @since 1.0 */ public static long round(Double number) { return Math.round(number); } /** * Round the value * * @param number a Double * @param precision the number of decimal places to keep * @return the Double rounded to the number of decimal places specified by precision * @since 1.6.4 */ public static double round(Double number, int precision) { return Math.floor(number *Math.pow(10,precision)+0.5)/Math.pow(10,precision); } /** * Truncate the value * * @param number a Double * @return the Double truncated to 0 decimal places (i.e. a synonym for floor) * @since 1.6.4 */ public static double trunc(Double number) { return Math.floor(number); } /** * Truncate the value * * @param number a Double * @param precision the number of decimal places to keep * @return the Double truncated to the number of decimal places specified by precision * @since 1.6.4 */ public static double trunc(Double number, int precision) { return Math.floor(number *Math.pow(10,precision))/Math.pow(10,precision); } /** * Parse a String into an Integer * * @param self a String * @return an Integer * @since 1.0 */ public static Integer toInteger(String self) { return Integer.valueOf(self.trim()); } /** * Parse a String into a Long * * @param self a String * @return a Long * @since 1.0 */ public static Long toLong(String self) { return Long.valueOf(self.trim()); } /** * Parse a String into a Short * * @param self a String * @return a Short * @since 1.5.7 */ public static Short toShort(String self) { return Short.valueOf(self.trim()); } /** * Parse a String into a Float * * @param self a String * @return a Float * @since 1.0 */ public static Float toFloat(String self) { return Float.valueOf(self.trim()); } /** * Parse a String into a Double * * @param self a String * @return a Double * @since 1.0 */ public static Double toDouble(String self) { return Double.valueOf(self.trim()); } /** * Parse a String into a BigInteger * * @param self a String * @return a BigInteger * @since 1.0 */ public static BigInteger toBigInteger(String self) { return new BigInteger(self.trim()); } /** * Parse a String into a BigDecimal * * @param self a String * @return a BigDecimal * @since 1.0 */ public static BigDecimal toBigDecimal(String self) { return new BigDecimal(self.trim()); } /** * Determine if a String can be parsed into an Integer. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isInteger(String self) { try { Integer.valueOf(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a Long. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isLong(String self) { try { Long.valueOf(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a Float. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isFloat(String self) { try { Float.valueOf(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a Double. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isDouble(String self) { try { Double.valueOf(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a BigInteger. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isBigInteger(String self) { try { new BigInteger(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a BigDecimal. * * @param self a String * @return true if the string can be parsed * @since 1.5.0 */ public static boolean isBigDecimal(String self) { try { new BigDecimal(self.trim()); return true; } catch (NumberFormatException nfe) { return false; } } /** * Determine if a String can be parsed into a Number. * Synonym for 'isBigDecimal()'. * * @param self a String * @return true if the string can be parsed * @see #isBigDecimal(java.lang.String) * @since 1.5.0 */ public static boolean isNumber(String self) { return isBigDecimal(self); } /** * Parse a CharSequence into an Integer * * @param self a CharSequence * @return an Integer * @see #toInteger(java.lang.String) * @since 1.8.2 */ public static Integer toInteger(CharSequence self) { return toInteger(self.toString()); } /** * Parse a CharSequence into a Long * * @param self a CharSequence * @return a Long * @see #toLong(java.lang.String) * @since 1.8.2 */ public static Long toLong(CharSequence self) { return toLong(self.toString()); } /** * Parse a CharSequence into a Short * * @param self a CharSequence * @return a Short * @see #toShort(java.lang.String) * @since 1.8.2 */ public static Short toShort(CharSequence self) { return toShort(self.toString()); } /** * Parse a CharSequence into a Float * * @param self a CharSequence * @return a Float * @see #toFloat(java.lang.String) * @since 1.8.2 */ public static Float toFloat(CharSequence self) { return toFloat(self.toString()); } /** * Parse a CharSequence into a Double * * @param self a CharSequence * @return a Double * @see #toDouble(java.lang.String) * @since 1.8.2 */ public static Double toDouble(CharSequence self) { return toDouble(self.toString()); } /** * Parse a CharSequence into a BigInteger * * @param self a CharSequence * @return a BigInteger * @see #toBigInteger(java.lang.String) * @since 1.8.2 */ public static BigInteger toBigInteger(CharSequence self) { return toBigInteger(self.toString()); } /** * Parse a CharSequence into a BigDecimal * * @param self a CharSequence * @return a BigDecimal * @see #toBigDecimal(java.lang.String) * @since 1.8.2 */ public static BigDecimal toBigDecimal(CharSequence self) { return toBigDecimal(self.toString()); } /** * Determine if a CharSequence can be parsed as an Integer. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isInteger(java.lang.String) * @since 1.8.2 */ public static boolean isInteger(CharSequence self) { return isInteger(self.toString()); } /** * Determine if a CharSequence can be parsed as a Long. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isLong(java.lang.String) * @since 1.8.2 */ public static boolean isLong(CharSequence self) { return isLong(self.toString()); } /** * Determine if a CharSequence can be parsed as a Float. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isFloat(java.lang.String) * @since 1.8.2 */ public static boolean isFloat(CharSequence self) { return isFloat(self.toString()); } /** * Determine if a CharSequence can be parsed as a Double. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isDouble(java.lang.String) * @since 1.8.2 */ public static boolean isDouble(CharSequence self) { return isDouble(self.toString()); } /** * Determine if a CharSequence can be parsed as a BigInteger. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isBigInteger(java.lang.String) * @since 1.8.2 */ public static boolean isBigInteger(CharSequence self) { return isBigInteger(self.toString()); } /** * Determine if a CharSequence can be parsed as a BigDecimal. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isBigDecimal(java.lang.String) * @since 1.8.2 */ public static boolean isBigDecimal(CharSequence self) { return isBigDecimal(self.toString()); } /** * Determine if a CharSequence can be parsed as a Number. * Synonym for 'isBigDecimal()'. * * @param self a CharSequence * @return true if the CharSequence can be parsed * @see #isNumber(java.lang.String) * @since 1.8.2 */ public static boolean isNumber(CharSequence self) { return isNumber(self.toString()); } /** * Determine if a Character is uppercase. * Synonym for 'Character.isUpperCase(this)'. * * @param self a Character * @return true if the character is uppercase * @see java.lang.Character#isUpperCase(char) * @since 1.5.7 */ public static boolean isUpperCase(Character self) { return Character.isUpperCase(self); } /** * Determine if a Character is lowercase. * Synonym for 'Character.isLowerCase(this)'. * * @param self a Character * @return true if the character is lowercase * @see java.lang.Character#isLowerCase(char) * @since 1.5.7 */ public static boolean isLowerCase(Character self) { return Character.isLowerCase(self); } /** * Determines if a character is a letter. * Synonym for 'Character.isLetter(this)'. * * @param self a Character * @return true if the character is a letter * @see java.lang.Character#isLetter(char) * @since 1.5.7 */ public static boolean isLetter(Character self) { return Character.isLetter(self); } /** * Determines if a character is a digit. * Synonym for 'Character.isDigit(this)'. * * @param self a Character * @return true if the character is a digit * @see java.lang.Character#isDigit(char) * @since 1.5.7 */ public static boolean isDigit(Character self) { return Character.isDigit(self); } /** * Determines if a character is a letter or digit. * Synonym for 'Character.isLetterOrDigit(this)'. * * @param self a Character * @return true if the character is a letter or digit * @see java.lang.Character#isLetterOrDigit(char) * @since 1.5.7 */ public static boolean isLetterOrDigit(Character self) { return Character.isLetterOrDigit(self); } /** * Determines if a character is a whitespace character. * Synonym for 'Character.isWhitespace(this)'. * * @param self a Character * @return true if the character is a whitespace character * @see java.lang.Character#isWhitespace(char) * @since 1.5.7 */ public static boolean isWhitespace(Character self) { return Character.isWhitespace(self); } /** * Converts the character to uppercase. * Synonym for 'Character.toUpperCase(this)'. * * @param self a Character to convert * @return the uppercase equivalent of the character, if any; * otherwise, the character itself. * @see java.lang.Character#isUpperCase(char) * @see java.lang.String#toUpperCase() * @since 1.5.7 */ public static char toUpperCase(Character self) { return Character.toUpperCase(self); } /** * Converts the character to lowercase. * Synonym for 'Character.toLowerCase(this)'. * * @param self a Character to convert * @return the lowercase equivalent of the character, if any; * otherwise, the character itself. * @see java.lang.Character#isLowerCase(char) * @see java.lang.String#toLowerCase() * @since 1.5.7 */ public static char toLowerCase(Character self) { return Character.toLowerCase(self); } /** * Transform a Number into an Integer * * @param self a Number * @return an Integer * @since 1.0 */ public static Integer toInteger(Number self) { return self.intValue(); } /** * Transform a Number into a Long * * @param self a Number * @return an Long * @since 1.0 */ public static Long toLong(Number self) { return self.longValue(); } /** * Transform a Number into a Float * * @param self a Number * @return an Float * @since 1.0 */ public static Float toFloat(Number self) { return self.floatValue(); } /** * Transform a Number into a Double * * @param self a Number * @return an Double * @since 1.0 */ public static Double toDouble(Number self) { // Conversions in which all decimal digits are known to be good. if ((self instanceof Double) || (self instanceof Long) || (self instanceof Integer) || (self instanceof Short) || (self instanceof Byte)) { return self.doubleValue(); } // Chances are this is a Float or a Big. // With Float we're extending binary precision and that gets ugly in decimal. // If we used Float.doubleValue() on 0.1f we get 0.10000000149011612. // Note that this is different than casting '(double) 0.1f' which will do the // binary extension just like in Java. // With Bigs and other unknowns, this is likely to be the same. return Double.valueOf(self.toString()); } /** * Transform a Number into a BigDecimal * * @param self a Number * @return an BigDecimal * @since 1.0 */ public static BigDecimal toBigDecimal(Number self) { // Quick method for scalars. if ((self instanceof Long) || (self instanceof Integer) || (self instanceof Short) || (self instanceof Byte)) { return BigDecimal.valueOf(self.longValue()); } return new BigDecimal(self.toString()); } /** * Transform this number to a the given type, using the 'as' operator. The * following types are supported in addition to the default * {@link #asType(java.lang.Object, java.lang.Class)}: *
        *
      • BigDecimal
      • *
      • BigInteger
      • *
      • Double
      • *
      • Float
      • *
      * @param self this number * @param c the desired type of the transformed result * @return an instance of the given type * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(Number self, Class c) { if (c == BigDecimal.class) { return (T) toBigDecimal(self); } else if (c == BigInteger.class) { return (T) toBigInteger(self); } else if (c == Double.class) { return (T) toDouble(self); } else if (c == Float.class) { return (T) toFloat(self); } return asType((Object) self, c); } /** * Transform this Number into a BigInteger. * * @param self a Number * @return an BigInteger * @since 1.0 */ public static BigInteger toBigInteger(Number self) { if (self instanceof BigInteger) { return (BigInteger) self; } else if (self instanceof BigDecimal) { return ((BigDecimal) self).toBigInteger(); } else if (self instanceof Double) { return new BigDecimal((Double)self).toBigInteger(); } else if (self instanceof Float) { return new BigDecimal((Float)self).toBigInteger(); } else { return new BigInteger(Long.toString(self.longValue())); } } // Boolean based methods //------------------------------------------------------------------------- /** * Logical conjunction of two boolean operators. * * @param left left operator * @param right right operator * @return result of logical conjunction * @since 1.0 */ public static Boolean and(Boolean left, Boolean right) { return left && right; } /** * Logical disjunction of two boolean operators * * @param left left operator * @param right right operator * @return result of logical disjunction * @since 1.0 */ public static Boolean or(Boolean left, Boolean right) { return left || right; } /** * Logical implication of two boolean operators * * @param left left operator * @param right right operator * @return result of logical implication * @since 1.8.3 */ public static Boolean implies(Boolean left, Boolean right) { return !left || right; } /** * Exclusive disjunction of two boolean operators * * @param left left operator * @param right right operator * @return result of exclusive disjunction * @since 1.0 */ public static Boolean xor(Boolean left, Boolean right) { return left ^ right; } // public static Boolean negate(Boolean left) { // return Boolean.valueOf(!left.booleanValue()); // } // File and stream based methods //------------------------------------------------------------------------- /** * Create an object output stream for this file. * * @param file a file * @return an object output stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectOutputStream newObjectOutputStream(File file) throws IOException { return new ObjectOutputStream(new FileOutputStream(file)); } /** * Create an object output stream for this output stream. * * @param outputStream an output stream * @return an object output stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectOutputStream newObjectOutputStream(OutputStream outputStream) throws IOException { return new ObjectOutputStream(outputStream); } /** * Create a new ObjectOutputStream for this file and then pass it to the * closure. This method ensures the stream is closed after the closure * returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.OutputStream, groovy.lang.Closure) * @since 1.5.0 */ public static T withObjectOutputStream(File file, Closure closure) throws IOException { return withStream(newObjectOutputStream(file), closure); } /** * Create a new ObjectOutputStream for this output stream and then pass it to the * closure. This method ensures the stream is closed after the closure * returns. * * @param outputStream am output stream * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.OutputStream, groovy.lang.Closure) * @since 1.5.0 */ public static T withObjectOutputStream(OutputStream outputStream, Closure closure) throws IOException { return withStream(newObjectOutputStream(outputStream), closure); } /** * Create an object input stream for this file. * * @param file a file * @return an object input stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectInputStream newObjectInputStream(File file) throws IOException { return new ObjectInputStream(new FileInputStream(file)); } /** * Create an object input stream for this input stream. * * @param inputStream an input stream * @return an object input stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectInputStream newObjectInputStream(InputStream inputStream) throws IOException { return new ObjectInputStream(inputStream); } /** * Create an object input stream for this input stream using the given class loader. * * @param inputStream an input stream * @param classLoader the class loader to use when loading the class * @return an object input stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectInputStream newObjectInputStream(InputStream inputStream, final ClassLoader classLoader) throws IOException { return new ObjectInputStream(inputStream) { protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { return Class.forName(desc.getName(), true, classLoader); } }; } /** * Create an object input stream for this file using the given class loader. * * @param file a file * @param classLoader the class loader to use when loading the class * @return an object input stream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static ObjectInputStream newObjectInputStream(File file, final ClassLoader classLoader) throws IOException { return newObjectInputStream(new FileInputStream(file), classLoader); } /** * Iterates through the given file object by object. * * @param self a File * @param closure a closure * @throws IOException if an IOException occurs. * @throws ClassNotFoundException if the class is not found. * @see #eachObject(java.io.ObjectInputStream, groovy.lang.Closure) * @since 1.0 */ public static void eachObject(File self, Closure closure) throws IOException, ClassNotFoundException { eachObject(newObjectInputStream(self), closure); } /** * Iterates through the given object stream object by object. The * ObjectInputStream is closed afterwards. * * @param ois an ObjectInputStream, closed after the operation * @param closure a closure * @throws IOException if an IOException occurs. * @throws ClassNotFoundException if the class is not found. * @since 1.0 */ public static void eachObject(ObjectInputStream ois, Closure closure) throws IOException, ClassNotFoundException { try { while (true) { try { Object obj = ois.readObject(); // we allow null objects in the object stream closure.call(obj); } catch (EOFException e) { break; } } InputStream temp = ois; ois = null; temp.close(); } finally { closeWithWarning(ois); } } /** * Create a new ObjectInputStream for this file and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.2 */ public static T withObjectInputStream(File file, Closure closure) throws IOException { return withStream(newObjectInputStream(file), closure); } /** * Create a new ObjectInputStream for this file associated with the given class loader and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param classLoader the class loader to use when loading the class * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.2 */ public static T withObjectInputStream(File file, ClassLoader classLoader, Closure closure) throws IOException { return withStream(newObjectInputStream(file, classLoader), closure); } /** * Create a new ObjectInputStream for this file and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param inputStream an input stream * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.0 */ public static T withObjectInputStream(InputStream inputStream, Closure closure) throws IOException { return withStream(newObjectInputStream(inputStream), closure); } /** * Create a new ObjectInputStream for this file and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param inputStream an input stream * @param classLoader the class loader to use when loading the class * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.0 */ public static T withObjectInputStream(InputStream inputStream, ClassLoader classLoader, Closure closure) throws IOException { return withStream(newObjectInputStream(inputStream, classLoader), closure); } /** * Iterates through this String line by line. Each line is passed * to the given 1 or 2 arg closure. If a 2 arg closure is found * the line count is passed as the second argument. * * @param self a String * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @see #eachLine(java.lang.String, int, groovy.lang.Closure) * @since 1.5.5 */ public static T eachLine(String self, Closure closure) throws IOException { return eachLine(self, 0, closure); } /** * Iterates through this CharSequence line by line. Each line is passed * to the given 1 or 2 arg closure. If a 2 arg closure is found * the line count is passed as the second argument. * * @param self a CharSequence * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @see #eachLine(java.lang.String, groovy.lang.Closure) * @since 1.8.2 */ public static T eachLine(CharSequence self, Closure closure) throws IOException { return eachLine(self.toString(), closure); } /** * Iterates through this String line by line. Each line is passed * to the given 1 or 2 arg closure. If a 2 arg closure is found * the line count is passed as the second argument. * * @param self a String * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @since 1.5.7 */ public static T eachLine(String self, int firstLine, Closure closure) throws IOException { int count = firstLine; T result = null; for (String line : readLines(self)) { result = callClosureForLine(closure, line, count); count++; } return result; } /** * Iterates through this CharSequence line by line. Each line is passed * to the given 1 or 2 arg closure. If a 2 arg closure is found * the line count is passed as the second argument. * * @param self a CharSequence * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @see #eachLine(java.lang.String, int, groovy.lang.Closure) * @since 1.8.2 */ public static T eachLine(CharSequence self, int firstLine, Closure closure) throws IOException { return eachLine(self.toString(), firstLine, closure); } /** * Iterates through this file line by line. Each line is passed to the * given 1 or 2 arg closure. The file is read using a reader which * is closed before this method returns. * * @param self a File * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.File, int, groovy.lang.Closure) * @since 1.5.5 */ public static T eachLine(File self, Closure closure) throws IOException { return eachLine(self, 1, closure); } /** * Iterates through this file line by line. Each line is passed to the * given 1 or 2 arg closure. The file is read using a reader which * is closed before this method returns. * * @param self a File * @param charset opens the file with a specified charset * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.File, java.lang.String, int, groovy.lang.Closure) * @since 1.6.8 */ public static T eachLine(File self, String charset, Closure closure) throws IOException { return eachLine(self, charset, 1, closure); } /** * Iterates through this file line by line. Each line is passed * to the given 1 or 2 arg closure. The file is read using a reader * which is closed before this method returns. * * @param self a File * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.5.7 */ public static T eachLine(File self, int firstLine, Closure closure) throws IOException { return eachLine(newReader(self), firstLine, closure); } /** * Iterates through this file line by line. Each line is passed * to the given 1 or 2 arg closure. The file is read using a reader * which is closed before this method returns. * * @param self a File * @param charset opens the file with a specified charset * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.6.8 */ public static T eachLine(File self, String charset, int firstLine, Closure closure) throws IOException { return eachLine(newReader(self, charset), firstLine, closure); } /** * Iterates through this stream reading with the provided charset, passing each line to the * given 1 or 2 arg closure. The stream is closed before this method returns. * * @param stream a stream * @param charset opens the stream with a specified charset * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.InputStream, java.lang.String, int, groovy.lang.Closure) * @since 1.5.5 */ public static T eachLine(InputStream stream, String charset, Closure closure) throws IOException { return eachLine(stream, charset, 1, closure); } /** * Iterates through this stream reading with the provided charset, passing each line to * the given 1 or 2 arg closure. The stream is closed after this method returns. * * @param stream a stream * @param charset opens the stream with a specified charset * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.5.7 */ public static T eachLine(InputStream stream, String charset, int firstLine, Closure closure) throws IOException { return eachLine(new InputStreamReader(stream, charset), firstLine, closure); } /** * Iterates through this stream, passing each line to the given 1 or 2 arg closure. * The stream is closed before this method returns. * * @param stream a stream * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.InputStream, int, groovy.lang.Closure) * @since 1.5.6 */ public static T eachLine(InputStream stream, Closure closure) throws IOException { return eachLine(stream, 1, closure); } /** * Iterates through this stream, passing each line to the given 1 or 2 arg closure. * The stream is closed before this method returns. * * @param stream a stream * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.5.7 */ public static T eachLine(InputStream stream, int firstLine, Closure closure) throws IOException { return eachLine(new InputStreamReader(stream), firstLine, closure); } /** * Iterates through the lines read from the URL's associated input stream passing each * line to the given 1 or 2 arg closure. The stream is closed before this method returns. * * @param url a URL to open and read * @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number starting at line 1) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @see #eachLine(java.net.URL, int, groovy.lang.Closure) * @since 1.5.6 */ public static T eachLine(URL url, Closure closure) throws IOException { return eachLine(url, 1, closure); } /** * Iterates through the lines read from the URL's associated input stream passing each * line to the given 1 or 2 arg closure. The stream is closed before this method returns. * * @param url a URL to open and read * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @see #eachLine(java.io.InputStream, int, groovy.lang.Closure) * @since 1.5.7 */ public static T eachLine(URL url, int firstLine, Closure closure) throws IOException { return eachLine(url.openConnection().getInputStream(), firstLine, closure); } /** * Iterates through the lines read from the URL's associated input stream passing each * line to the given 1 or 2 arg closure. The stream is closed before this method returns. * * @param url a URL to open and read * @param charset opens the stream with a specified charset * @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number starting at line 1) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @see #eachLine(java.net.URL, java.lang.String, int, groovy.lang.Closure) * @since 1.5.6 */ public static T eachLine(URL url, String charset, Closure closure) throws IOException { return eachLine(url, charset, 1, closure); } /** * Iterates through the lines read from the URL's associated input stream passing each * line to the given 1 or 2 arg closure. The stream is closed before this method returns. * * @param url a URL to open and read * @param charset opens the stream with a specified charset * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.5.7 */ public static T eachLine(URL url, String charset, int firstLine, Closure closure) throws IOException { return eachLine(newReader(url, charset), firstLine, closure); } /** * Iterates through the given reader line by line. Each line is passed to the * given 1 or 2 arg closure. If the closure has two arguments, the line count is passed * as the second argument. The Reader is closed before this method returns. * * @param self a Reader, closed after the method returns * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 1.5.6 */ public static T eachLine(Reader self, Closure closure) throws IOException { return eachLine(self, 1, closure); } /** * Iterates through the given reader line by line. Each line is passed to the * given 1 or 2 arg closure. If the closure has two arguments, the line count is passed * as the second argument. The Reader is closed before this method returns. * * @param self a Reader, closed after the method returns * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure which will be passed each line (or for 2 arg closures the line and line count) * @return the last value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.7 */ public static T eachLine(Reader self, int firstLine, Closure closure) throws IOException { BufferedReader br; int count = firstLine; T result = null; if (self instanceof BufferedReader) br = (BufferedReader) self; else br = new BufferedReader(self); try { while (true) { String line = br.readLine(); if (line == null) { break; } else { result = callClosureForLine(closure, line, count); count++; } } Reader temp = self; self = null; temp.close(); return result; } finally { closeWithWarning(self); closeWithWarning(br); } } /** * Iterates through this file line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a File * @param regex the delimiting regular expression * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.5.5 */ public static T splitEachLine(File self, String regex, Closure closure) throws IOException { return splitEachLine(newReader(self), regex, closure); } /** * Iterates through this file line by line, splitting each line using * the given separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression Pattern. * Finally the resources used for processing the file are closed. * * @param self a File * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(File self, Pattern pattern, Closure closure) throws IOException { return splitEachLine(newReader(self), pattern, closure); } /** * Iterates through this file line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a File * @param regex the delimiting regular expression * @param charset opens the file with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(File self, String regex, String charset, Closure closure) throws IOException { return splitEachLine(newReader(self, charset), regex, closure); } /** * Iterates through this file line by line, splitting each line using * the given regex separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a File * @param pattern the regular expression Pattern for the delimiter * @param charset opens the file with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(File self, Pattern pattern, String charset, Closure closure) throws IOException { return splitEachLine(newReader(self, charset), pattern, closure); } /** * Iterates through the input stream associated with this URL line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the URL are closed. * * @param self a URL to open and read * @param regex the delimiting regular expression * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(URL self, String regex, Closure closure) throws IOException { return splitEachLine(newReader(self), regex, closure); } /** * Iterates through the input stream associated with this URL line by line, splitting each line using * the given regex separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the URL are closed. * * @param self a URL to open and read * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(URL self, Pattern pattern, Closure closure) throws IOException { return splitEachLine(newReader(self), pattern, closure); } /** * Iterates through the input stream associated with this URL line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the URL are closed. * * @param self a URL to open and read * @param regex the delimiting regular expression * @param charset opens the file with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(URL self, String regex, String charset, Closure closure) throws IOException { return splitEachLine(newReader(self, charset), regex, closure); } /** * Iterates through the input stream associated with this URL line by line, splitting each line using * the given regex separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the URL are closed. * * @param self a URL to open and read * @param pattern the regular expression Pattern for the delimiter * @param charset opens the file with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(URL self, Pattern pattern, String charset, Closure closure) throws IOException { return splitEachLine(newReader(self, charset), pattern, closure); } /** * Iterates through the given reader line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. The Reader is closed afterwards. *

      * Here is an example: *

           * def s = 'The 3 quick\nbrown 4 fox'
           * def result = ''
           * new StringReader(s).splitEachLine(/\d/){ parts ->
           *     result += "${parts[0]}_${parts[1]}|"
           * }
           * assert result == 'The _ quick|brown _ fox|'
           * 
      * * @param self a Reader, closed after the method returns * @param regex the delimiting regular expression * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see java.lang.String#split(java.lang.String) * @since 1.5.5 */ public static T splitEachLine(Reader self, String regex, Closure closure) throws IOException { return splitEachLine(self, Pattern.compile(regex), closure); } /** * Iterates through the given reader line by line, splitting each line using * the given regex separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. The Reader is closed afterwards. *

      * Here is an example: *

           * def s = 'The 3 quick\nbrown 4 fox'
           * def result = ''
           * new StringReader(s).splitEachLine(~/\d/){ parts ->
           *     result += "${parts[0]}_${parts[1]}|"
           * }
           * assert result == 'The _ quick|brown _ fox|'
           * 
      * * @param self a Reader, closed after the method returns * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see java.lang.String#split(java.lang.String) * @since 1.6.8 */ public static T splitEachLine(Reader self, Pattern pattern, Closure closure) throws IOException { BufferedReader br; T result = null; if (self instanceof BufferedReader) br = (BufferedReader) self; else br = new BufferedReader(self); try { while (true) { String line = br.readLine(); if (line == null) { break; } else { List vals = Arrays.asList(pattern.split(line)); result = closure.call(vals); } } Reader temp = self; self = null; temp.close(); return result; } finally { closeWithWarning(self); closeWithWarning(br); } } /** * Iterates through the given InputStream line by line using the specified * encoding, splitting each line using the given separator. The list of tokens * for each line is then passed to the given closure. Finally, the stream * is closed. * * @param stream an InputStream * @param regex the delimiting regular expression * @param charset opens the stream with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.5.5 */ public static T splitEachLine(InputStream stream, String regex, String charset, Closure closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure); } /** * Iterates through the given InputStream line by line using the specified * encoding, splitting each line using the given separator Pattern. The list of tokens * for each line is then passed to the given closure. Finally, the stream * is closed. * * @param stream an InputStream * @param pattern the regular expression Pattern for the delimiter * @param charset opens the stream with a specified charset * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(InputStream stream, Pattern pattern, String charset, Closure closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), pattern, closure); } /** * Iterates through the given InputStream line by line, splitting each line using * the given separator. The list of tokens for each line is then passed to * the given closure. The stream is closed before the method returns. * * @param stream an InputStream * @param regex the delimiting regular expression * @param closure a closure * @throws IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) * @since 1.5.6 */ public static T splitEachLine(InputStream stream, String regex, Closure closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream)), regex, closure); } /** * Iterates through the given InputStream line by line, splitting each line using * the given separator Pattern. The list of tokens for each line is then passed to * the given closure. The stream is closed before the method returns. * * @param stream an InputStream * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @throws IOException if an IOException occurs. * @return the last value returned by the closure * @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 1.6.8 */ public static T splitEachLine(InputStream stream, Pattern pattern, Closure closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream)), pattern, closure); } /** * Iterates through the given String line by line, splitting each line using * the given separator. The list of tokens for each line is then passed to * the given closure. * * @param self a String * @param regex the delimiting regular expression * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @see java.lang.String#split(java.lang.String) * @since 1.5.5 */ public static T splitEachLine(String self, String regex, Closure closure) throws IOException { return splitEachLine(self, Pattern.compile(regex), closure); } /** * Iterates through the given CharSequence line by line, splitting each line using * the given separator. The list of tokens for each line is then passed to * the given closure. * * @param self a CharSequence * @param regex the delimiting regular expression * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid * @see #splitEachLine(String, String, Closure) * @since 1.8.2 */ public static T splitEachLine(CharSequence self, CharSequence regex, Closure closure) throws IOException { return splitEachLine(self.toString(), regex.toString(), closure); } /** * Iterates through the given String line by line, splitting each line using * the given separator Pattern. The list of tokens for each line is then passed to * the given closure. * * @param self a String * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @see java.util.regex.Pattern#split(java.lang.CharSequence) * @since 1.6.8 */ public static T splitEachLine(String self, Pattern pattern, Closure closure) throws IOException { final List list = readLines(self); T result = null; for (String line : list) { List vals = Arrays.asList(pattern.split(line)); result = closure.call(vals); } return result; } /** * Iterates through the given CharSequence line by line, splitting each line using * the given separator Pattern. The list of tokens for each line is then passed to * the given closure. * * @param self a CharSequence * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an error occurs * @see #splitEachLine(String, Pattern, Closure) * @since 1.8.2 */ public static T splitEachLine(CharSequence self, Pattern pattern, Closure closure) throws IOException { return splitEachLine(self.toString(), pattern, closure); } /** * Read a single, whole line from the given Reader. * * @param self a Reader * @return a line * @throws IOException if an IOException occurs. * @since 1.0 */ public static String readLine(Reader self) throws IOException { if (self instanceof BufferedReader) { BufferedReader br = (BufferedReader) self; return br.readLine(); } if (self.markSupported()) { return readLineFromReaderWithMark(self); } return readLineFromReaderWithoutMark(self); } private static int charBufferSize = 4096; // half the default stream buffer size private static int expectedLineLength = 160; // double the default line length private static int EOF = -1; // End Of File /* * This method tries to read subsequent buffers from the reader using a mark */ private static String readLineFromReaderWithMark(final Reader input) throws IOException { char[] cbuf = new char[charBufferSize]; try { input.mark(charBufferSize); } catch (IOException e) { // this should never happen LOG.warning("Caught exception setting mark on supporting reader: " + e); // fallback return readLineFromReaderWithoutMark(input); } // could be changed into do..while, but then // we might create an additional StringBuffer // instance at the end of the stream int count = input.read(cbuf); if (count == EOF) // we are at the end of the input data return null; StringBuffer line = new StringBuffer(expectedLineLength); // now work on the buffer(s) int ls = lineSeparatorIndex(cbuf, count); while (ls == -1) { line.append(cbuf, 0, count); count = input.read(cbuf); if (count == EOF) { // we are at the end of the input data return line.toString(); } ls = lineSeparatorIndex(cbuf, count); } line.append(cbuf, 0, ls); // correct ls if we have \r\n int skipLS = 1; if (ls + 1 < count) { // we are not at the end of the buffer if (cbuf[ls] == '\r' && cbuf[ls + 1] == '\n') { skipLS++; } } else { if (cbuf[ls] == '\r' && input.read() == '\n') { skipLS++; } } //reset() and skip over last linesep input.reset(); input.skip(line.length() + skipLS); return line.toString(); } /* * This method reads without a buffer. * It returns too many empty lines if \r\n combinations * are used. Nothing can be done because we can't push * back the character we have just read. */ private static String readLineFromReaderWithoutMark(Reader input) throws IOException { int c = input.read(); if (c == -1) return null; StringBuffer line = new StringBuffer(expectedLineLength); while (c != EOF && c != '\n' && c != '\r') { char ch = (char) c; line.append(ch); c = input.read(); } return line.toString(); } /* * searches for \n or \r * Returns -1 if not found. */ private static int lineSeparatorIndex(char[] array, int length) { for (int k = 0; k < length; k++) { if (isLineSeparator(array[k])) { return k; } } return -1; } /* * true if either \n or \r */ private static boolean isLineSeparator(char c) { return c == '\n' || c == '\r'; } static String lineSeparator = null; /** * Return a String with lines (separated by LF, CR/LF, or CR) * terminated by the platform specific line separator. * * @param self a String object * @return the denormalized string * @since 1.6.0 */ public static String denormalize(final String self) { // Don't do this in static initializer because we may never be needed. // TODO: Put this lineSeparator property somewhere everyone can use it. if (lineSeparator == null) { final StringWriter sw = new StringWriter(2); try { // We use BufferedWriter rather than System.getProperty because // it has the security manager rigamarole to deal with the possible exception. final BufferedWriter bw = new BufferedWriter(sw); bw.newLine(); bw.flush(); lineSeparator = sw.toString(); } catch (IOException ioe) { // This shouldn't happen, but this is the same default used by // BufferedWriter on a security exception. lineSeparator = "\n"; } } final int len = self.length(); if (len < 1) { return self; } final StringBuilder sb = new StringBuilder((110 * len) / 100); int i = 0; while (i < len) { final char ch = self.charAt(i++); switch (ch) { case '\r': sb.append(lineSeparator); // Eat the following LF if any. if ((i < len) && (self.charAt(i) == '\n')) { ++i; } break; case '\n': sb.append(lineSeparator); break; default: sb.append(ch); break; } } return sb.toString(); } /** * Return a CharSequence with lines (separated by LF, CR/LF, or CR) * terminated by the platform specific line separator. * * @param self a CharSequence object * @return the denormalized CharSequence * @see #denormalize(String) * @since 1.8.2 */ public static CharSequence denormalize(final CharSequence self) { return denormalize(self.toString()); } /** * Return a String with linefeeds and carriage returns normalized to linefeeds. * * @param self a String object * @return the normalized string * @since 1.6.0 */ public static String normalize(final String self) { int nx = self.indexOf('\r'); if (nx < 0) { return self; } final int len = self.length(); final StringBuilder sb = new StringBuilder(len); int i = 0; do { sb.append(self, i, nx); sb.append('\n'); if ((i = nx + 1) >= len) break; if (self.charAt(i) == '\n') { // skip the LF in CR LF if (++i >= len) break; } nx = self.indexOf('\r', i); } while (nx > 0); sb.append(self, i, len); return sb.toString(); } /** * Return a CharSequence with linefeeds and carriage returns normalized to linefeeds. * * @param self a CharSequence object * @return the normalized CharSequence * @see #normalize(String) * @since 1.8.2 */ public static CharSequence normalize(final CharSequence self) { return normalize(self.toString()); } /** * Return the lines of a String as a List of Strings. * * @param self a String object * @return a list of lines * @throws java.io.IOException if an error occurs * @since 1.5.5 */ public static List readLines(String self) throws IOException { return readLines(new StringReader(self)); } /** * Return the lines of a CharSequence as a List of CharSequence. * * @param self a CharSequence object * @return a list of lines * @throws java.io.IOException if an error occurs * @since 1.8.2 */ public static List readLines(CharSequence self) throws IOException { return new ArrayList(readLines(self.toString())); } /** * Reads the file into a list of Strings, with one item for each line. * * @param file a File * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.0 */ public static List readLines(File file) throws IOException { return readLines(newReader(file)); } /** * Reads the file into a list of Strings, with one item for each line. * * @param file a File * @param charset opens the file with a specified charset * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.6.8 */ public static List readLines(File file, String charset) throws IOException { return readLines(newReader(file, charset)); } /** * Reads the stream into a list, with one element for each line. * * @param stream a stream * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.0 */ public static List readLines(InputStream stream) throws IOException { return readLines(newReader(stream)); } /** * Reads the stream into a list, with one element for each line. * * @param stream a stream * @param charset opens the stream with a specified charset * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.6.8 */ public static List readLines(InputStream stream, String charset) throws IOException { return readLines(newReader(stream, charset)); } /** * Reads the URL contents into a list, with one element for each line. * * @param self a URL * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.6.8 */ public static List readLines(URL self) throws IOException { return readLines(newReader(self)); } /** * Reads the URL contents into a list, with one element for each line. * * @param self a URL * @param charset opens the URL with a specified charset * @return a List of lines * @throws IOException if an IOException occurs. * @see #readLines(java.io.Reader) * @since 1.6.8 */ public static List readLines(URL self, String charset) throws IOException { return readLines(newReader(self, charset)); } /** * Reads the reader into a list of Strings, with one entry for each line. * The reader is closed before this method returns. * * @param reader a Reader * @return a List of lines * @throws IOException if an IOException occurs. * @since 1.0 */ public static List readLines(Reader reader) throws IOException { IteratorClosureAdapter closure = new IteratorClosureAdapter(reader); eachLine(reader, closure); return closure.asList(); } /** * Read the content of the File using the specified encoding and return it * as a String. * * @param file the file whose content we want to read * @param charset the charset used to read the content of the file * @return a String containing the content of the file * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(File file, String charset) throws IOException { return getText(newReader(file, charset)); } /** * Read the content of the File and returns it as a String. * * @param file the file whose content we want to read * @return a String containing the content of the file * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(File file) throws IOException { return getText(newReader(file)); } /** * Read the content of this URL and returns it as a String. * * @param url URL to read content from * @return the text from that URL * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(URL url) throws IOException { return getText(url, CharsetToolkit.getDefaultSystemCharset().toString()); } /** * Read the content of this URL and returns it as a String. * * @param url URL to read content from * @param parameters connection parameters * @return the text from that URL * @throws IOException if an IOException occurs. * @since 1.8.1 */ public static String getText(URL url, Map parameters) throws IOException { return getText(url, parameters, CharsetToolkit.getDefaultSystemCharset().toString()); } /** * Read the data from this URL and return it as a String. The connection * stream is closed before this method returns. * * @param url URL to read content from * @param charset opens the stream with a specified charset * @return the text from that URL * @throws IOException if an IOException occurs. * @see java.net.URLConnection#getInputStream() * @since 1.0 */ public static String getText(URL url, String charset) throws IOException { BufferedReader reader = newReader(url, charset); return getText(reader); } /** * Read the data from this URL and return it as a String. The connection * stream is closed before this method returns. * * @param url URL to read content from * @param parameters connection parameters * @param charset opens the stream with a specified charset * @return the text from that URL * @throws IOException if an IOException occurs. * @see java.net.URLConnection#getInputStream() * @since 1.8.1 */ public static String getText(URL url, Map parameters, String charset) throws IOException { BufferedReader reader = newReader(url, parameters, charset); return getText(reader); } /** * Read the content of this InputStream and return it as a String. * The stream is closed before this method returns. * * @param is an input stream * @return the text from that URL * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); return getText(reader); } /** * Read the content of this InputStream using specified charset and return * it as a String. The stream is closed before this method returns. * * @param is an input stream * @param charset opens the stream with a specified charset * @return the text from that URL * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(InputStream is, String charset) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset)); return getText(reader); } /** * Read the content of the Reader and return it as a String. The reader * is closed before this method returns. * * @param reader a Reader whose content we want to read * @return a String containing the content of the buffered reader * @throws IOException if an IOException occurs. * @see #getText(java.io.BufferedReader) * @since 1.0 */ public static String getText(Reader reader) throws IOException { BufferedReader bufferedReader = new BufferedReader(reader); return getText(bufferedReader); } /** * Read the content of the BufferedReader and return it as a String. * The BufferedReader is closed afterwards. * * @param reader a BufferedReader whose content we want to read * @return a String containing the content of the buffered reader * @throws IOException if an IOException occurs. * @since 1.0 */ public static String getText(BufferedReader reader) throws IOException { StringBuilder answer = new StringBuilder(); // reading the content of the file within a char buffer // allow to keep the correct line endings char[] charBuffer = new char[8192]; int nbCharRead /* = 0*/; try { while ((nbCharRead = reader.read(charBuffer)) != -1) { // appends buffer answer.append(charBuffer, 0, nbCharRead); } Reader temp = reader; reader = null; temp.close(); } finally { closeWithWarning(reader); } return answer.toString(); } /** * Read the content of the File and returns it as a byte[]. * * @param file the file whose content we want to read * @return a String containing the content of the file * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static byte[] getBytes(File file) throws IOException { return getBytes(new FileInputStream(file)); } /** * Read the content of this URL and returns it as a byte[]. * * @param url URL to read content from * @return the byte[] from that URL * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static byte[] getBytes(URL url) throws IOException { return getBytes(url.openConnection().getInputStream()); } /** * Read the content of this InputStream and return it as a byte[]. * The stream is closed before this method returns. * * @param is an input stream * @return the byte[] from that InputStream * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static byte[] getBytes(InputStream is) throws IOException { ByteArrayOutputStream answer = new ByteArrayOutputStream(); // reading the content of the file within a byte buffer byte[] byteBuffer = new byte[8192]; int nbByteRead /* = 0*/; try { while ((nbByteRead = is.read(byteBuffer)) != -1) { // appends buffer answer.write(byteBuffer, 0, nbByteRead); } } finally { closeWithWarning(is); } return answer.toByteArray(); } /** * Write the bytes from the byte array to the File. * * @param file the file to write to * @param bytes the byte[] to write to the file * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static void setBytes(File file, byte[] bytes) throws IOException { setBytes(new FileOutputStream(file), bytes); } /** * Write the byte[] to the output stream. * The stream is closed before this method returns. * * @param os an output stream * @param bytes the byte[] to write to the output stream * @throws IOException if an IOException occurs. * @since 1.7.1 */ public static void setBytes(OutputStream os, byte[] bytes) throws IOException { try { os.write(bytes); } finally { closeWithWarning(os); } } /** * Write the text and append a newline (using the platform's line-ending). * * @param writer a BufferedWriter * @param line the line to write * @throws IOException if an IOException occurs. * @since 1.0 */ public static void writeLine(BufferedWriter writer, String line) throws IOException { writer.write(line); writer.newLine(); } /** * Write the text to the File. * * @param file a File * @param text the text to write to the File * @throws IOException if an IOException occurs. * @since 1.0 */ public static void write(File file, String text) throws IOException { BufferedWriter writer = null; try { writer = newWriter(file); writer.write(text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * Synonym for write(text) allowing file.text = 'foo'. * * @param file a File * @param text the text to write to the File * @throws IOException if an IOException occurs. * @see #write(java.io.File, java.lang.String) * @since 1.5.1 */ public static void setText(File file, String text) throws IOException { write(file, text); } /** * Synonym for write(text, charset) allowing: *
           * myFile.setText('some text', charset)
           * 
      * or with some help from ExpandoMetaClass, you could do something like: *
           * myFile.metaClass.setText = { String s -> delegate.setText(s, 'UTF-8') }
           * myfile.text = 'some text'
           * 
      * * @param file A File * @param charset The charset used when writing to the file * @param text The text to write to the File * @throws IOException if an IOException occurs. * @see #write(java.io.File, java.lang.String, java.lang.String) * @since 1.7.3 */ public static void setText(File file, String text, String charset) throws IOException { write(file, text, charset); } /** * Write the text to the File. * * @param file a File * @param text the text to write to the File * @return the original file * @throws IOException if an IOException occurs. * @since 1.0 */ public static File leftShift(File file, Object text) throws IOException { append(file, text); return file; } /** * Write bytes to a File. * * @param file a File * @param bytes the byte array to append to the end of the File * @return the original file * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static File leftShift(File file, byte[] bytes) throws IOException { append(file, bytes); return file; } /** * Append binary data to the file. See {@link #append(java.io.File, java.io.InputStream)} * @param file a File * @param data an InputStream of data to write to the file * @return the file * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static File leftShift(File file, InputStream data) throws IOException { append(file, data); return file; } /** * Write the text to the File, using the specified encoding. * * @param file a File * @param text the text to write to the File * @param charset the charset used * @throws IOException if an IOException occurs. * @since 1.0 */ public static void write(File file, String text, String charset) throws IOException { BufferedWriter writer = null; try { writer = newWriter(file, charset); writer.write(text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * Append the text at the end of the File. * * @param file a File * @param text the text to append at the end of the File * @throws IOException if an IOException occurs. * @since 1.0 */ public static void append(File file, Object text) throws IOException { BufferedWriter writer = null; try { writer = newWriter(file, true); InvokerHelper.write(writer, text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * Append bytes to the end of a File. * * @param file a File * @param bytes the byte array to append to the end of the File * @throws IOException if an IOException occurs. * @since 1.5.1 */ public static void append(File file, byte[] bytes) throws IOException { BufferedOutputStream stream = null; try { stream = new BufferedOutputStream( new FileOutputStream(file,true) ); stream.write(bytes, 0, bytes.length); stream.flush(); OutputStream temp = stream; stream = null; temp.close(); } finally { closeWithWarning(stream); } } /** * Append binary data to the file. It will not be * interpreted as text. * @param self a File * @param stream stream to read data from. * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static void append(File self, InputStream stream ) throws IOException { OutputStream out = new FileOutputStream( self, true ); try { leftShift( out, stream ); } finally { closeWithWarning( out ); } } /** * Append the text at the end of the File, using a specified encoding. * * @param file a File * @param text the text to append at the end of the File * @param charset the charset used * @throws IOException if an IOException occurs. * @since 1.0 */ public static void append(File file, Object text, String charset) throws IOException { BufferedWriter writer = null; try { writer = newWriter(file, charset, true); InvokerHelper.write(writer, text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * This method is used to throw useful exceptions when the eachFile* and eachDir closure methods * are used incorrectly. * * @param dir The directory to check * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @since 1.0 */ private static void checkDir(File dir) throws FileNotFoundException, IllegalArgumentException { if (!dir.exists()) throw new FileNotFoundException(dir.getAbsolutePath()); if (!dir.isDirectory()) throw new IllegalArgumentException("The provided File object is not a directory: " + dir.getAbsolutePath()); } /** * Invokes the closure for each 'child' file in this 'parent' folder/directory. * Both regular files and subfolders/subdirectories can be processed depending * on the fileType enum value. * * @param self a file object * @param fileType if normal files or directories or both should be processed * @param closure the closure to invoke * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @since 1.7.1 */ public static void eachFile(final File self, final FileType fileType, final Closure closure) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final File[] files = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (files == null) return; for (File file : files) { if (fileType == FileType.ANY || (fileType != FileType.FILES && file.isDirectory()) || (fileType != FileType.DIRECTORIES && file.isFile())) { closure.call(file); } } } /** * Invokes the closure for each 'child' file in this 'parent' folder/directory. * Both regular files and subfolders/subdirectories are processed. * * @param self a File (that happens to be a folder/directory) * @param closure a closure (first parameter is the 'child' file) * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see java.io.File#listFiles() * @see #eachFile(java.io.File, groovy.io.FileType, groovy.lang.Closure) * @since 1.5.0 */ public static void eachFile(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFile(self, FileType.ANY, closure); } /** * Invokes the closure for each subdirectory in this directory, * ignoring regular files. * * @param self a File (that happens to be a folder/directory) * @param closure a closure (first parameter is the subdirectory file) * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see java.io.File#listFiles() * @see #eachFile(java.io.File, groovy.io.FileType, groovy.lang.Closure) * @since 1.0 */ public static void eachDir(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFile(self, FileType.DIRECTORIES, closure); } /** * Invokes the closure for each descendant file in this directory. * Sub-directories are recursively searched in a depth-first fashion. * Both regular files and subdirectories may be passed to the closure * depending on the value of fileType. * * @param self a file object * @param fileType if normal files or directories or both should be processed * @param closure the closure to invoke on each file * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @since 1.7.1 */ public static void eachFileRecurse(final File self, final FileType fileType, final Closure closure) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final File[] files = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (files == null) return; for (File file : files) { if (file.isDirectory()) { if (fileType != FileType.FILES) closure.call(file); eachFileRecurse(file, fileType, closure); } else if (fileType != FileType.DIRECTORIES) { closure.call(file); } } } /** * Invokes closure for each descendant file in this directory tree. * Sub-directories are recursively traversed as found. * The traversal can be adapted by providing various options in the options Map according * to the following keys:
      *
      type
      A {@link groovy.io.FileType} enum to determine if normal files or directories or both are processed
      *
      preDir
      A {@link groovy.lang.Closure} run before each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing.
      *
      preRoot
      A boolean indicating that the 'preDir' closure should be applied at the root level
      *
      postDir
      A {@link groovy.lang.Closure} run after each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing.
      *
      postRoot
      A boolean indicating that the 'postDir' closure should be applied at the root level
      *
      visitRoot
      A boolean indicating that the given closure should be applied for the root dir * (not applicable if the 'type' is set to {@link groovy.io.FileType#FILES})
      *
      maxDepth
      The maximum number of directory levels when recursing * (default is -1 which means infinite, set to 0 for no recursion)
      *
      filter
      A filter to perform on traversed files/directories (using the {@link #isCase(java.lang.Object, java.lang.Object)} method). If set, * only files/dirs which match are candidates for visiting.
      *
      nameFilter
      A filter to perform on the name of traversed files/directories (using the {@link #isCase(java.lang.Object, java.lang.Object)} method). If set, * only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)
      *
      excludeFilter
      A filter to perform on traversed files/directories (using the {@link #isCase(java.lang.Object, java.lang.Object)} method). * If set, any candidates which match won't be visited.
      *
      excludeNameFilter
      A filter to perform on the names of traversed files/directories (using the {@link #isCase(java.lang.Object, java.lang.Object)} method). * If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)
      *
      sort
      A {@link groovy.lang.Closure} which if set causes the files and subdirectories for each directory to be processed in sorted order. * Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.
      *
      * This example prints out file counts and size aggregates for groovy source files within a directory tree: *
           * def totalSize = 0
           * def count = 0
           * def sortByTypeThenName = { a, b ->
           *     a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
           * }
           * rootDir.traverse(
           *         type         : FILES,
           *         nameFilter   : ~/.*\.groovy/,
           *         preDir       : { if (it.name == '.svn') return SKIP_SUBTREE },
           *         postDir      : { println "Found $count files in $it.name totalling $totalSize bytes"
           *                         totalSize = 0; count = 0 },
           *         postRoot     : true
           *         sort         : sortByTypeThenName
           * ) {it -> totalSize += it.size(); count++ }
           * 
      * * @param self a File * @param options a Map of options to alter the traversal behavior * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory or illegal filter combinations are supplied * @see #sort(java.util.Collection, groovy.lang.Closure) * @see groovy.io.FileVisitResult * @see groovy.io.FileType * @since 1.7.1 */ public static void traverse(final File self, final Map options, final Closure closure) throws FileNotFoundException, IllegalArgumentException { Number maxDepthNumber = asType(options.remove("maxDepth"), Number.class); int maxDepth = maxDepthNumber == null ? -1 : maxDepthNumber.intValue(); Boolean visitRoot = asType(get(options, "visitRoot", false), Boolean.class); Boolean preRoot = asType(get(options, "preRoot", false), Boolean.class); Boolean postRoot = asType(get(options, "postRoot", false), Boolean.class); final Closure pre = (Closure) options.get("preDir"); final Closure post = (Closure) options.get("postDir"); final FileType type = (FileType) options.get("type"); final Object filter = options.get("filter"); final Object nameFilter = options.get("nameFilter"); final Object excludeFilter = options.get("excludeFilter"); final Object excludeNameFilter = options.get("excludeNameFilter"); Object preResult = null; if (preRoot && pre != null) { preResult = pre.call(self); } if (preResult == FileVisitResult.TERMINATE || preResult == FileVisitResult.SKIP_SUBTREE) return; FileVisitResult terminated = traverse(self, options, closure, maxDepth); if (type != FileType.FILES && visitRoot) { if (closure != null && notFiltered(self, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(self); if (closureResult == FileVisitResult.TERMINATE) return; } } if (postRoot && post != null && terminated != FileVisitResult.TERMINATE) post.call(self); } private static boolean notFiltered(File file, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) { if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true; if (filter != null && nameFilter != null) throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'"); if (excludeFilter != null && excludeNameFilter != null) throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'"); Object filterToUse = null; Object filterParam = null; if (filter != null) { filterToUse = filter; filterParam = file; } else if (nameFilter != null) { filterToUse = nameFilter; filterParam = file.getName(); } Object excludeFilterToUse = null; Object excludeParam = null; if (excludeFilter != null) { excludeFilterToUse = excludeFilter; excludeParam = file; } else if (excludeNameFilter != null) { excludeFilterToUse = excludeNameFilter; excludeParam = file.getName(); } final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse); final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse); boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam)); boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam)); return included && !excluded; } /** * Invokes the closure for each descendant file in this directory tree. * Sub-directories are recursively traversed in a depth-first fashion. * Convenience method for {@link #traverse(java.io.File, java.util.Map, groovy.lang.Closure)} when * no options to alter the traversal behavior are required. * * @param self a File * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see #traverse(java.io.File, java.util.Map, groovy.lang.Closure) * @since 1.7.1 */ public static void traverse(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException { traverse(self, new HashMap(), closure); } /** * Invokes the closure specified with key 'visit' in the options Map * for each descendant file in this directory tree. Convenience method * for {@link #traverse(java.io.File, java.util.Map, groovy.lang.Closure)} allowing the 'visit' closure * to be included in the options Map rather than as a parameter. * * @param self a File * @param options a Map of options to alter the traversal behavior * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory or illegal filter combinations are supplied * @see #traverse(java.io.File, java.util.Map, groovy.lang.Closure) * @since 1.7.1 */ public static void traverse(final File self, final Map options) throws FileNotFoundException, IllegalArgumentException { final Closure visit = (Closure) options.remove("visit"); traverse(self, options, visit); } private static FileVisitResult traverse(final File self, final Map options, final Closure closure, final int maxDepth) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final Closure pre = (Closure) options.get("preDir"); final Closure post = (Closure) options.get("postDir"); final FileType type = (FileType) options.get("type"); final Object filter = options.get("filter"); final Object nameFilter = options.get("nameFilter"); final Object excludeFilter = options.get("excludeFilter"); final Object excludeNameFilter = options.get("excludeNameFilter"); final Closure sort = (Closure) options.get("sort"); final File[] origFiles = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (origFiles != null) { List files = Arrays.asList(origFiles); if (sort != null) files = sort(files, sort); for (File file : files) { if (file.isDirectory()) { if (type != FileType.FILES) { if (closure != null && notFiltered(file, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(file); if (closureResult == FileVisitResult.SKIP_SIBLINGS) break; if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } if (maxDepth != 0) { Object preResult = null; if (pre != null) { preResult = pre.call(file); } if (preResult == FileVisitResult.SKIP_SIBLINGS) break; if (preResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; if (preResult != FileVisitResult.SKIP_SUBTREE) { FileVisitResult terminated = traverse(file, options, closure, maxDepth - 1); if (terminated == FileVisitResult.TERMINATE) return terminated; } Object postResult = null; if (post != null) { postResult = post.call(file); } if (postResult == FileVisitResult.SKIP_SIBLINGS) break; if (postResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } else if (type != FileType.DIRECTORIES) { if (closure != null && notFiltered(file, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(file); if (closureResult == FileVisitResult.SKIP_SIBLINGS) break; if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } } } return FileVisitResult.CONTINUE; } /** * Invokes the closure for each descendant file in this directory. * Sub-directories are recursively searched in a depth-first fashion. * Both regular files and subdirectories are passed to the closure. * * @param self a File * @param closure a closure * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see #eachFileRecurse(java.io.File, groovy.io.FileType, groovy.lang.Closure) * @since 1.0 */ public static void eachFileRecurse(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.ANY, closure); } /** * Invokes the closure for each descendant directory of this directory. * Sub-directories are recursively searched in a depth-first fashion. * Only subdirectories are passed to the closure; regular files are ignored. * * @param self a directory * @param closure a closure * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see #eachFileRecurse(java.io.File, groovy.io.FileType, groovy.lang.Closure) * @since 1.5.0 */ public static void eachDirRecurse(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.DIRECTORIES, closure); } /** * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory * - calling the {@link #isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Both regular files and subdirectories may be candidates for matching depending * on the value of fileType. *
           * // collect names of files in baseDir matching supplied regex pattern
           * import static groovy.io.FileType.*
           * def names = []
           * baseDir.eachFileMatch FILES, ~/foo\d\.txt/, { names << it.name }
           * assert names == ['foo1.txt', 'foo2.txt']
           *
           * // remove all *.bak files in baseDir
           * baseDir.eachFileMatch FILES, ~/.*\.bak/, { File bak -> bak.delete() }
           *
           * // print out files > 4K in size from baseDir
           * baseDir.eachFileMatch FILES, { new File(baseDir, it).size() > 4096 }, { println "$it.name ${it.size()}" }
           * 
      * * @param self a file * @param fileType whether normal files or directories or both should be processed * @param nameFilter the filter to perform on the name of the file/directory (using the {@link #isCase(java.lang.Object, java.lang.Object)} method) * @param closure the closure to invoke * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @since 1.7.1 */ public static void eachFileMatch(final File self, final FileType fileType, final Object nameFilter, final Closure closure) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final File[] files = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (files == null) return; final MetaClass metaClass = InvokerHelper.getMetaClass(nameFilter); for (final File currentFile : files) { if ((fileType != FileType.FILES && currentFile.isDirectory()) || (fileType != FileType.DIRECTORIES && currentFile.isFile())) { if (DefaultTypeTransformation.castToBoolean(metaClass.invokeMethod(nameFilter, "isCase", currentFile.getName()))) closure.call(currentFile); } } } /** * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory * - calling the {@link #isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Both regular files and subdirectories are matched. * * @param self a file * @param nameFilter the nameFilter to perform on the name of the file (using the {@link #isCase(java.lang.Object, java.lang.Object)} method) * @param closure the closure to invoke * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see #eachFileMatch(java.io.File, groovy.io.FileType, java.lang.Object, groovy.lang.Closure) * @since 1.5.0 */ public static void eachFileMatch(final File self, final Object nameFilter, final Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFileMatch(self, FileType.ANY, nameFilter, closure); } /** * Invokes the closure for each subdirectory whose name (dir.name) matches the given nameFilter in the given directory * - calling the {@link #isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Only subdirectories are matched; regular files are ignored. * * @param self a file * @param nameFilter the nameFilter to perform on the name of the directory (using the {@link #isCase(java.lang.Object, java.lang.Object)} method) * @param closure the closure to invoke * @throws FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided File object does not represent a directory * @see #eachFileMatch(java.io.File, groovy.io.FileType, java.lang.Object, groovy.lang.Closure) * @since 1.5.0 */ public static void eachDirMatch(final File self, final Object nameFilter, final Closure closure) throws FileNotFoundException, IllegalArgumentException { eachFileMatch(self, FileType.DIRECTORIES, nameFilter, closure); } /** * Deletes a directory with all contained files and subdirectories. *

      The method returns *

        *
      • true, when deletion was successful
      • *
      • true, when it is called for a non existing directory
      • *
      • false, when it is called for a file which isn't a directory
      • *
      • false, when directory couldn't be deleted
      • *
      *

      * * @param self a File * @return true if the file doesn't exist or deletion was successful * @since 1.6.0 */ public static boolean deleteDir(final File self) { if (!self.exists()) return true; if (!self.isDirectory()) return false; File[] files = self.listFiles(); if (files == null) // couldn't access files return false; // delete contained files boolean result = true; for (File file : files) { if (file.isDirectory()) { if (!deleteDir(file)) result = false; } else { if (!file.delete()) result = false; } } // now delete directory itself if(!self.delete()) result = false; return result; } /** * Renames the file. It's a shortcut for {@link java.io.File#renameTo(File)} * * @param self a File * @param newPathName The new pathname for the named file * @return true if and only if the renaming succeeded; * false otherwise * @since 1.7.4 */ public static boolean renameTo(final File self, String newPathName) { return self.renameTo(new File(newPathName)); } /** * Allows a simple syntax for using timers. This timer will execute the * given closure after the given delay. * * @param timer a timer object * @param delay the delay in milliseconds before running the closure code * @param closure the closure to invoke * @return The timer task which has been scheduled. * @since 1.5.0 */ public static TimerTask runAfter(Timer timer, int delay, final Closure closure) { TimerTask timerTask = new TimerTask() { public void run() { closure.call(); } }; timer.schedule(timerTask, delay); return timerTask; } /** * Create a buffered reader for this file. * * @param file a File * @return a BufferedReader * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedReader newReader(File file) throws IOException { CharsetToolkit toolkit = new CharsetToolkit(file); return toolkit.getReader(); } /** * Create a buffered reader for this file, using the specified * charset as the encoding. * * @param file a File * @param charset the charset for this File * @return a BufferedReader * @throws FileNotFoundException if the File was not found * @throws UnsupportedEncodingException if the encoding specified is not supported * @since 1.0 */ public static BufferedReader newReader(File file, String charset) throws FileNotFoundException, UnsupportedEncodingException { return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); } /** * Creates a reader for this input stream. * * @param self an input stream * @return a reader * @since 1.0 */ public static BufferedReader newReader(InputStream self) { return new BufferedReader(new InputStreamReader(self)); } /** * Creates a reader for this input stream, using the specified * charset as the encoding. * * @param self an input stream * @param charset the charset for this input stream * @return a reader * @throws UnsupportedEncodingException if the encoding specified is not supported * @since 1.6.0 */ public static BufferedReader newReader(InputStream self, String charset) throws UnsupportedEncodingException { return new BufferedReader(new InputStreamReader(self, charset)); } /** * Create a new BufferedReader for this file and then * passes it into the closure, ensuring the reader is closed after the * closure returns. * * @param file a file object * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withReader(File file, Closure closure) throws IOException { return withReader(newReader(file), closure); } /** * Create a new BufferedReader for this file using the specified charset and then * passes it into the closure, ensuring the reader is closed after the * closure returns. * * @param file a file object * @param charset the charset for this input stream * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.6.0 */ public static T withReader(File file, String charset, Closure closure) throws IOException { return withReader(newReader(file, charset), closure); } /** * Create a buffered output stream for this file. * * @param file a file object * @return the created OutputStream * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedOutputStream newOutputStream(File file) throws IOException { return new BufferedOutputStream(new FileOutputStream(file)); } /** * Creates a new data output stream for this file. * * @param file a file object * @return the created DataOutputStream * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static DataOutputStream newDataOutputStream(File file) throws IOException { return new DataOutputStream(new FileOutputStream(file)); } /** * Creates a new OutputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.OutputStream, groovy.lang.Closure) * @since 1.5.2 */ public static Object withOutputStream(File file, Closure closure) throws IOException { return withStream(newOutputStream(file), closure); } /** * Create a new InputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.2 */ public static Object withInputStream(File file, Closure closure) throws IOException { return withStream(newInputStream(file), closure); } /** * Creates a new InputStream for this URL and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param url a URL * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.2 */ public static T withInputStream(URL url, Closure closure) throws IOException { return withStream(newInputStream(url), closure); } /** * Create a new DataOutputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.OutputStream, groovy.lang.Closure) * @since 1.5.2 */ public static T withDataOutputStream(File file, Closure closure) throws IOException { return withStream(newDataOutputStream(file), closure); } /** * Create a new DataInputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withStream(java.io.InputStream, groovy.lang.Closure) * @since 1.5.2 */ public static T withDataInputStream(File file, Closure closure) throws IOException { return withStream(newDataInputStream(file), closure); } /** * Create a buffered writer for this file. * * @param file a File * @return a BufferedWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedWriter newWriter(File file) throws IOException { return new BufferedWriter(new FileWriter(file)); } /** * Creates a buffered writer for this file, optionally appending to the * existing file content. * * @param file a File * @param append true if data should be appended to the file * @return a BufferedWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedWriter newWriter(File file, boolean append) throws IOException { return new BufferedWriter(new FileWriter(file, append)); } /** * Helper method to create a buffered writer for a file. If the given * charset is "UTF-16BE" or "UTF-16LE", the requisite byte order mark is * written to the stream before the writer is returned. * * @param file a File * @param charset the name of the encoding used to write in this file * @param append true if in append mode * @return a BufferedWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedWriter newWriter(File file, String charset, boolean append) throws IOException { if (append) { return new EncodingAwareBufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), charset)); } else { // first write the Byte Order Mark for Unicode encodings FileOutputStream stream = new FileOutputStream(file); if ("UTF-16BE".equals(charset)) { writeUtf16Bom(stream, true); } else if ("UTF-16LE".equals(charset)) { writeUtf16Bom(stream, false); } return new EncodingAwareBufferedWriter(new OutputStreamWriter(stream, charset)); } } /** * Creates a buffered writer for this file, writing data using the given * encoding. * * @param file a File * @param charset the name of the encoding used to write in this file * @return a BufferedWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static BufferedWriter newWriter(File file, String charset) throws IOException { return newWriter(file, charset, false); } /** * Write a Byte Order Mark at the beginning of the file * * @param stream the FileOutputStream to write the BOM to * @param bigEndian true if UTF 16 Big Endian or false if Low Endian * @throws IOException if an IOException occurs. * @since 1.0 */ private static void writeUtf16Bom(FileOutputStream stream, boolean bigEndian) throws IOException { if (bigEndian) { stream.write(-2); stream.write(-1); } else { stream.write(-1); stream.write(-2); } } /** * Creates a new BufferedWriter for this file, passes it to the closure, and * ensures the stream is flushed and closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withWriter(File file, Closure closure) throws IOException { return withWriter(newWriter(file), closure); } /** * Creates a new BufferedWriter for this file, passes it to the closure, and * ensures the stream is flushed and closed after the closure returns. * The writer will use the given charset encoding. * * @param file a File * @param charset the charset used * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withWriter(File file, String charset, Closure closure) throws IOException { return withWriter(newWriter(file, charset), closure); } /** * Create a new BufferedWriter which will append to this * file. The writer is passed to the closure and will be closed before * this method returns. * * @param file a File * @param charset the charset used * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withWriterAppend(File file, String charset, Closure closure) throws IOException { return withWriter(newWriter(file, charset, true), closure); } /** * Create a new BufferedWriter for this file in append mode. The writer * is passed to the closure and is closed after the closure returns. * * @param file a File * @param closure a closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withWriterAppend(File file, Closure closure) throws IOException { return withWriter(newWriter(file, true), closure); } /** * Create a new PrintWriter for this file. * * @param file a File * @return the created PrintWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static PrintWriter newPrintWriter(File file) throws IOException { return new GroovyPrintWriter(newWriter(file)); } /** * Create a new PrintWriter for this file, using specified * charset. * * @param file a File * @param charset the charset * @return a PrintWriter * @throws IOException if an IOException occurs. * @since 1.0 */ public static PrintWriter newPrintWriter(File file, String charset) throws IOException { return new GroovyPrintWriter(newWriter(file, charset)); } /** * Create a new PrintWriter for this file, using specified * charset. * * @param writer a writer * @return a PrintWriter * @since 1.6.0 */ public static PrintWriter newPrintWriter(Writer writer) { return new GroovyPrintWriter(writer); } /** * Create a new PrintWriter for this file which is then * passed it into the given closure. This method ensures its the writer * is closed after the closure returns. * * @param file a File * @param closure the closure to invoke with the PrintWriter * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withPrintWriter(File file, Closure closure) throws IOException { return withWriter(newPrintWriter(file), closure); } /** * Create a new PrintWriter with a specified charset for * this file. The writer is passed to the closure, and will be closed * before this method returns. * * @param file a File * @param charset the charset * @param closure the closure to invoke with the PrintWriter * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withPrintWriter(File file, String charset, Closure closure) throws IOException { return withWriter(newPrintWriter(file, charset), closure); } /** * Create a new PrintWriter with a specified charset for * this file. The writer is passed to the closure, and will be closed * before this method returns. * * @param writer a writer * @param closure the closure to invoke with the PrintWriter * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.6.0 */ public static T withPrintWriter(Writer writer, Closure closure) throws IOException { return withWriter(newPrintWriter(writer), closure); } /** * Allows this writer to be used within the closure, ensuring that it * is flushed and closed before this method returns. * * @param writer the writer which is used and then closed * @param closure the closure that the writer is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withWriter(Writer writer, Closure closure) throws IOException { try { T result = closure.call(writer); try { writer.flush(); } catch (IOException e) { // try to continue even in case of error } Writer temp = writer; writer = null; temp.close(); return result; } finally { closeWithWarning(writer); } } /** * Allows this reader to be used within the closure, ensuring that it * is closed before this method returns. * * @param reader the reader which is used and then closed * @param closure the closure that the writer is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withReader(Reader reader, Closure closure) throws IOException { try { T result = closure.call(reader); Reader temp = reader; reader = null; temp.close(); return result; } finally { closeWithWarning(reader); } } /** * Allows this input stream to be used within the closure, ensuring that it * is flushed and closed before this method returns. * * @param stream the stream which is used and then closed * @param closure the closure that the stream is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withStream(InputStream stream, Closure closure) throws IOException { try { T result = closure.call(stream); InputStream temp = stream; stream = null; temp.close(); return result; } finally { closeWithWarning(stream); } } /** * Helper method to create a new BufferedReader for a URL and then * passes it to the closure. The reader is closed after the closure returns. * * @param url a URL * @param closure the closure to invoke with the reader * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withReader(URL url, Closure closure) throws IOException { return withReader(url.openConnection().getInputStream(), closure); } /** * Helper method to create a new Reader for a URL and then * passes it to the closure. The reader is closed after the closure returns. * * @param url a URL * @param charset the charset used * @param closure the closure to invoke with the reader * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.6 */ public static T withReader(URL url, String charset, Closure closure) throws IOException { return withReader(url.openConnection().getInputStream(), charset, closure); } /** * Helper method to create a new Reader for a stream and then * passes it into the closure. The reader (and this stream) is closed after * the closure returns. * * @see java.io.InputStreamReader * @param in a stream * @param closure the closure to invoke with the InputStream * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withReader(InputStream in, Closure closure) throws IOException { return withReader(new InputStreamReader(in), closure); } /** * Helper method to create a new Reader for a stream and then * passes it into the closure. The reader (and this stream) is closed after * the closure returns. * * @see java.io.InputStreamReader * @param in a stream * @param charset the charset used to decode the stream * @param closure the closure to invoke with the reader * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.6 */ public static T withReader(InputStream in, String charset, Closure closure) throws IOException { return withReader(new InputStreamReader(in, charset), closure); } /** * Creates a writer from this stream, passing it to the given closure. * This method ensures the stream is closed after the closure returns. * * @param stream the stream which is used and then closed * @param closure the closure that the writer is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withWriter(java.io.Writer, groovy.lang.Closure) * @since 1.5.2 */ public static T withWriter(OutputStream stream, Closure closure) throws IOException { return withWriter(new OutputStreamWriter(stream), closure); } /** * Creates a writer from this stream, passing it to the given closure. * This method ensures the stream is closed after the closure returns. * * @param stream the stream which is used and then closed * @param charset the charset used * @param closure the closure that the writer is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @see #withWriter(java.io.Writer, groovy.lang.Closure) * @since 1.5.2 */ public static T withWriter(OutputStream stream, String charset, Closure closure) throws IOException { return withWriter(new OutputStreamWriter(stream, charset), closure); } /** * Passes this OutputStream to the closure, ensuring that the stream * is closed after the closure returns, regardless of errors. * * @param os the stream which is used and then closed * @param closure the closure that the stream is passed into * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withStream(OutputStream os, Closure closure) throws IOException { try { T result = closure.call(os); os.flush(); OutputStream temp = os; os = null; temp.close(); return result; } finally { closeWithWarning(os); } } /** * Creates a buffered input stream for this file. * * @param file a File * @return a BufferedInputStream of the file * @throws FileNotFoundException if the file is not found. * @since 1.0 */ public static BufferedInputStream newInputStream(File file) throws FileNotFoundException { return new BufferedInputStream(new FileInputStream(file)); } /** * Creates an inputstream for this URL, with the possibility to set different connection parameters using the * parameters map: *
        *
      • connectTimeout : the connection timeout
      • *
      • readTimeout : the read timeout
      • *
      • useCaches : set the use cache property for the URL connection
      • *
      • allowUserInteraction : set the user interaction flag for the URL connection
      • *
      • requestProperties : a map of properties to be passed to the URL connection
      • *
      * @param parameters an optional map specifying part or all of supported connection parameters * @param url the url for which to create the inputstream * @return an InputStream from the underlying URLConnection * @throws IOException if an I/O error occurs while creating the input stream * @since 1.8.1 */ private static InputStream configuredInputStream(Map parameters, URL url) throws IOException { final URLConnection connection = url.openConnection(); if (parameters!=null) { if (parameters.containsKey("connectTimeout")) { connection.setConnectTimeout(asType(parameters.get("connectTimeout"), Integer.class)); } if (parameters.containsKey("readTimeout")) { connection.setReadTimeout(asType(parameters.get("readTimeout"), Integer.class)); } if (parameters.containsKey("useCaches")) { connection.setUseCaches(asType(parameters.get("useCaches"), Boolean.class)); } if (parameters.containsKey("allowUserInteraction")) { connection.setAllowUserInteraction(asType(parameters.get("allowUserInteraction"), Boolean.class)); } if (parameters.containsKey("requestProperties")) { @SuppressWarnings("unchecked") Map properties = (Map) parameters.get("requestProperties"); for (Map.Entry entry : properties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } } return connection.getInputStream(); } /** * Creates a buffered input stream for this URL. * * @param url a URL * @return a BufferedInputStream for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.5.2 */ public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException { return new BufferedInputStream(configuredInputStream(null, url)); } /** * Creates a buffered input stream for this URL. * * @param url a URL * @param parameters connection parameters * @return a BufferedInputStream for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.8.1 */ public static BufferedInputStream newInputStream(URL url, Map parameters) throws MalformedURLException, IOException { return new BufferedInputStream(configuredInputStream(parameters, url)); } /** * Creates a buffered reader for this URL. * * @param url a URL * @return a BufferedReader for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.5.5 */ public static BufferedReader newReader(URL url) throws MalformedURLException, IOException { return newReader(configuredInputStream(null, url)); } /** * Creates a buffered reader for this URL. * * @param url a URL * @param parameters connection parameters * @return a BufferedReader for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.8.1 */ public static BufferedReader newReader(URL url, Map parameters) throws MalformedURLException, IOException { return newReader(configuredInputStream(parameters, url)); } /** * Creates a buffered reader for this URL using the given encoding. * * @param url a URL * @param charset opens the stream with a specified charset * @return a BufferedReader for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.5.5 */ public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException { return new BufferedReader(new InputStreamReader(configuredInputStream(null, url), charset)); } /** * Creates a buffered reader for this URL using the given encoding. * * @param url a URL * @param parameters connection parameters * @param charset opens the stream with a specified charset * @return a BufferedReader for the URL * @throws MalformedURLException is thrown if the URL is not well formed * @throws IOException if an I/O error occurs while creating the input stream * @since 1.8.1 */ public static BufferedReader newReader(URL url, Map parameters, String charset) throws MalformedURLException, IOException { return new BufferedReader(new InputStreamReader(configuredInputStream(parameters, url), charset)); } /** * Create a data input stream for this file * * @param file a File * @return a DataInputStream of the file * @throws FileNotFoundException if the file is not found. * @since 1.5.0 */ public static DataInputStream newDataInputStream(File file) throws FileNotFoundException { return new DataInputStream(new FileInputStream(file)); } /** * Traverse through each byte of this File * * @param self a File * @param closure a closure * @throws IOException if an IOException occurs. * @see #eachByte(java.io.InputStream, groovy.lang.Closure) * @since 1.0 */ public static void eachByte(File self, Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); eachByte(is, closure); } /** * Traverse through the bytes of this File, bufferLen bytes at a time. * * @param self a File * @param bufferLen the length of the buffer to use. * @param closure a 2 parameter closure which is passed the byte[] and a number of bytes successfully read. * @throws IOException if an IOException occurs. * @see #eachByte(java.io.InputStream, int, groovy.lang.Closure) * @since 1.7.4 */ public static void eachByte(File self, int bufferLen, Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); eachByte(is, bufferLen, closure); } /** * Traverse through each byte of this Byte array. Alias for each. * * @param self a Byte array * @param closure a closure * @see #each(java.lang.Object, groovy.lang.Closure) * @since 1.5.5 */ public static void eachByte(Byte[] self, Closure closure) { each(self, closure); } /** * Traverse through each byte of this byte array. Alias for each. * * @param self a byte array * @param closure a closure * @see #each(java.lang.Object, groovy.lang.Closure) * @since 1.5.5 */ public static void eachByte(byte[] self, Closure closure) { each(self, closure); } /** * Traverse through each byte of the specified stream. The * stream is closed after the closure returns. * * @param is stream to iterate over, closed after the method call * @param closure closure to apply to each byte * @throws IOException if an IOException occurs. * @since 1.0 */ public static void eachByte(InputStream is, Closure closure) throws IOException { try { while (true) { int b = is.read(); if (b == -1) { break; } else { closure.call((byte) b); } } InputStream temp = is; is = null; temp.close(); } finally { closeWithWarning(is); } } /** * Traverse through each the specified stream reading bytes into a buffer * and calling the 2 parameter closure with this buffer and the number of bytes. * * @param is stream to iterate over, closed after the method call. * @param bufferLen the length of the buffer to use. * @param closure a 2 parameter closure which is passed the byte[] and a number of bytes successfully read. * @throws IOException if an IOException occurs. * @since 1.8 */ public static void eachByte(InputStream is, int bufferLen, Closure closure) throws IOException { byte[] buffer = new byte[ bufferLen ] ; int bytesRead = 0 ; try { while ( ( bytesRead = is.read( buffer, 0, bufferLen ) ) > 0 ) { closure.call( new Object[]{ buffer, bytesRead } ) ; } InputStream temp = is; is = null; temp.close(); } finally { closeWithWarning(is); } } /** * Reads the InputStream from this URL, passing each byte to the given * closure. The URL stream will be closed before this method returns. * * @param url url to iterate over * @param closure closure to apply to each byte * @throws IOException if an IOException occurs. * @see #eachByte(java.io.InputStream, groovy.lang.Closure) * @since 1.0 */ public static void eachByte(URL url, Closure closure) throws IOException { InputStream is = url.openConnection().getInputStream(); eachByte(is, closure); } /** * Reads the InputStream from this URL, passing a byte[] and a number of bytes * to the given closure. The URL stream will be closed before this method returns. * * @param url url to iterate over * @param bufferLen the length of the buffer to use. * @param closure a 2 parameter closure which is passed the byte[] and a number of bytes successfully read. * @throws IOException if an IOException occurs. * @see #eachByte(java.io.InputStream, int, groovy.lang.Closure) * @since 1.8 */ public static void eachByte(URL url, int bufferLen, Closure closure) throws IOException { InputStream is = url.openConnection().getInputStream(); eachByte(is, bufferLen, closure); } /** * Transforms each character from this reader by passing it to the given * closure. The Closure should return each transformed character, which * will be passed to the Writer. The reader and writer will be both be * closed before this method returns. * * @param self a Reader object * @param writer a Writer to receive the transformed characters * @param closure a closure that performs the required transformation * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static void transformChar(Reader self, Writer writer, Closure closure) throws IOException { int c; try { char[] chars = new char[1]; while ((c = self.read()) != -1) { chars[0] = (char) c; writer.write((String) closure.call(new String(chars))); } writer.flush(); Writer temp2 = writer; writer = null; temp2.close(); Reader temp1 = self; self = null; temp1.close(); } finally { closeWithWarning(self); closeWithWarning(writer); } } /** * Transforms the lines from a reader with a Closure and * write them to a writer. Both Reader and Writer are * closed after the operation. * * @param reader Lines of text to be transformed. Reader is closed afterwards. * @param writer Where transformed lines are written. Writer is closed afterwards. * @param closure Single parameter closure that is called to transform each line of * text from the reader, before writing it to the writer. * @throws IOException if an IOException occurs. * @since 1.0 */ public static void transformLine(Reader reader, Writer writer, Closure closure) throws IOException { BufferedReader br = new BufferedReader(reader); BufferedWriter bw = new BufferedWriter(writer); String line; try { while ((line = br.readLine()) != null) { Object o = closure.call(line); if (o != null) { bw.write(o.toString()); bw.newLine(); } } bw.flush(); Writer temp2 = writer; writer = null; temp2.close(); Reader temp1 = reader; reader = null; temp1.close(); } finally { closeWithWarning(br); closeWithWarning(reader); closeWithWarning(bw); closeWithWarning(writer); } } /** * Filter the lines from a reader and write them on the writer, * according to a closure which returns true if the line should be included. * Both Reader and Writer are closed after the operation. * * @param reader a reader, closed after the call * @param writer a writer, closed after the call * @param closure the closure which returns booleans * @throws IOException if an IOException occurs. * @since 1.0 */ public static void filterLine(Reader reader, Writer writer, Closure closure) throws IOException { BufferedReader br = new BufferedReader(reader); BufferedWriter bw = new BufferedWriter(writer); String line; try { while ((line = br.readLine()) != null) { if (DefaultTypeTransformation.castToBoolean(closure.call(line))) { bw.write(line); bw.newLine(); } } bw.flush(); Writer temp2 = writer; writer = null; temp2.close(); Reader temp1 = reader; reader = null; temp1.close(); } finally { closeWithWarning(br); closeWithWarning(reader); closeWithWarning(bw); closeWithWarning(writer); } } /** * Filters the lines of a File and creates a Writable in return to * stream the filtered lines. * * @param self a File * @param closure a closure which returns a boolean indicating to filter * the line or not * @return a Writable closure * @throws IOException if self is not readable * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.0 */ public static Writable filterLine(File self, Closure closure) throws IOException { return filterLine(newReader(self), closure); } /** * Filters the lines of a File and creates a Writable in return to * stream the filtered lines. * * @param self a File * @param charset opens the file with a specified charset * @param closure a closure which returns a boolean indicating to filter * the line or not * @return a Writable closure * @throws IOException if an IOException occurs * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.6.8 */ public static Writable filterLine(File self, String charset, Closure closure) throws IOException { return filterLine(newReader(self, charset), closure); } /** * Filter the lines from this File, and write them to the given writer based * on the given closure predicate. * * @param self a File * @param writer a writer destination to write filtered lines to * @param closure a closure which takes each line as a parameter and returns * true if the line should be written to this writer. * @throws IOException if self is not readable * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.0 */ public static void filterLine(File self, Writer writer, Closure closure) throws IOException { filterLine(newReader(self), writer, closure); } /** * Filter the lines from this File, and write them to the given writer based * on the given closure predicate. * * @param self a File * @param writer a writer destination to write filtered lines to * @param charset opens the file with a specified charset * @param closure a closure which takes each line as a parameter and returns * true if the line should be written to this writer. * @throws IOException if an IO error occurs * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.6.8 */ public static void filterLine(File self, Writer writer, String charset, Closure closure) throws IOException { filterLine(newReader(self, charset), writer, closure); } /** * Filter the lines from this Reader, and return a Writable which can be * used to stream the filtered lines to a destination. The closure should * return true if the line should be passed to the writer. * * @param reader this reader * @param closure a closure used for filtering * @return a Writable which will use the closure to filter each line * from the reader when the Writable#writeTo(Writer) is called. * @since 1.0 */ public static Writable filterLine(Reader reader, final Closure closure) { final BufferedReader br = new BufferedReader(reader); return new Writable() { public Writer writeTo(Writer out) throws IOException { BufferedWriter bw = new BufferedWriter(out); String line; while ((line = br.readLine()) != null) { if (DefaultTypeTransformation.castToBoolean(closure.call(line))) { bw.write(line); bw.newLine(); } } bw.flush(); return out; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new StringWriterIOException(e); } return buffer.toString(); } }; } /** * Filter lines from an input stream using a closure predicate. The closure * will be passed each line as a String, and it should return * true if the line should be passed to the writer. * * @param self an input stream * @param predicate a closure which returns boolean and takes a line * @return a writable which writes out the filtered lines * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.0 */ public static Writable filterLine(InputStream self, Closure predicate) { return filterLine(newReader(self), predicate); } /** * Filter lines from an input stream using a closure predicate. The closure * will be passed each line as a String, and it should return * true if the line should be passed to the writer. * * @param self an input stream * @param charset opens the stream with a specified charset * @param predicate a closure which returns boolean and takes a line * @return a writable which writes out the filtered lines * @throws UnsupportedEncodingException if the encoding specified is not supported * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.6.8 */ public static Writable filterLine(InputStream self, String charset, Closure predicate) throws UnsupportedEncodingException { return filterLine(newReader(self, charset), predicate); } /** * Uses a closure to filter lines from this InputStream and pass them to * the given writer. The closure will be passed each line as a String, and * it should return true if the line should be passed to the * writer. * * @param self the InputStream * @param writer a writer to write output to * @param predicate a closure which returns true if a line should be accepted * @throws IOException if an IOException occurs. * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.0 */ public static void filterLine(InputStream self, Writer writer, Closure predicate) throws IOException { filterLine(newReader(self), writer, predicate); } /** * Uses a closure to filter lines from this InputStream and pass them to * the given writer. The closure will be passed each line as a String, and * it should return true if the line should be passed to the * writer. * * @param self the InputStream * @param writer a writer to write output to * @param charset opens the stream with a specified charset * @param predicate a closure which returns true if a line should be accepted * @throws IOException if an IOException occurs. * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.6.8 */ public static void filterLine(InputStream self, Writer writer, String charset, Closure predicate) throws IOException { filterLine(newReader(self, charset), writer, predicate); } /** * Filter lines from a URL using a closure predicate. The closure * will be passed each line as a String, and it should return * true if the line should be passed to the writer. * * @param self a URL * @param predicate a closure which returns boolean and takes a line * @return a writable which writes out the filtered lines * @throws IOException if an IO exception occurs * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.6.8 */ public static Writable filterLine(URL self, Closure predicate) throws IOException { return filterLine(newReader(self), predicate); } /** * Filter lines from a URL using a closure predicate. The closure * will be passed each line as a String, and it should return * true if the line should be passed to the writer. * * @param self the URL * @param charset opens the URL with a specified charset * @param predicate a closure which returns boolean and takes a line * @return a writable which writes out the filtered lines * @throws IOException if an IO exception occurs * @see #filterLine(java.io.Reader, groovy.lang.Closure) * @since 1.6.8 */ public static Writable filterLine(URL self, String charset, Closure predicate) throws IOException { return filterLine(newReader(self, charset), predicate); } /** * Uses a closure to filter lines from this URL and pass them to * the given writer. The closure will be passed each line as a String, and * it should return true if the line should be passed to the * writer. * * @param self the URL * @param writer a writer to write output to * @param predicate a closure which returns true if a line should be accepted * @throws IOException if an IOException occurs. * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.6.8 */ public static void filterLine(URL self, Writer writer, Closure predicate) throws IOException { filterLine(newReader(self), writer, predicate); } /** * Uses a closure to filter lines from this URL and pass them to * the given writer. The closure will be passed each line as a String, and * it should return true if the line should be passed to the * writer. * * @param self the URL * @param writer a writer to write output to * @param charset opens the URL with a specified charset * @param predicate a closure which returns true if a line should be accepted * @throws IOException if an IOException occurs. * @see #filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 1.6.8 */ public static void filterLine(URL self, Writer writer, String charset, Closure predicate) throws IOException { filterLine(newReader(self, charset), writer, predicate); } /** * Reads the content of the file into a byte array. * * @param file a File * @return a byte array with the contents of the file. * @throws IOException if an IOException occurs. * @since 1.0 */ public static byte[] readBytes(File file) throws IOException { byte[] bytes = new byte[(int) file.length()]; FileInputStream fileInputStream = new FileInputStream(file); DataInputStream dis = new DataInputStream(fileInputStream); try { dis.readFully(bytes); InputStream temp = dis; dis = null; temp.close(); } finally { closeWithWarning(dis); } return bytes; } // ================================ // Socket and ServerSocket methods /** * Passes the Socket's InputStream and OutputStream to the closure. The * streams will be closed after the closure returns, even if an exception * is thrown. * * @param socket a Socket * @param closure a Closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.2 */ public static T withStreams(Socket socket, Closure closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); try { T result = closure.call(new Object[]{input, output}); InputStream temp1 = input; input = null; temp1.close(); OutputStream temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(input); closeWithWarning(output); } } /** * Creates an InputObjectStream and an OutputObjectStream from a Socket, and * passes them to the closure. The streams will be closed after the closure * returns, even if an exception is thrown. * * @param socket this Socket * @param closure a Closure * @return the value returned by the closure * @throws IOException if an IOException occurs. * @since 1.5.0 */ public static T withObjectStreams(Socket socket, Closure closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(output); ObjectInputStream ois = new ObjectInputStream(input); try { T result = closure.call(new Object[]{ois, oos}); InputStream temp1 = ois; ois = null; temp1.close(); temp1 = input; input = null; temp1.close(); OutputStream temp2 = oos; oos = null; temp2.close(); temp2 = output; output = null; temp2.close(); return result; } finally { closeWithWarning(ois); closeWithWarning(input); closeWithWarning(oos); closeWithWarning(output); } } /** * Overloads the left shift operator to provide an append mechanism to * add things to the output stream of a socket * * @param self a Socket * @param value a value to append * @return a Writer * @throws IOException if an IOException occurs. * @since 1.0 */ public static Writer leftShift(Socket self, Object value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Overloads the left shift operator to provide an append mechanism * to add bytes to the output stream of a socket * * @param self a Socket * @param value a value to append * @return an OutputStream * @throws IOException if an IOException occurs. * @since 1.0 */ public static OutputStream leftShift(Socket self, byte[] value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Accepts a connection and passes the resulting Socket to the closure * which runs in a new Thread. * * @param serverSocket a ServerSocket * @param closure a Closure * @return a Socket * @throws IOException if an IOException occurs. * @see java.net.ServerSocket#accept() * @since 1.0 */ public static Socket accept(ServerSocket serverSocket, final Closure closure) throws IOException { return accept(serverSocket, true, closure); } /** * Accepts a connection and passes the resulting Socket to the closure * which runs in a new Thread or the calling thread, as needed. * * @param serverSocket a ServerSocket * @param runInANewThread This flag should be true, if the closure should be invoked in a new thread, else false. * @param closure a Closure * @return a Socket * @throws IOException if an IOException occurs. * @see java.net.ServerSocket#accept() * @since 1.7.6 */ public static Socket accept(ServerSocket serverSocket, final boolean runInANewThread, final Closure closure) throws IOException { final Socket socket = serverSocket.accept(); if(runInANewThread) { new Thread(new Runnable() { public void run() { invokeClosureWithSocket(socket, closure); } }).start(); } else { invokeClosureWithSocket(socket, closure); } return socket; } private static void invokeClosureWithSocket(Socket socket, Closure closure) { try { closure.call(socket); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.warning("Caught exception closing socket: " + e); } } } } /** * Converts this File to a {@link groovy.lang.Writable}. * * @param file a File * @return a File which wraps the input file and which implements Writable * @since 1.0 */ public static File asWritable(File file) { return new WritableFile(file); } /** * Converts this File to a {@link groovy.lang.Writable} or delegates to default * {@link #asType(java.lang.Object, java.lang.Class)}. * * @param f a File * @param c the desired class * @return the converted object * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(File f, Class c) { if (c == Writable.class) { return (T) asWritable(f); } return asType((Object) f, c); } /** * Allows a file to return a Writable implementation that can output itself * to a Writer stream. * * @param file a File * @param encoding the encoding to be used when reading the file's contents * @return File which wraps the input file and which implements Writable * @since 1.0 */ public static File asWritable(File file, String encoding) { return new WritableFile(file, encoding); } /** * Converts the given String into a List of strings of one character. * * @param self a String * @return a List of characters (a 1-character String) * @since 1.0 */ public static List toList(String self) { int size = self.length(); List answer = new ArrayList(size); for (int i = 0; i < size; i++) { answer.add(self.substring(i, i + 1)); } return answer; } /** * Converts the given CharSequence into a List of CharSequence of one character. * * @param self a CharSequence * @return a List of characters (a 1-character CharSequence) * @see #toSet(String) * @since 1.8.2 */ public static List toList(CharSequence self) { return new ArrayList(toList(self.toString())); } /** * Converts the given String into a Set of unique strings of one character. *

      * Example usage: *

           * assert 'groovy'.toSet() == ['v', 'g', 'r', 'o', 'y'] as Set
           * assert "abc".toSet().iterator()[0] instanceof String
           * 
      * * @param self a String * @return a Set of unique character Strings (each a 1-character String) * @since 1.8.0 */ public static Set toSet(String self) { return new HashSet(toList(self)); } /** * Converts the given CharSequence into a Set of unique CharSequence of one character. * * @param self a CharSequence * @return a Set of unique character CharSequence (each a 1-character CharSequence) * @see #toSet(String) * @since 1.8.2 */ public static Set toSet(CharSequence self) { return new HashSet(toList(self)); } /** * Converts the given String into an array of characters. * Alias for toCharArray. * * @param self a String * @return an array of characters * @see java.lang.String#toCharArray() * @since 1.6.0 */ public static char[] getChars(String self) { return self.toCharArray(); } /** * Converts the given CharSequence into an array of characters. * * @param self a CharSequence * @return an array of characters * @see #getChars(String) * @since 1.8.2 */ public static char[] getChars(CharSequence self) { return getChars(self.toString()); } /** * Converts the GString to a File, or delegates to the default * {@link #asType(java.lang.Object, java.lang.Class)} * * @param self a GString * @param c the desired class * @return the converted object * @since 1.5.0 */ @SuppressWarnings("unchecked") public static T asType(GString self, Class c) { if (c == File.class) { return (T) new File(self.toString()); } else if (Number.class.isAssignableFrom(c)) { return asType(self.toString(), c); } return asType((Object) self, c); } /** *

      Provides a method to perform custom 'dynamic' type conversion * to the given class using the as operator.

      * Example: '123' as Double *

      By default, the following types are supported: *

        *
      • List
      • *
      • BigDecimal
      • *
      • BigInteger
      • *
      • Long
      • *
      • Integer
      • *
      • Short
      • *
      • Byte
      • *
      • Character
      • *
      • Double
      • *
      • Float
      • *
      • File
      • *
      • Subclasses of Enum (Java 5 and above)
      • *
      * If any other type is given, the call is delegated to * {@link #asType(java.lang.Object, java.lang.Class)}. * * @param self a String * @param c the desired class * @return the converted object * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(String self, Class c) { if (c == List.class) { return (T) toList(self); } else if (c == BigDecimal.class) { return (T) toBigDecimal(self); } else if (c == BigInteger.class) { return (T) toBigInteger(self); } else if (c == Long.class || c == Long.TYPE) { return (T) toLong(self); } else if (c == Integer.class || c == Integer.TYPE) { return (T) toInteger(self); } else if (c == Short.class || c == Short.TYPE) { return (T) toShort(self); } else if (c == Byte.class || c == Byte.TYPE) { return (T) Byte.valueOf(self.trim()); } else if (c == Character.class || c == Character.TYPE) { return (T) toCharacter(self); } else if (c == Double.class || c == Double.TYPE) { return (T) toDouble(self); } else if (c == Float.class || c == Float.TYPE) { return (T) toFloat(self); } else if (c == File.class) { return (T) new File(self); } else if (DefaultTypeTransformation.isEnumSubclass(c)) { return (T) InvokerHelper.invokeMethod(c, "valueOf", new Object[]{ self }); } return asType((Object) self, c); } /** *

      Provides a method to perform custom 'dynamic' type conversion * to the given class using the as operator. * * @param self a CharSequence * @param c the desired class * @return the converted object * @see #asType(String, Class) * @since 1.8.2 */ public static T asType(CharSequence self, Class c) { return asType(self.toString(), c); } /** * Process each regex group matched substring of the given string. If the closure * parameter takes one argument, an array with all match groups is passed to it. * If the closure takes as many arguments as there are match groups, then each * parameter will be one match group. * * @param self the source string * @param regex a Regex string * @param closure a closure with one parameter or as much parameters as groups * @return the source string * @since 1.6.0 */ public static String eachMatch(String self, String regex, Closure closure) { return eachMatch(self, Pattern.compile(regex), closure); } /** * Process each regex group matched substring of the given CharSequence. If the closure * parameter takes one argument, an array with all match groups is passed to it. * If the closure takes as many arguments as there are match groups, then each * parameter will be one match group. * * @param self the source CharSequence * @param regex a Regex CharSequence * @param closure a closure with one parameter or as much parameters as groups * @return the source CharSequence * @see #eachMatch(String, String, groovy.lang.Closure) * @since 1.8.2 */ public static String eachMatch(CharSequence self, CharSequence regex, Closure closure) { return eachMatch(self.toString(), regex.toString(), closure); } /** * Process each regex group matched substring of the given pattern. If the closure * parameter takes one argument, an array with all match groups is passed to it. * If the closure takes as many arguments as there are match groups, then each * parameter will be one match group. * * @param self the source string * @param pattern a regex Pattern * @param closure a closure with one parameter or as much parameters as groups * @return the source string * @since 1.6.1 */ public static String eachMatch(String self, Pattern pattern, Closure closure) { Matcher m = pattern.matcher(self); each(m, closure); return self; } /** * Process each regex group matched substring of the given pattern. If the closure * parameter takes one argument, an array with all match groups is passed to it. * If the closure takes as many arguments as there are match groups, then each * parameter will be one match group. * * @param self the source CharSequence * @param pattern a regex Pattern * @param closure a closure with one parameter or as much parameters as groups * @return the source CharSequence * @see #eachMatch(String, Pattern, groovy.lang.Closure) * @since 1.8.2 */ public static String eachMatch(CharSequence self, Pattern pattern, Closure closure) { return eachMatch(self.toString(), pattern, closure); } /** * Iterates over the elements of an iterable collection of items and returns * the index of the first item that matches the condition specified in the closure. * * @param self the iteration object over which to iterate * @param closure the filter to perform a match on the collection * @return an integer that is the index of the first matched object or -1 if no match was found * @since 1.0 */ public static int findIndexOf(Object self, Closure closure) { return findIndexOf(self, 0, closure); } /** * Iterates over the elements of an iterable collection of items, starting from a * specified startIndex, and returns the index of the first item that matches the * condition specified in the closure. * * @param self the iteration object over which to iterate * @param startIndex start matching from this index * @param closure the filter to perform a match on the collection * @return an integer that is the index of the first matched object or -1 if no match was found * @since 1.5.0 */ public static int findIndexOf(Object self, int startIndex, Closure closure) { int result = -1; int i = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) { Object value = iter.next(); if (i < startIndex) { continue; } if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { result = i; break; } } return result; } /** * Iterates over the elements of an iterable collection of items and returns * the index of the last item that matches the condition specified in the closure. * * @param self the iteration object over which to iterate * @param closure the filter to perform a match on the collection * @return an integer that is the index of the last matched object or -1 if no match was found * @since 1.5.2 */ public static int findLastIndexOf(Object self, Closure closure) { return findLastIndexOf(self, 0, closure); } /** * Iterates over the elements of an iterable collection of items, starting * from a specified startIndex, and returns the index of the last item that * matches the condition specified in the closure. * * @param self the iteration object over which to iterate * @param startIndex start matching from this index * @param closure the filter to perform a match on the collection * @return an integer that is the index of the last matched object or -1 if no match was found * @since 1.5.2 */ public static int findLastIndexOf(Object self, int startIndex, Closure closure) { int result = -1; int i = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) { Object value = iter.next(); if (i < startIndex) { continue; } if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { result = i; } } return result; } /** * Iterates over the elements of an iterable collection of items and returns * the index values of the items that match the condition specified in the closure. * * @param self the iteration object over which to iterate * @param closure the filter to perform a match on the collection * @return a list of numbers corresponding to the index values of all matched objects * @since 1.5.2 */ public static List findIndexValues(Object self, Closure closure) { return findIndexValues(self, 0, closure); } /** * Iterates over the elements of an iterable collection of items, starting from * a specified startIndex, and returns the index values of the items that match * the condition specified in the closure. * * @param self the iteration object over which to iterate * @param startIndex start matching from this index * @param closure the filter to perform a match on the collection * @return a list of numbers corresponding to the index values of all matched objects * @since 1.5.2 */ public static List findIndexValues(Object self, Number startIndex, Closure closure) { List result = new ArrayList(); long count = 0; long startCount = startIndex.longValue(); for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) { Object value = iter.next(); if (count < startCount) { continue; } if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { result.add(count); } } return result; } /** * Iterates through the classloader parents until it finds a loader with a class * named "org.codehaus.groovy.tools.RootLoader". If there is no such class * null will be returned. The name is used for comparison because * a direct comparison using == may fail as the class may be loaded through * different classloaders. * * @param self a ClassLoader * @return the rootLoader for the ClassLoader * @see org.codehaus.groovy.tools.RootLoader * @since 1.5.0 */ public static ClassLoader getRootLoader(ClassLoader self) { while (true) { if (self == null) return null; if (isRootLoaderClassOrSubClass(self)) return self; self = self.getParent(); } } private static boolean isRootLoaderClassOrSubClass(ClassLoader self) { Class current = self.getClass(); while(!current.getName().equals(Object.class.getName())) { if(current.getName().equals(RootLoader.class.getName())) return true; current = current.getSuperclass(); } return false; } /** * Converts a given object to a type. This method is used through * the "as" operator and is overloadable as any other operator. * * @param obj the object to convert * @param type the goal type * @return the resulting object * @since 1.0 */ @SuppressWarnings("unchecked") public static T asType(Object obj, Class type) { if (String.class == type) { return (T) InvokerHelper.toString(obj); } // fall back to cast try { return (T) DefaultTypeTransformation.castToType(obj, type); } catch (GroovyCastException e) { MetaClass mc = InvokerHelper.getMetaClass(obj); if (mc instanceof ExpandoMetaClass) { ExpandoMetaClass emc = (ExpandoMetaClass) mc; Object mixedIn = emc.castToMixedType(obj, type); if (mixedIn != null) return (T) mixedIn; } if (type.isInterface()) { try { List interfaces = new ArrayList(); interfaces.add(type); return (T) ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, obj); } catch (GroovyRuntimeException cause) { // ignore } } throw e; } } private static Object asArrayType(Object object, Class type) { if (type.isAssignableFrom(object.getClass())) { return object; } Collection list = DefaultTypeTransformation.asCollection(object); int size = list.size(); Class elementType = type.getComponentType(); Object array = Array.newInstance(elementType, size); int idx = 0; if (boolean.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setBoolean(array, idx, (Boolean) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, boolean.class})); } } else if (byte.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setByte(array, idx, (Byte) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, byte.class})); } } else if (char.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setChar(array, idx, (Character) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, char.class})); } } else if (double.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setDouble(array, idx, (Double) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, double.class})); } } else if (float.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setFloat(array, idx, (Float) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, float.class})); } } else if (int.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setInt(array, idx, (Integer) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, int.class})); } } else if (long.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setLong(array, idx, (Long) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, long.class})); } } else if (short.class.equals(elementType)) { for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.setShort(array, idx, (Short) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, short.class})); } } else for (Iterator iter = list.iterator(); iter.hasNext(); idx++) { Object element = iter.next(); Array.set(array, idx, InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, elementType})); } return array; } /** * Convenience method to dynamically create a new instance of this * class. Calls the default constructor. * * @param c a class * @return a new instance of this class * @since 1.0 */ @SuppressWarnings("unchecked") public static T newInstance(Class c) { return (T) InvokerHelper.invokeConstructorOf(c, null); } /** * Helper to construct a new instance from the given arguments. * The constructor is called based on the number and types in the * args array. Use newInstance(null) or simply * newInstance() for the default (no-arg) constructor. * * @param c a class * @param args the constructor arguments * @return a new instance of this class. * @since 1.0 */ @SuppressWarnings("unchecked") public static T newInstance(Class c, Object[] args) { if (args == null) args = new Object[]{null}; return (T) InvokerHelper.invokeConstructorOf(c, args); } /** * Adds a "metaClass" property to all class objects so you can use the syntax * String.metaClass.myMethod = { println "foo" } * * @param c The java.lang.Class instance * @return An MetaClass instance * @since 1.5.0 */ public static MetaClass getMetaClass(Class c) { MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); MetaClass mc = metaClassRegistry.getMetaClass(c); if (mc instanceof ExpandoMetaClass || mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass) return mc; else { return new HandleMetaClass(mc); } } /** * Obtains a MetaClass for an object either from the registry or in the case of * a GroovyObject from the object itself. * * @param obj The object in question * @return The MetaClass * @since 1.5.0 */ public static MetaClass getMetaClass(Object obj) { MetaClass mc = InvokerHelper.getMetaClass(obj); return new HandleMetaClass(mc, obj); } /** * Obtains a MetaClass for an object either from the registry or in the case of * a GroovyObject from the object itself. * * @param obj The object in question * @return The MetaClass * @since 1.6.0 */ public static MetaClass getMetaClass(GroovyObject obj) { // we need this method as trick to guarantee correct method selection return getMetaClass((Object)obj); } /** * Sets the metaclass for a given class. * * @param self the class whose metaclass we wish to set * @param metaClass the new MetaClass * @since 1.6.0 */ public static void setMetaClass(Class self, MetaClass metaClass) { final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); if (metaClass == null) metaClassRegistry.removeMetaClass(self); else { if (metaClass instanceof HandleMetaClass) { metaClassRegistry.setMetaClass(self, ((HandleMetaClass)metaClass).getAdaptee()); } else { metaClassRegistry.setMetaClass(self, metaClass); } if (self==NullObject.class) { NullObject.getNullObject().setMetaClass(metaClass); } } } /** * Set the metaclass for an object * @param self the object whose metaclass we want to set * @param metaClass the new metaclass value * @since 1.6.0 */ public static void setMetaClass(Object self, MetaClass metaClass) { if (metaClass instanceof HandleMetaClass) metaClass = ((HandleMetaClass)metaClass).getAdaptee(); if (self instanceof GroovyObject) { ((GroovyObject)self).setMetaClass(metaClass); disablePrimitiveOptimization(self); } else if (self instanceof Class) { ((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass((Class)self, metaClass); } else { ((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass(self, metaClass); } } private static void disablePrimitiveOptimization(Object self) { Field sdyn; Class c = self.getClass(); try { sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL); sdyn.setBoolean(null, true); } catch (Throwable e) { //DO NOTHING } } /** * Sets/updates the metaclass for a given class to a closure. * * @param self the class whose metaclass we wish to update * @param closure the closure representing the new metaclass * @return the new metaclass value * @throws GroovyRuntimeException if the metaclass can't be set for this class * @since 1.6.0 */ public static MetaClass metaClass (Class self, Closure closure){ MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); MetaClass mc = metaClassRegistry.getMetaClass(self); if (mc instanceof ExpandoMetaClass) { ((ExpandoMetaClass) mc).define(closure); return mc; } else { if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass) { ((ExpandoMetaClass)((DelegatingMetaClass) mc).getAdaptee()).define(closure); return mc; } else { if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee().getClass() == MetaClassImpl.class) { ExpandoMetaClass emc = new ExpandoMetaClass(self, false, true); emc.initialize(); emc.define(closure); ((DelegatingMetaClass) mc).setAdaptee(emc); return mc; } else { if (mc.getClass() == MetaClassImpl.class) { // default case mc = new ExpandoMetaClass(self, false, true); mc.initialize(); ((ExpandoMetaClass)mc).define(closure); metaClassRegistry.setMetaClass(self, mc); return mc; } else { throw new GroovyRuntimeException("Can't add methods to custom meta class " + mc); } } } } } /** * Sets/updates the metaclass for a given object to a closure. * * @param self the object whose metaclass we wish to update * @param closure the closure representing the new metaclass * @return the new metaclass value * @throws GroovyRuntimeException if the metaclass can't be set for this object * @since 1.6.0 */ public static MetaClass metaClass (Object self, Closure closure){ MetaClass emc = hasPerInstanceMetaClass(self); if (emc == null) { final ExpandoMetaClass metaClass = new ExpandoMetaClass(self.getClass(), false, true); metaClass.initialize(); metaClass.define(closure); setMetaClass(self, metaClass); return metaClass; } else { if (emc instanceof ExpandoMetaClass) { ((ExpandoMetaClass)emc).define(closure); return emc; } else { if (emc instanceof DelegatingMetaClass && ((DelegatingMetaClass)emc).getAdaptee() instanceof ExpandoMetaClass) { ((ExpandoMetaClass)((DelegatingMetaClass)emc).getAdaptee()).define(closure); return emc; } else { throw new RuntimeException("Can't add methods to non-ExpandoMetaClass " + emc); } } } } private static MetaClass hasPerInstanceMetaClass(Object object) { if (object instanceof GroovyObject) { MetaClass mc = ((GroovyObject)object).getMetaClass(); if (mc == GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()) || mc.getClass() == MetaClassImpl.class) return null; else return mc; } else { ClassInfo info = ClassInfo.getClassInfo(object.getClass()); info.lock(); try { return info.getPerInstanceMetaClass(object); } finally { info.unlock(); } } } /** * Attempts to create an Iterator for the given object by first * converting it to a Collection. * * @param a an array * @return an Iterator for the given Array. * @see org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation#asCollection(java.lang.Object[]) * @since 1.6.4 */ public static Iterator iterator(T[] a) { return DefaultTypeTransformation.asCollection(a).iterator(); } /** * Attempts to create an Iterator for the given object by first * converting it to a Collection. * * @param o an object * @return an Iterator for the given Object. * @see org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation#asCollection(java.lang.Object) * @since 1.0 */ public static Iterator iterator(Object o) { return DefaultTypeTransformation.asCollection(o).iterator(); } /** * Allows an Enumeration to behave like an Iterator. Note that the * {@link java.util.Iterator#remove() remove()} method is unsupported since the * underlying Enumeration does not provide a mechanism for removing items. * * @param enumeration an Enumeration object * @return an Iterator for the given Enumeration * @since 1.0 */ public static Iterator iterator(final Enumeration enumeration) { return new Iterator() { private T last; public boolean hasNext() { return enumeration.hasMoreElements(); } public T next() { last = enumeration.nextElement(); return last; } public void remove() { throw new UnsupportedOperationException("Cannot remove() from an Enumeration"); } }; } /** * Returns an {@link java.util.Iterator} which traverses each match. * * @param matcher a Matcher object * @return an Iterator for a Matcher * @see java.util.regex.Matcher#group() * @since 1.0 */ public static Iterator iterator(final Matcher matcher) { matcher.reset(); return new Iterator() { private boolean found /* = false */; private boolean done /* = false */; public boolean hasNext() { if (done) { return false; } if (!found) { found = matcher.find(); if (!found) { done = true; } } return found; } public Object next() { if (!found) { if (!hasNext()) { throw new NoSuchElementException(); } } found = false; if (hasGroup(matcher)) { // are we using groups? // yes, so return the specified group as list List list = new ArrayList(matcher.groupCount()); for (int i = 0; i <= matcher.groupCount(); i++) { list.add(matcher.group(i)); } return list; } else { // not using groups, so return the nth // occurrence of the pattern return matcher.group(); } } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Creates an iterator which will traverse through the reader a line at a time. * * @param self a Reader object * @return an Iterator for the Reader * @see java.io.BufferedReader#readLine() * @since 1.5.0 */ public static Iterator iterator(Reader self) { final BufferedReader bufferedReader; if (self instanceof BufferedReader) bufferedReader = (BufferedReader) self; else bufferedReader = new BufferedReader(self); return new Iterator() { String nextVal /* = null */; boolean nextMustRead = true; boolean hasNext = true; public boolean hasNext() { if (nextMustRead && hasNext) { try { nextVal = readNext(); nextMustRead = false; } catch (IOException e) { hasNext = false; } } return hasNext; } public String next() { String retval = null; if (nextMustRead) { try { retval = readNext(); } catch (IOException e) { hasNext = false; } } else retval = nextVal; nextMustRead = true; return retval; } private String readNext() throws IOException { String nv = bufferedReader.readLine(); if (nv == null) hasNext = false; return nv; } public void remove() { throw new UnsupportedOperationException("Cannot remove() from a Reader Iterator"); } }; } /** * Standard iterator for a input stream which iterates through the stream * content in a byte-based fashion. * * @param self an InputStream object * @return an Iterator for the InputStream * @since 1.5.0 */ public static Iterator iterator(InputStream self) { return iterator(new DataInputStream(self)); } /** * Standard iterator for a data input stream which iterates through the * stream content a Byte at a time. * * @param self a DataInputStream object * @return an Iterator for the DataInputStream * @since 1.5.0 */ public static Iterator iterator(final DataInputStream self) { return new Iterator() { Byte nextVal; boolean nextMustRead = true; boolean hasNext = true; public boolean hasNext() { if (nextMustRead && hasNext) { try { nextVal = self.readByte(); nextMustRead = false; } catch (IOException e) { hasNext = false; } } return hasNext; } public Byte next() { Byte retval = null; if (nextMustRead) { try { retval = self.readByte(); } catch (IOException e) { hasNext = false; } } else retval = nextVal; nextMustRead = true; return retval; } public void remove() { throw new UnsupportedOperationException("Cannot remove() from a DataInputStream Iterator"); } }; } /** * An identity function for iterators, supporting 'duck-typing' when trying to get an * iterator for each object within a collection, some of which may already be iterators. * * @param self an iterator object * @return itself * @since 1.5.0 */ public static Iterator iterator(Iterator self) { return self; } /** *

      Returns an object satisfying Groovy truth if the implementing MetaClass responds to * a method with the given name and arguments types. * *

      Note that this method's return value is based on realised methods and does not take into account * objects or classes that implement invokeMethod or methodMissing * *

      This method is "safe" in that it will always return a value and never throw an exception * * @param self The object to inspect * @param name The name of the method of interest * @param argTypes The argument types to match against * @return A List of MetaMethods matching the argument types which will be empty if no matching methods exist * @see groovy.lang.MetaObjectProtocol#respondsTo(java.lang.Object, java.lang.String, java.lang.Object[]) * @since 1.6.0 */ public static List respondsTo(Object self, String name, Object[] argTypes) { return InvokerHelper.getMetaClass(self).respondsTo(self, name, argTypes); } /** *

      Returns an object satisfying Groovy truth if the implementing MetaClass responds to * a method with the given name regardless of the arguments. * *

      Note that this method's return value is based on realised methods and does not take into account * objects or classes that implement invokeMethod or methodMissing * *

      This method is "safe" in that it will always return a value and never throw an exception * * @param self The object to inspect * @param name The name of the method of interest * @return A List of MetaMethods matching the given name or an empty list if no matching methods exist * @see groovy.lang.MetaObjectProtocol#respondsTo(java.lang.Object, java.lang.String) * @since 1.6.1 */ public static List respondsTo(Object self, String name) { return InvokerHelper.getMetaClass(self).respondsTo(self, name); } /** *

      Returns true of the implementing MetaClass has a property of the given name * *

      Note that this method will only return true for realised properties and does not take into * account implementation of getProperty or propertyMissing * * @param self The object to inspect * @param name The name of the property of interest * @return The found MetaProperty or null if it doesn't exist * @see groovy.lang.MetaObjectProtocol#hasProperty(java.lang.Object, java.lang.String) * @since 1.6.1 */ public static MetaProperty hasProperty(Object self, String name) { return InvokerHelper.getMetaClass(self).hasProperty(self, name); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ProcessGroovyMethods.java0000644001501200150120000004477411645141222026527 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import java.io.*; /** * This class defines new groovy methods which appear on normal JDK * classes related to process management. *

      * Static methods are used with the first parameter being the destination class, * i.e. public static String reverse(String self) * provides a reverse() method for String. *

      * NOTE: While this class contains many 'public' static methods, it is * primarily regarded as an internal class (its internal package name * suggests this also). We value backwards compatibility of these * methods when used within Groovy but value less backwards compatibility * at the Java method call level. I.e. future versions of Groovy may * remove or move a method call in this file but would normally * aim to keep the method available from within Groovy. */ public class ProcessGroovyMethods extends DefaultGroovyMethodsSupport { /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar fashion. * * @param self a Process instance * @return the InputStream for the process * @since 1.0 */ public static InputStream getIn(Process self) { return self.getInputStream(); } /** * Read the text of the output stream of the Process. * * @param self a Process instance * @return the text of the output * @throws java.io.IOException if an IOException occurs. * @since 1.0 */ public static String getText(Process self) throws IOException { return DefaultGroovyMethods.getText(new BufferedReader(new InputStreamReader(self.getInputStream()))); } /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar fashion. * * @param self a Process instance * @return the error InputStream for the process * @since 1.0 */ public static InputStream getErr(Process self) { return self.getErrorStream(); } /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar fashion. * * @param self a Process instance * @return the OutputStream for the process * @since 1.0 */ public static OutputStream getOut(Process self) { return self.getOutputStream(); } /** * Overloads the left shift operator (<<) to provide an append mechanism * to pipe data to a Process. * * @param self a Process instance * @param value a value to append * @return a Writer * @throws java.io.IOException if an IOException occurs. * @since 1.0 */ public static Writer leftShift(Process self, Object value) throws IOException { return DefaultGroovyMethods.leftShift(self.getOutputStream(), value); } /** * Overloads the left shift operator to provide an append mechanism * to pipe into a Process * * @param self a Process instance * @param value data to append * @return an OutputStream * @throws java.io.IOException if an IOException occurs. * @since 1.0 */ public static OutputStream leftShift(Process self, byte[] value) throws IOException { return DefaultGroovyMethods.leftShift(self.getOutputStream(), value); } /** * Wait for the process to finish during a certain amount of time, otherwise stops the process. * * @param self a Process * @param numberOfMillis the number of milliseconds to wait before stopping the process * @since 1.0 */ public static void waitForOrKill(Process self, long numberOfMillis) { ProcessRunner runnable = new ProcessRunner(self); Thread thread = new Thread(runnable); thread.start(); runnable.waitForOrKill(numberOfMillis); } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The stream data is thrown away but blocking due to a full output buffer is avoided. * Use this method if you don't care about the standard or error output and just * want the process to run silently - use carefully however, because since the stream * data is thrown away, it might be difficult to track down when something goes wrong. * For this, two Threads are started, so this method will return immediately. * * @param self a Process * @since 1.0 */ public static void consumeProcessOutput(Process self) { consumeProcessOutput(self, (OutputStream)null, (OutputStream)null); } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied Appendable. * For this, two Threads are started, so this method will return immediately. * * @param self a Process * @param output an Appendable to capture the process stdout * @param error an Appendable to capture the process stderr * @since 1.7.5 */ public static void consumeProcessOutput(Process self, Appendable output, Appendable error) { consumeProcessOutputStream(self, output); consumeProcessErrorStream(self, error); } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied OutputStream. * For this, two Threads are started, so this method will return immediately. * * @param self a Process * @param output an OutputStream to capture the process stdout * @param error an OutputStream to capture the process stderr * @since 1.5.2 */ public static void consumeProcessOutput(Process self, OutputStream output, OutputStream error) { consumeProcessOutputStream(self, output); consumeProcessErrorStream(self, error); } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The stream data is thrown away but blocking due to a full output buffer is avoided. * Use this method if you don't care about the standard or error output and just * want the process to run silently - use carefully however, because since the stream * data is thrown away, it might be difficult to track down when something goes wrong. * For this, two Threads are started, but join()ed, so we wait. * As implied by the waitFor... name, we also wait until we finish * as well. Finally, the output and error streams are closed. * * @param self a Process * @since 1.6.5 */ public static void waitForProcessOutput(Process self) { waitForProcessOutput(self, (OutputStream)null, (OutputStream)null); } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied Appendable. * For this, two Threads are started, but join()ed, so we wait. * As implied by the waitFor... name, we also wait until we finish * as well. Finally, the output and error streams are closed. * * @param self a Process * @param output an Appendable to capture the process stdout * @param error an Appendable to capture the process stderr * @since 1.7.5 */ public static void waitForProcessOutput(Process self, Appendable output, Appendable error) { Thread tout = consumeProcessOutputStream(self, output); Thread terr = consumeProcessErrorStream(self, error); try { tout.join(); } catch (InterruptedException ignore) {} try { terr.join(); } catch (InterruptedException ignore) {} try { self.waitFor(); } catch (InterruptedException ignore) {} try { self.getErrorStream().close(); } catch (IOException ignore) {} try { self.getInputStream().close(); } catch (IOException ignore) {} } /** * Gets the output and error streams from a process and reads them * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied OutputStream. * For this, two Threads are started, but join()ed, so we wait. * As implied by the waitFor... name, we also wait until we finish * as well. Finally, the output and error streams are closed. * * @param self a Process * @param output an OutputStream to capture the process stdout * @param error an OutputStream to capture the process stderr * @since 1.6.5 */ public static void waitForProcessOutput(Process self, OutputStream output, OutputStream error) { Thread tout = consumeProcessOutputStream(self, output); Thread terr = consumeProcessErrorStream(self, error); try { tout.join(); } catch (InterruptedException ignore) {} try { terr.join(); } catch (InterruptedException ignore) {} try { self.waitFor(); } catch (InterruptedException ignore) {} try { self.getErrorStream().close(); } catch (IOException ignore) {} try { self.getInputStream().close(); } catch (IOException ignore) {} } /** * Gets the error stream from a process and reads it * to keep the process from blocking due to a full buffer. * The processed stream data is appended to the supplied OutputStream. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param err an OutputStream to capture the process stderr * @return the Thread * @since 1.5.2 */ public static Thread consumeProcessErrorStream(Process self, OutputStream err) { Thread thread = new Thread(new ByteDumper(self.getErrorStream(), err)); thread.start(); return thread; } /** * Gets the error stream from a process and reads it * to keep the process from blocking due to a full buffer. * The processed stream data is appended to the supplied Appendable. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param error an Appendable to capture the process stderr * @return the Thread * @since 1.7.5 */ public static Thread consumeProcessErrorStream(Process self, Appendable error) { Thread thread = new Thread(new TextDumper(self.getErrorStream(), error)); thread.start(); return thread; } /** * Gets the output stream from a process and reads it * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied Appendable. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param output an Appendable to capture the process stdout * @return the Thread * @since 1.7.5 */ public static Thread consumeProcessOutputStream(Process self, Appendable output) { Thread thread = new Thread(new TextDumper(self.getInputStream(), output)); thread.start(); return thread; } /** * Gets the output stream from a process and reads it * to keep the process from blocking due to a full output buffer. * The processed stream data is appended to the supplied OutputStream. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param output an OutputStream to capture the process stdout * @return the Thread * @since 1.5.2 */ public static Thread consumeProcessOutputStream(Process self, OutputStream output) { Thread thread = new Thread(new ByteDumper(self.getInputStream(), output)); thread.start(); return thread; } /** * Creates a new BufferedWriter as stdin for this process, * passes it to the closure, and ensures the stream is flushed * and closed after the closure returns. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param closure a closure * @since 1.5.2 */ public static void withWriter(final Process self, final Closure closure) { new Thread(new Runnable() { public void run() { try { DefaultGroovyMethods.withWriter(new BufferedOutputStream(getOut(self)), closure); } catch (IOException e) { throw new GroovyRuntimeException("exception while reading process stream", e); } } }).start(); } /** * Creates a new buffered OutputStream as stdin for this process, * passes it to the closure, and ensures the stream is flushed * and closed after the closure returns. * A new Thread is started, so this method will return immediately. * * @param self a Process * @param closure a closure * @since 1.5.2 */ public static void withOutputStream(final Process self, final Closure closure) { new Thread(new Runnable() { public void run() { try { DefaultGroovyMethods.withStream(new BufferedOutputStream(getOut(self)), closure); } catch (IOException e) { throw new GroovyRuntimeException("exception while reading process stream", e); } } }).start(); } /** * Allows one Process to asynchronously pipe data to another Process. * * @param left a Process instance * @param right a Process to pipe output to * @return the second Process to allow chaining * @throws java.io.IOException if an IOException occurs. * @since 1.5.2 */ public static Process pipeTo(final Process left, final Process right) throws IOException { new Thread(new Runnable() { public void run() { InputStream in = new BufferedInputStream(getIn(left)); OutputStream out = new BufferedOutputStream(getOut(right)); byte[] buf = new byte[8192]; int next; try { while ((next = in.read(buf)) != -1) { out.write(buf, 0, next); } } catch (IOException e) { throw new GroovyRuntimeException("exception while reading process stream", e); } finally { closeWithWarning(out); } } }).start(); return right; } /** * Overrides the or operator to allow one Process to asynchronously * pipe data to another Process. * * @param left a Process instance * @param right a Process to pipe output to * @return the second Process to allow chaining * @throws java.io.IOException if an IOException occurs. * @since 1.5.1 */ public static Process or(final Process left, final Process right) throws IOException { return pipeTo(left, right); } /** * A Runnable which waits for a process to complete together with a notification scheme * allowing another thread to wait a maximum number of seconds for the process to complete * before killing it. * * @since 1.0 */ protected static class ProcessRunner implements Runnable { Process process; private boolean finished; public ProcessRunner(Process process) { this.process = process; } private void doProcessWait() { try { process.waitFor(); } catch (InterruptedException e) { // Ignore } } public void run() { doProcessWait(); synchronized (this) { notifyAll(); finished = true; } } public synchronized void waitForOrKill(long millis) { if (!finished) { try { wait(millis); } catch (InterruptedException e) { // Ignore } if (!finished) { process.destroy(); doProcessWait(); } } } } private static class TextDumper implements Runnable { InputStream in; Appendable app; public TextDumper(InputStream in, Appendable app) { this.in = in; this.app = app; } public void run() { InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); String next; try { while ((next = br.readLine()) != null) { if (app != null) { app.append(next); app.append("\n"); } } } catch (IOException e) { throw new GroovyRuntimeException("exception while reading process stream", e); } } } private static class ByteDumper implements Runnable { InputStream in; OutputStream out; public ByteDumper(InputStream in, OutputStream out) { this.in = new BufferedInputStream(in); this.out = out; } public void run() { byte[] buf = new byte[8192]; int next; try { while ((next = in.read(buf)) != -1) { if (out != null) out.write(buf, 0, next); } } catch (IOException e) { throw new GroovyRuntimeException("exception while dumping process stream", e); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/Reflector.java0000644001501200150120000000246111627206700024272 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.MissingMethodException; import org.codehaus.groovy.reflection.CachedMethod; /** * Provides as alternative to reflection using bytecode generation. * * @author James Strachan * @version $Revision: 4247 $ */ public class Reflector { public Object invoke(CachedMethod method, Object object, Object[] arguments) { return noSuchMethod(method, object, arguments); } protected Object noSuchMethod(CachedMethod method, Object object, Object[] arguments) { throw new MissingMethodException(method.getName(), method.getDeclaringClass().getTheClass(), arguments, false); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/HandleMetaClass.java0000644001501200150120000000767611627206700025352 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.*; import java.lang.reflect.Method; public class HandleMetaClass extends DelegatingMetaClass { private Object object; private static MetaClass myMetaClass; private static final Object NONE = new Object(); public HandleMetaClass(MetaClass mc) { this(mc, null); } public HandleMetaClass(MetaClass mc, Object obj) { super(mc); if (obj != null) { if (InvokerHelper.getMetaClass(obj.getClass()) == mc || !(mc instanceof ExpandoMetaClass)) object = obj; // object has default meta class, so we need to replace it on demand else object = NONE; // object already has per instance meta class } if (myMetaClass == null) myMetaClass = InvokerHelper.getMetaClass(getClass()); } public void initialize() { replaceDelegate(); delegate.initialize(); } public GroovyObject replaceDelegate() { if (object == null) { if (!(delegate instanceof ExpandoMetaClass)) { delegate = new ExpandoMetaClass(delegate.getTheClass(), true, true); delegate.initialize(); } DefaultGroovyMethods.setMetaClass(delegate.getTheClass(), delegate); } else { if (object != NONE) { final MetaClass metaClass = delegate; delegate = new ExpandoMetaClass(delegate.getTheClass(), false, true); if (metaClass instanceof ExpandoMetaClass) { ExpandoMetaClass emc = (ExpandoMetaClass) metaClass; for (MetaMethod method : emc.getExpandoMethods()) ((ExpandoMetaClass)delegate).registerInstanceMethod(method); } delegate.initialize(); DefaultGroovyMethods.setMetaClass(object, delegate); object = NONE; } } return (GroovyObject)delegate; } public Object invokeMethod(String name, Object args) { return replaceDelegate().invokeMethod(name, args); } // this method mimics EMC behavior public Object getProperty(String property) { if(ExpandoMetaClass.isValidExpandoProperty(property)) { if(property.equals(ExpandoMetaClass.STATIC_QUALIFIER) || property.equals(ExpandoMetaClass.CONSTRUCTOR) || myMetaClass.hasProperty(this, property) == null) { return replaceDelegate().getProperty(property); } } return myMetaClass.getProperty(this, property); } public void setProperty(String property, Object newValue) { replaceDelegate().setProperty(property, newValue); } public void addNewInstanceMethod(Method method) { throw new UnsupportedOperationException(); } public void addNewStaticMethod(Method method) { throw new UnsupportedOperationException(); } public void addMetaMethod(MetaMethod metaMethod) { throw new UnsupportedOperationException(); } public void addMetaBeanProperty(MetaBeanProperty metaBeanProperty) { throw new UnsupportedOperationException(); } public boolean equals(Object obj) { return super.equals(obj) || getAdaptee().equals(obj) || (obj instanceof HandleMetaClass && equals(((HandleMetaClass)obj).getAdaptee())); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DefaultMethodKey.java0000644001501200150120000000246711627206700025551 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; /** * A default implementation of MethodKey * * @author James Strachan * @version $Revision$ */ public class DefaultMethodKey extends MethodKey{ private final Class[] parameterTypes; public DefaultMethodKey(Class sender, String name, Class[] parameterTypes, boolean isCallToSuper) { super(sender, name,isCallToSuper); this.parameterTypes = parameterTypes; } public int getParameterCount() { return parameterTypes.length; } public Class getParameterType(int index) { Class c = parameterTypes[index]; if (c==null) return Object.class; return c; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/MethodRankHelper.java0000644001501200150120000005026511707612046025551 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.MetaMethod; import groovy.lang.MetaProperty; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; /** * Utility class for MissingMethodException, MissingPropertyException etc. * This class contains methods assisting in ranking and listing probable intended * methods/fields when a exception is thrown. * * @author Hjalmar Ekengren */ public class MethodRankHelper{ //These are the costs for the various edit operations //they are used by the two DamerauLevenshtein implementations public static final int DL_SUBSTITUTION = 10; public static final int DL_DELETE = 10; //This is also the cost for a insert public static final int DL_TRANSPOSITION = 5; public static final int DL_CASE = 5; public static final int MAX_RECOMENDATIONS = 5; public static final int MAX_METHOD_SCORE = 50; public static final int MAX_CONSTRUCTOR_SCORE = 20; public static final int MAX_FIELD_SCORE = 30; private static final class Pair { private U u; private V v; public Pair(U u, V v){ this.u = u; this.v = v; } } /** * Returns a string detailing possible solutions to a missing method * if no good solutions can be found a empty string is returned. * * @param methodName the name of the method that doesn't exist * @param type the class on which the method is invoked * @param arguments the arguments passed to the method * @return a string with probable solutions to the exception */ public static String getMethodSuggestionString(String methodName, Class type, Object[] arguments){ ClassInfo ci = ClassInfo.getClassInfo(type); List methods = new ArrayList(ci.getMetaClass().getMethods()); methods.addAll(ci.getMetaClass().getMetaMethods()); List sugg = rankMethods(methodName,arguments,methods); StringBuffer sb = new StringBuffer(); if (!sugg.isEmpty()){ sb.append("\nPossible solutions: "); for(int i = 0; i < sugg.size(); i++) { if(i != 0) sb.append(", "); sb.append(sugg.get(i).getName()).append("("); sb.append(listParameterNames(sugg.get(i).getParameterTypes())); sb.append(")"); } } Class[] argumentClasses = getArgumentClasses(arguments); List> conflictClasses = getConflictClasses(sugg,argumentClasses); if (!conflictClasses.isEmpty()){ sb.append("\nThe following classes appear as argument class and as parameter class, "); sb.append("but are defined by different class loader:\n"); boolean first = true; for(Pair pair: conflictClasses) { if (!first) { sb.append(", "); } else { first = false; } sb.append(pair.u.getName()).append(" (defined by '"); sb.append(pair.u.getClassLoader()); sb.append("' and '"); sb.append(pair.v.getClassLoader()); sb.append("')"); } sb.append("\nIf one of the method suggestions matches the method you wanted to call, "); sb.append("\nthen check your class loader setup."); } return sb.toString(); } private static List> getConflictClasses(List sugg, Class[] argumentClasses) { List> ret = new LinkedList>(); Set recordedClasses = new HashSet(); for (MetaMethod method : sugg) { Class[] para = method.getNativeParameterTypes(); for (Class aPara : para) { if (recordedClasses.contains(aPara)) continue; for (Class argumentClass : argumentClasses) { if (argumentClass == null) continue; if (argumentClass == aPara) continue; if (argumentClass.getName().equals(aPara.getName())) { ret.add(new Pair(argumentClass, aPara)); } } recordedClasses.add(aPara); } } return ret; } private static Class[] getArgumentClasses(Object[] arguments) { Class[] argumentClasses = new Class[arguments.length]; for (int i=0; i0){ StringBuffer sb = new StringBuffer(); sb.append("\nPossible solutions: "); for(int i = 0; i < sugg.length; i++){ if(i != 0) sb.append(", "); sb.append(type.getName()).append("("); sb.append(listParameterNames(sugg[i].getParameterTypes())); sb.append(")"); } return sb.toString(); } else{ return ""; } } /** * Returns a string detailing possible solutions to a missing field or property * if no good solutions can be found a empty string is returned. * * @param fieldName the missing field * @param type the class on which the field is sought * @return a string with probable solutions to the exception */ public static String getPropertySuggestionString(String fieldName, Class type){ ClassInfo ci = ClassInfo.getClassInfo(type); List fi = ci.getMetaClass().getProperties(); List rf = new ArrayList(fi.size()); StringBuffer sb = new StringBuffer(); sb.append("\nPossible solutions: "); for(MetaProperty mp : fi) rf.add(new RankableField(fieldName, mp)); Collections.sort(rf); int i = 0; for (RankableField f : rf) { if (i > MAX_RECOMENDATIONS) break; if (f.score > MAX_FIELD_SCORE) break; if(i > 0) sb.append(", "); sb.append(f.f.getName()); i++; } return i > 0? sb.toString(): ""; } /** * creates a comma separated list of each of the class names. * * @param cachedClasses the array of Classes * @return the Class names */ private static String listParameterNames(Class[] cachedClasses){ StringBuffer sb = new StringBuffer(); for(int i =0; i < cachedClasses.length;i++){ if(i != 0) sb.append(", "); sb.append(cachedClasses[i].getName()); } return sb.toString(); } private static String listParameterNames(CachedClass[] cachedClasses){ StringBuffer sb = new StringBuffer(); for(int i =0; i < cachedClasses.length;i++){ if(i != 0) sb.append(", "); sb.append(cachedClasses[i].getName()); } return sb.toString(); } /** * Returns a sorted(ranked) list of a selection of the methods among candidates which * most closely resembles original. * * @param name * @param original * @param methods * @return a sorted lists of Methods */ private static List rankMethods(String name, Object[] original, List methods) { List rm = new ArrayList(methods.size()); if (original==null) original = new Object[0]; Class[] ta = new Class[original.length]; Class nullC = NullObject.class; for(int i = 0; i < original.length; i++){ //All nulls have to be wrapped so that they can be compared ta[i] = original[i] == null?nullC: original[i].getClass(); } for (MetaMethod m:methods) { rm.add(new RankableMethod(name, ta, m)); } Collections.sort(rm); List l = new ArrayList(rm.size()); for (RankableMethod m : rm) { if (l.size() > MAX_RECOMENDATIONS) break; if (m.score > MAX_METHOD_SCORE) break; l.add(m.m); } return l; } /** * This class wraps a method object and a score variable so methods * Can easily be ranked by their likeness to a another method * */ private static final class RankableMethod implements Comparable { final MetaMethod m; final Integer score; public RankableMethod(String name, Class[] argumentTypes, MetaMethod m2) { this.m = m2; int nameDist = delDistance(name, m2.getName()); //unbox primitives Class[] mArgs = new Class[m2.getParameterTypes().length]; for(int i =0; i < mArgs.length; i++){ //All args have to be boxed since argumentTypes is always boxed mArgs[i] = boxVar(m2.getParameterTypes()[i].getTheClass()); } int argDist = damerauLevenshteinDistance(argumentTypes,mArgs); this.score = nameDist + argDist; } public int compareTo(Object o) { RankableMethod mo = (RankableMethod) o; return score.compareTo(mo.score); } } /** * Returns a sorted(ranked) list of a selection of the constructors among candidates which * most closely resembles original. * * @param original * @param candidates * @return a sorted lists of Methods */ private static Constructor[] rankConstructors(Object[] original, Constructor[] candidates) { RankableConstructor[] rc = new RankableConstructor[candidates.length]; Class[] ta = new Class[original.length]; Class nullC = NullObject.class; for (int i = 0; i < original.length; i++) { //All nulls have to be wrapped so that they can be compared ta[i] = original[i] == null ? nullC : original[i].getClass(); } for (int i = 0; i < candidates.length; i++) { rc[i] = new RankableConstructor(ta, candidates[i]); } Arrays.sort(rc); List l = new ArrayList(); int index = 0; while (l.size() < MAX_RECOMENDATIONS && index < rc.length && rc[index].score < MAX_CONSTRUCTOR_SCORE) { l.add(rc[index].c); index++; } return l.toArray(new Constructor[l.size()]); } /** * This class wraps a method object and a score variable so methods * Can easily be ranked by their likeness to a another method * */ private static final class RankableConstructor implements Comparable { final Constructor c; final Integer score; public RankableConstructor(Class[] argumentTypes, Constructor c) { this.c = c; //unbox primitives Class[] cArgs = new Class[c.getParameterTypes().length]; for(int i =0; i < cArgs.length; i++){ //All args have to be boxed since argumentTypes is always boxed cArgs[i] = boxVar(c.getParameterTypes()[i]); } this.score = damerauLevenshteinDistance(argumentTypes,cArgs); } public int compareTo(Object o) { RankableConstructor co = (RankableConstructor) o; return score.compareTo(co.score); } } /** * This class wraps a method object and a score variable so methods * Can easily be ranked by their likeness to a another method * */ private static final class RankableField implements Comparable { final MetaProperty f; final Integer score; public RankableField(String name, MetaProperty mp) { this.f = mp; this.score = delDistance(name,mp.getName()); } public int compareTo(Object o) { RankableField co = (RankableField) o; return score.compareTo(co.score); } } /** * If c is a primitive class this method returns a boxed version * otherwise c is returned. * In java 1.5 this can be simplified thanks to the Type class. * @param c * @return a boxed version of c if c can be boxed, else c */ protected static Class boxVar(Class c){ if(Boolean.TYPE.equals(c)){ return Boolean.class; }else if(Character.TYPE.equals(c)){ return Character.class; }else if(Byte.TYPE.equals(c)){ return Byte.class; }else if(Double.TYPE.equals(c)){ return Double.class; }else if(Float.TYPE.equals(c)){ return Float.class; }else if(Integer.TYPE.equals(c)){ return Integer.class; }else if(Long.TYPE.equals(c)){ return Long.class; }else if(Short.TYPE.equals(c)){ return Short.class; }else{ return c; } } /** * This is a small wrapper for nulls */ private static class NullObject{ } /** * This is a slightly modified version of the Damerau Levenshtein distance * algorithm. It has a additional test to see if a character has switched case, * in the original algorithm this counts as a substitution. * The "cost" for a substitution is given as 10 instead of 1 in this version, * this enables transpositions and case modifications to have a lower cost than * substitutions. * * Currently the lowercase versions of t_j and s_i isn't cached, its probable * that some speed could be gained from this. * * This version is based on Chas Emerick's implementation of Levenshtein Distance * for jakarta commons. * @param s a CharSequence * @param t the CharSequence to be compared to s * @return a value representing the edit distance between s and t */ public static int delDistance(CharSequence s, CharSequence t) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } int n = s.length(); // length of s int m = t.length(); // length of t if (n == 0) { return m; } else if (m == 0) { return n; } //we have to keep 3 rows instead of the 2 used in Levenshtein int[][] vals = new int[3][n + 1]; int _d[]; //placeholder to assist in rotating vals // indexes into strings s and t int i; // iterates through s int j; // iterates through t char t_j; // jth character of t char s_i; // ith character of s int cost; // cost for (i = 0; i <= n; i++) { vals[1][i] = i * DL_DELETE; } for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); vals[0][0] = j * DL_DELETE; for (i = 1; i <= n; i++) { s_i = s.charAt(i - 1); if (Character.isLowerCase(s_i) ^ Character.isLowerCase(t_j)) { //if s_i and t_i don't have have the same case cost = caselessCompare(s_i, t_j) ? DL_CASE : DL_SUBSTITUTION; } else { //if they share case check for substitution cost = s_i == t_j ? 0 : DL_SUBSTITUTION; } // minimum of cell to the left+1, to the top+1, diagonally left and up +cost vals[0][i] = Math.min(Math.min(vals[0][i - 1] + DL_DELETE, vals[1][i] + DL_DELETE), vals[1][i - 1] + cost); //Check for transposition, somewhat more complex now since we have to check for case if (i > 1 && j > 1) { cost = Character.isLowerCase(s_i) ^ Character.isLowerCase(t.charAt(j - 2)) ? DL_CASE : 0; cost = Character.isLowerCase(s.charAt(i - 2)) ^ Character.isLowerCase(t_j) ? cost + DL_CASE : cost; if (caselessCompare(s_i, t.charAt(j - 2)) && caselessCompare(s.charAt(i - 2), t_j)) { vals[0][i] = Math.min(vals[0][i], vals[2][i - 2] + DL_TRANSPOSITION + cost); } } } // rotate all value arrays upwards(older rows get a higher index) _d = vals[2]; vals[2] = vals[1]; vals[1] = vals[0]; vals[0] = _d; } // our last action in the above loop was to rotate vals, so vals[1] now // actually has the most recent cost counts return vals[1][n]; } /** * Compares two characters whilst ignoring case. * @param a the first character * @param b the second character * @return true if the characters are equal */ private static boolean caselessCompare(char a, char b){ return Character.toLowerCase(a) == Character.toLowerCase(b); } /** * This is a implementation of DL distance between two Object arrays instead * of character streams. The objects are compared using their equals method. * No objects may be null. * This implementation is based on Chas Emerick's implementation of Levenshtein Distance * for jakarta commons. * @param s a Object array * @param t this array is compared to s * @return the edit distance between the two arrays */ public static int damerauLevenshteinDistance(Object[] s, Object[] t) { if (s == null || t == null) { throw new IllegalArgumentException("Arrays must not be null"); } int n = s.length; // length of s int m = t.length; // length of t if (n == 0) { return m; } else if (m == 0) { return n; } int[][] vals = new int[3][n + 1]; int _d[]; //placeholder to assist in rotating vals // indexes into arrays s and t int i; // iterates through s int j; // iterates through t Object t_j; // jth object of t int cost; // cost for (i = 0; i <= n; i++) { vals[1][i] = i * DL_DELETE ; } for (j = 1; j <= m; j++) { t_j = t[j - 1]; vals[0][0] = j * DL_DELETE ; for (i = 1; i <= n; i++) { cost = s[i - 1].equals(t_j)? 0 : DL_SUBSTITUTION; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost vals[0][i] = Math.min(Math.min(vals[0][i - 1] + DL_DELETE, vals[1][i] + DL_DELETE), vals[1][i - 1] + cost); //Check for transposition if(i > 1 && j > 1 && s[i -1].equals(t[j -2]) && s[i- 2].equals(t_j)){ vals[0][i] = Math.min(vals[0][i], vals[2][i-2] + DL_TRANSPOSITION); } } // rotate all value arrays upwards(older rows get a higher index) _d = vals[2]; vals[2] = vals[1]; vals[1] = vals[0]; vals[0] = _d; } return vals[1][n]; } }groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ScriptTestAdapter.java0000644001501200150120000000305111715031256025746 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import junit.framework.Test; import junit.framework.TestResult; /** * An adapter to make any Groovy Script class an instance of a JUnit Test * * @version $Revision$ */ public class ScriptTestAdapter implements Test { private Class scriptClass; private String[] arguments; public ScriptTestAdapter(Class scriptClass, String[] arguments) { this.scriptClass = scriptClass; this.arguments = arguments; } public int countTestCases() { return 1; } public void run(TestResult result) { try { result.startTest(this); // lets run the script InvokerHelper.runScript(scriptClass, arguments); result.endTest(this); } catch (Exception e) { result.addError(this, e); } } public String toString() { return "TestCase for script: " + scriptClass.getName(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/ArrayUtil.java0000644001501200150120000253332011707612046024271 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; /** * This is a generated class used internally during the writing of bytecode within the CallSiteWriter logic.
      * This is not a class exposed to users, as is the case with almost all classes in the org.codehaus.groovy packages.

      * * The purpose is the reduction of the size of the bytecode. Consider creating a three element Object[] with null values:
      *

      *  ANEWARRAY java/lang/Object    
      *  DUP
      *  ICONST_0
      *  ACONST_NULL
      *  AASTORE
      *  DUP
      *  ICONST_1
      *  ACONST_NULL
      *  AASTORE
      *  DUP
      *  ICONST_2
      *  ACONST_NULL
      *  AASTORE
      * 
      * with ArrayUtils you can have it like this: *
      *  ACONST_NULL
      *  ACONST_NULL
      *  ACONST_NULL
      *  INVOKESTATIC ArrayUtils.createArray(Object,Object,Object)
      * 
      * The number of needed instructions is thus reduced from 15 to 4. For every entry we save 3 bytecode instructions. * This allows better readable bytecode and it allows the JIT to see less bytecode to optimize, helping under the * inlining threshold here or there.

      * * So even though the class is ugly, there are good reason to have this in Groovy, even if the class makes * absolutely no sense in normal Java. But it is not used in normal Java, but from the bytecode. */ public class ArrayUtil { private static final Object[] EMPTY = new Object[0] ; public static Object[] createArray() { return EMPTY; } public static Object[] createArray(Object arg0) { return new Object[]{ arg0}; } public static Object[] createArray(Object arg0, Object arg1) { return new Object[]{ arg0, arg1}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2) { return new Object[]{ arg0, arg1, arg2}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3) { return new Object[]{ arg0, arg1, arg2, arg3}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4) { return new Object[]{ arg0, arg1, arg2, arg3, arg4}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244, Object arg245) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244, arg245}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244, Object arg245, Object arg246) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244, arg245, arg246}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244, Object arg245, Object arg246, Object arg247) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244, arg245, arg246, arg247}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244, Object arg245, Object arg246, Object arg247, Object arg248) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244, arg245, arg246, arg247, arg248}; } public static Object[] createArray(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object arg21, Object arg22, Object arg23, Object arg24, Object arg25, Object arg26, Object arg27, Object arg28, Object arg29, Object arg30, Object arg31, Object arg32, Object arg33, Object arg34, Object arg35, Object arg36, Object arg37, Object arg38, Object arg39, Object arg40, Object arg41, Object arg42, Object arg43, Object arg44, Object arg45, Object arg46, Object arg47, Object arg48, Object arg49, Object arg50, Object arg51, Object arg52, Object arg53, Object arg54, Object arg55, Object arg56, Object arg57, Object arg58, Object arg59, Object arg60, Object arg61, Object arg62, Object arg63, Object arg64, Object arg65, Object arg66, Object arg67, Object arg68, Object arg69, Object arg70, Object arg71, Object arg72, Object arg73, Object arg74, Object arg75, Object arg76, Object arg77, Object arg78, Object arg79, Object arg80, Object arg81, Object arg82, Object arg83, Object arg84, Object arg85, Object arg86, Object arg87, Object arg88, Object arg89, Object arg90, Object arg91, Object arg92, Object arg93, Object arg94, Object arg95, Object arg96, Object arg97, Object arg98, Object arg99, Object arg100, Object arg101, Object arg102, Object arg103, Object arg104, Object arg105, Object arg106, Object arg107, Object arg108, Object arg109, Object arg110, Object arg111, Object arg112, Object arg113, Object arg114, Object arg115, Object arg116, Object arg117, Object arg118, Object arg119, Object arg120, Object arg121, Object arg122, Object arg123, Object arg124, Object arg125, Object arg126, Object arg127, Object arg128, Object arg129, Object arg130, Object arg131, Object arg132, Object arg133, Object arg134, Object arg135, Object arg136, Object arg137, Object arg138, Object arg139, Object arg140, Object arg141, Object arg142, Object arg143, Object arg144, Object arg145, Object arg146, Object arg147, Object arg148, Object arg149, Object arg150, Object arg151, Object arg152, Object arg153, Object arg154, Object arg155, Object arg156, Object arg157, Object arg158, Object arg159, Object arg160, Object arg161, Object arg162, Object arg163, Object arg164, Object arg165, Object arg166, Object arg167, Object arg168, Object arg169, Object arg170, Object arg171, Object arg172, Object arg173, Object arg174, Object arg175, Object arg176, Object arg177, Object arg178, Object arg179, Object arg180, Object arg181, Object arg182, Object arg183, Object arg184, Object arg185, Object arg186, Object arg187, Object arg188, Object arg189, Object arg190, Object arg191, Object arg192, Object arg193, Object arg194, Object arg195, Object arg196, Object arg197, Object arg198, Object arg199, Object arg200, Object arg201, Object arg202, Object arg203, Object arg204, Object arg205, Object arg206, Object arg207, Object arg208, Object arg209, Object arg210, Object arg211, Object arg212, Object arg213, Object arg214, Object arg215, Object arg216, Object arg217, Object arg218, Object arg219, Object arg220, Object arg221, Object arg222, Object arg223, Object arg224, Object arg225, Object arg226, Object arg227, Object arg228, Object arg229, Object arg230, Object arg231, Object arg232, Object arg233, Object arg234, Object arg235, Object arg236, Object arg237, Object arg238, Object arg239, Object arg240, Object arg241, Object arg242, Object arg243, Object arg244, Object arg245, Object arg246, Object arg247, Object arg248, Object arg249) { return new Object[]{ arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30, arg31, arg32, arg33, arg34, arg35, arg36, arg37, arg38, arg39, arg40, arg41, arg42, arg43, arg44, arg45, arg46, arg47, arg48, arg49, arg50, arg51, arg52, arg53, arg54, arg55, arg56, arg57, arg58, arg59, arg60, arg61, arg62, arg63, arg64, arg65, arg66, arg67, arg68, arg69, arg70, arg71, arg72, arg73, arg74, arg75, arg76, arg77, arg78, arg79, arg80, arg81, arg82, arg83, arg84, arg85, arg86, arg87, arg88, arg89, arg90, arg91, arg92, arg93, arg94, arg95, arg96, arg97, arg98, arg99, arg100, arg101, arg102, arg103, arg104, arg105, arg106, arg107, arg108, arg109, arg110, arg111, arg112, arg113, arg114, arg115, arg116, arg117, arg118, arg119, arg120, arg121, arg122, arg123, arg124, arg125, arg126, arg127, arg128, arg129, arg130, arg131, arg132, arg133, arg134, arg135, arg136, arg137, arg138, arg139, arg140, arg141, arg142, arg143, arg144, arg145, arg146, arg147, arg148, arg149, arg150, arg151, arg152, arg153, arg154, arg155, arg156, arg157, arg158, arg159, arg160, arg161, arg162, arg163, arg164, arg165, arg166, arg167, arg168, arg169, arg170, arg171, arg172, arg173, arg174, arg175, arg176, arg177, arg178, arg179, arg180, arg181, arg182, arg183, arg184, arg185, arg186, arg187, arg188, arg189, arg190, arg191, arg192, arg193, arg194, arg195, arg196, arg197, arg198, arg199, arg200, arg201, arg202, arg203, arg204, arg205, arg206, arg207, arg208, arg209, arg210, arg211, arg212, arg213, arg214, arg215, arg216, arg217, arg218, arg219, arg220, arg221, arg222, arg223, arg224, arg225, arg226, arg227, arg228, arg229, arg230, arg231, arg232, arg233, arg234, arg235, arg236, arg237, arg238, arg239, arg240, arg241, arg242, arg243, arg244, arg245, arg246, arg247, arg248, arg249}; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/StackTraceUtils.java0000644001501200150120000001606711627206700025421 0ustar miguelmiguel/* * Copyright 2004-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * Originally was grails.utils.GrailsUtils, removed some grails specific stuff. * Utility methods removing internal lines from stack traces * * @author Graeme Rocher * @version $Revision: 5544 $ * @since 1.5 */ public class StackTraceUtils { public static final String STACK_LOG_NAME = "StackTrace"; private static final Logger STACK_LOG; // set log to consume traces by default, end user can override later static { outer: do { Enumeration existingLogs = LogManager.getLogManager().getLoggerNames(); while (existingLogs.hasMoreElements()) { if (STACK_LOG_NAME.equals(existingLogs.nextElement())) { STACK_LOG = Logger.getLogger(STACK_LOG_NAME); break outer; } } STACK_LOG = Logger.getLogger(STACK_LOG_NAME); STACK_LOG.setUseParentHandlers(false); } while (false); } private static final String[] GROOVY_PACKAGES = System.getProperty("groovy.sanitized.stacktraces", "groovy.," + "org.codehaus.groovy.," + "java.," + "javax.," + "sun.," + "gjdk.groovy.," ).split("(\\s|,)+"); private static List tests = new ArrayList(); /** *

      Adds a groovy.lang.Closure to test whether the stack trace * element should be added or not.

      *

      The groovy.lang.Closure will be given the class name as parameter. * the return value decides if the element will be added or not. *

        *
      • true - trace element will be added to the trace *
      • false - trace element will not be added to the trace *
      • null - continue with next test *
      * Groovy truth will be used to determine true and false, null is excluded from * defaulting to false here. If all tests have been executed and all of them skipped, then * the groovy standard filtering will take place.

      * * @param test the testing groovy.lang.Closure */ public static void addClassTest(Closure test) { tests.add(test); } /** *

      Remove all apparently groovy-internal trace entries from the exception instance

      *

      This modifies the original instance and returns it, it does not clone

      * * @param t the Throwable whose stack trace we want to sanitize * @return The original Throwable but with a sanitized stack trace */ public static Throwable sanitize(Throwable t) { // Note that this getBoolean access may well be synced... if (!Boolean.getBoolean("groovy.full.stacktrace")) { StackTraceElement[] trace = t.getStackTrace(); List newTrace = new ArrayList(); for (StackTraceElement stackTraceElement : trace) { if (isApplicationClass(stackTraceElement.getClassName())) { newTrace.add(stackTraceElement); } } // We don't want to lose anything, so log it STACK_LOG.log(Level.WARNING, "Sanitizing stacktrace:", t); StackTraceElement[] clean = new StackTraceElement[newTrace.size()]; newTrace.toArray(clean); t.setStackTrace(clean); } return t; } public static void printSanitizedStackTrace(Throwable t, PrintWriter p) { t = StackTraceUtils.sanitize(t); StackTraceElement[] trace = t.getStackTrace(); for (StackTraceElement stackTraceElement : trace) { p.println("at " + stackTraceElement.getClassName() + "(" + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber() + ")"); } } public static void printSanitizedStackTrace(Throwable t) { printSanitizedStackTrace(t, new PrintWriter(System.err)); } public static boolean isApplicationClass(String className) { for (Closure test : tests) { Object result = test.call(className); if (result != null) { return DefaultTypeTransformation.castToBoolean(result); } } for (String groovyPackage : GROOVY_PACKAGES) { if (className.startsWith(groovyPackage)) { return false; } } return true; } /** *

      Extracts the root cause of the exception, no matter how nested it is

      * * @param t a Throwable * @return The deepest cause of the exception that can be found */ public static Throwable extractRootCause(Throwable t) { Throwable result = t; while (result.getCause() != null) { result = result.getCause(); } return result; } /** *

      Get the root cause of an exception and sanitize it for display to the user

      *

      This will MODIFY the stacktrace of the root cause exception object and return it

      * * @param t a throwable * @return The root cause exception instance, with its stace trace modified to filter out groovy runtime classes */ public static Throwable sanitizeRootCause(Throwable t) { return StackTraceUtils.sanitize(StackTraceUtils.extractRootCause(t)); } /** *

      Sanitize the exception and ALL nested causes

      *

      This will MODIFY the stacktrace of the exception instance and all its causes irreversibly

      * * @param t a throwable * @return The root cause exception instances, with stack trace modified to filter out groovy runtime classes */ public static Throwable deepSanitize(Throwable t) { Throwable current = t; while (current.getCause() != null) { current = StackTraceUtils.sanitize(current.getCause()); } return StackTraceUtils.sanitize(t); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/InvokerInvocationException.java0000644001501200150120000000252711627206700027676 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.GroovyRuntimeException; import java.lang.reflect.InvocationTargetException; /** * An exception thrown if a method is called and an exception occurred * * @author James Strachan * @version $Revision$ */ public class InvokerInvocationException extends GroovyRuntimeException { public InvokerInvocationException(InvocationTargetException e) { super(e.getTargetException()); } public InvokerInvocationException(Throwable cause) { super(cause); } public String getMessage() { Throwable cause = getCause(); return (cause==null)?"java.lang.NullPointerException":cause.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/CurriedClosure.java0000644001501200150120000002030111707612046025273 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; /** * A wrapper for Closure to support currying. * Normally used only internally through the curry(), rcurry() or * ncurry() methods on Closure. * Typical usages: *
       * // normal usage
       * def unitAdder = { first, second, unit -> "${first + second} $unit" }
       * assert unitAdder(10, 15, "minutes") == "25 minutes"
       * assert unitAdder.curry(60)(15, "minutes") == "75 minutes"
       * def minuteAdder = unitAdder.rcurry("minutes")
       * assert minuteAdder(15, 60) == "75 minutes"
       *
       * // explicit creation
       * import org.codehaus.groovy.runtime.CurriedClosure
       * assert new CurriedClosure(unitAdder, 45)(15, "minutes") == "60 minutes"
       * assert new CurriedClosure(unitAdder, "six", "ty")("minutes") == "sixty minutes"
       * 
      * * @author Jochen Theodorou * @author Paul King */ public final class CurriedClosure extends Closure { private Object[] curriedParams; private int index; private int numTrailingArgs = 0; private Class varargType = null; public CurriedClosure(int index, Closure uncurriedClosure, Object... arguments) { super(uncurriedClosure.clone()); curriedParams = arguments; this.index = index; final int origMaxLen = uncurriedClosure.getMaximumNumberOfParameters(); maximumNumberOfParameters = origMaxLen - arguments.length; Class[] classes = uncurriedClosure.getParameterTypes(); Class lastType = classes.length == 0 ? null : classes[classes.length-1]; if (lastType != null && lastType.isArray()) { varargType = lastType; } if (isVararg()) { if (index < 0) { numTrailingArgs = (-index) - arguments.length; } } else { // perform some early param checking for non-vararg case if (index < 0) { // normalise this.index += origMaxLen; } if (maximumNumberOfParameters < 0) { throw new IllegalArgumentException("Can't curry " + arguments.length + " arguments for a closure with " + origMaxLen + " parameters."); } if (index < 0) { if (index < -origMaxLen || index > -arguments.length) throw new IllegalArgumentException("To curry " + arguments.length + " argument(s) expect index range " + (-origMaxLen) + ".." + (-arguments.length) + " but found " + index); } else if (index > maximumNumberOfParameters) { throw new IllegalArgumentException("To curry " + arguments.length + " argument(s) expect index range 0.." + maximumNumberOfParameters + " but found " + index); } } } public CurriedClosure(Closure uncurriedClosure, Object... arguments) { this(0, uncurriedClosure, arguments); } public Object[] getUncurriedArguments(Object... arguments) { if (isVararg()) { int normalizedIndex = index < 0 ? index + arguments.length + curriedParams.length : index; if (normalizedIndex < 0 || normalizedIndex > arguments.length) { throw new IllegalArgumentException("When currying expected index range between " + (-arguments.length - curriedParams.length) + ".." + (arguments.length + curriedParams.length) + " but found " + index); } final Object newCurriedParams[] = new Object[curriedParams.length + arguments.length]; System.arraycopy(arguments, 0, newCurriedParams, 0, normalizedIndex); System.arraycopy(curriedParams, 0, newCurriedParams, normalizedIndex, curriedParams.length); if (arguments.length - normalizedIndex > 0) System.arraycopy(arguments, normalizedIndex, newCurriedParams, curriedParams.length + normalizedIndex, arguments.length - normalizedIndex); return newCurriedParams; } final Object newCurriedParams[] = new Object[curriedParams.length + arguments.length]; System.arraycopy(arguments, 0, newCurriedParams, 0, index); System.arraycopy(curriedParams, 0, newCurriedParams, index, curriedParams.length); if (arguments.length - index > 0) System.arraycopy(arguments, index, newCurriedParams, curriedParams.length + index, arguments.length - index); return newCurriedParams; } public void setDelegate(Object delegate) { ((Closure) getOwner()).setDelegate(delegate); } public Object getDelegate() { return ((Closure) getOwner()).getDelegate(); } public void setResolveStrategy(int resolveStrategy) { ((Closure) getOwner()).setResolveStrategy(resolveStrategy); } public int getResolveStrategy() { return ((Closure) getOwner()).getResolveStrategy(); } @SuppressWarnings("unchecked") public Object clone() { Closure uncurriedClosure = (Closure) ((Closure) getOwner()).clone(); return new CurriedClosure(index, uncurriedClosure, curriedParams); } public Class[] getParameterTypes() { Class[] oldParams = ((Closure) getOwner()).getParameterTypes(); int extraParams = 0; int gobbledParams = curriedParams.length; if (isVararg()) { int numNonVarargs = oldParams.length - 1; if (index < 0) { int absIndex = index < 0 ? -index : index; // do -ve indexes based on actual args, so can't accurately calculate type here // so work out minimal type params and vararg on end will allow for other possibilities if (absIndex > numNonVarargs) gobbledParams = numNonVarargs; int newNumNonVarargs = numNonVarargs - gobbledParams; if (absIndex - curriedParams.length > newNumNonVarargs) extraParams = absIndex - curriedParams.length - newNumNonVarargs; int keptParams = Math.max(numNonVarargs - absIndex, 0); Class[] newParams = new Class[keptParams + newNumNonVarargs + extraParams + 1]; System.arraycopy(oldParams, 0, newParams, 0, keptParams); for (int i = 0; i < newNumNonVarargs; i++) newParams[keptParams + i] = Object.class; for (int i = 0; i < extraParams; i++) newParams[keptParams + newNumNonVarargs + i] = varargType.getComponentType(); newParams[newParams.length - 1] = varargType; return newParams; } int leadingKept = Math.min(index, numNonVarargs); int trailingKept = Math.max(numNonVarargs - leadingKept - curriedParams.length, 0); if (index > leadingKept) extraParams = index - leadingKept; Class[] newParams = new Class[leadingKept + trailingKept + extraParams + 1]; System.arraycopy(oldParams, 0, newParams, 0, leadingKept); if (trailingKept > 0) System.arraycopy(oldParams, leadingKept + curriedParams.length, newParams, leadingKept, trailingKept); for (int i = 0; i < extraParams; i++) newParams[leadingKept + trailingKept + i] = varargType.getComponentType(); newParams[newParams.length - 1] = varargType; return newParams; } Class[] newParams = new Class[oldParams.length - gobbledParams + extraParams]; System.arraycopy(oldParams, 0, newParams, 0, index); if (newParams.length - index > 0) System.arraycopy(oldParams, curriedParams.length + index, newParams, index, newParams.length - index); return newParams; } private boolean isVararg() { return varargType != null; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java0000644001501200150120000002232311707612046027635 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; import groovy.lang.Closure; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ResourceBundle; import java.util.Locale; import java.util.regex.Matcher; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.reflection.ReflectionUtils; /** * This class defines all the new static groovy methods which appear on normal * JDK classes inside the Groovy environment. Static methods are used with the * first parameter as the destination class. * * @author Guillaume Laforge * @author Dierk Koenig * @author Joachim Baumann * @author Paul King * @version $Revision$ */ public class DefaultGroovyStaticMethods { /** * Start a Thread with the given closure as a Runnable instance. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param closure the Runnable closure * @return the started thread * @since 1.0 */ public static Thread start(Thread self, Closure closure) { return createThread(null, false, closure); } /** * Start a Thread with a given name and the given closure * as a Runnable instance. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param name the name to give the thread * @param closure the Runnable closure * @return the started thread * @since 1.6 */ public static Thread start(Thread self, String name, Closure closure) { return createThread(name, false, closure); } /** * Start a daemon Thread with the given closure as a Runnable instance. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param closure the Runnable closure * @return the started thread * @since 1.0 */ public static Thread startDaemon(Thread self, Closure closure) { return createThread(null, true, closure); } /** * Start a daemon Thread with a given name and the given closure as * a Runnable instance. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param name the name to give the thread * @param closure the Runnable closure * @return the started thread * @since 1.6 */ public static Thread startDaemon(Thread self, String name, Closure closure) { return createThread(name, true, closure); } private static Thread createThread(String name, boolean daemon, Closure closure) { Thread thread = name != null ? new Thread(closure, name) : new Thread(closure); if (daemon) thread.setDaemon(true); thread.start(); return thread; } /** * Get the last hidden matcher that the system used to do a match. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @return the last regex matcher * @since 1.0 */ public static Matcher getLastMatcher(Matcher self) { return RegexSupport.getLastMatcher(); } /** * This method is used by both sleep() methods to implement sleeping * for the given time even if interrupted * * @param millis the number of milliseconds to sleep * @param closure optional closure called when interrupted * as long as the closure returns false the sleep continues */ private static void sleepImpl(long millis, Closure closure) { long start = System.currentTimeMillis(); long rest = millis; long current; while (rest > 0) { try { Thread.sleep(rest); rest = 0; } catch (InterruptedException e) { if (closure != null) { if (DefaultTypeTransformation.castToBoolean(closure.call(e))) { return; } } current = System.currentTimeMillis(); // compensate for closure's time rest = millis + start - current; } } } /** * Sleep for so many milliseconds, even if interrupted. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param milliseconds the number of milliseconds to sleep * @since 1.0 */ public static void sleep(Object self, long milliseconds) { sleepImpl(milliseconds, null); } /** * Sleep for so many milliseconds, using a given closure for interrupt processing. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param milliseconds the number of milliseconds to sleep * @param onInterrupt interrupt handler, InterruptedException is passed to the Closure * as long as it returns false, the sleep continues * @since 1.0 */ public static void sleep(Object self, long milliseconds, Closure onInterrupt) { sleepImpl(milliseconds, onInterrupt); } /** * Parse a String into a Date instance using the given pattern. * This convenience method acts as a wrapper for {@link java.text.SimpleDateFormat}. *

      *

      Note that a new SimpleDateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param format pattern used to parse the input string. * @param input String to be parsed to create the date instance * @return a new Date instance representing the parsed input string * @throws ParseException if there is a parse error * @see java.text.SimpleDateFormat#parse(java.lang.String) * @since 1.5.7 */ public static Date parse(Date self, String format, String input) throws ParseException { return new SimpleDateFormat(format).parse(input); } /** * Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy * containing US-locale-constants only (e.g. Sat for Saturdays). * Such a string is generated by the toString method of {@link java.util.Date} *

      Note that a new SimpleDateFormat instance is created for every * invocation of this method (for thread safety).

      * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param dateToString String to be parsed to create the date instance. Must match the pattern EEE MMM dd HH:mm:ss zzz yyyy with US-locale symbols * @return a new Date instance representing the parsed input string * @throws ParseException if there is a parse error */ public static Date parseToStringDate(Date self, String dateToString) throws ParseException { return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(dateToString); } /** * Works exactly like ResourceBundle.getBundle(String). This is needed * because the java method depends on a particular stack configuration that * is not guaranteed in Groovy when calling the Java method. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param bundleName the name of the bundle. * @return the resource bundle * @see java.util.ResourceBundle#getBundle(java.lang.String) * @since 1.6.0 */ public static ResourceBundle getBundle(ResourceBundle self, String bundleName) { return getBundle(self, bundleName, Locale.getDefault()); } /** * Works exactly like ResourceBundle.getBundle(String, Locale). This is needed * because the java method depends on a particular stack configuration that * is not guaranteed in Groovy when calling the Java method. * * @param self placeholder variable used by Groovy categories; ignored for default static methods * @param bundleName the name of the bundle. * @param locale the specific locale * @return the resource bundle * @see java.util.ResourceBundle#getBundle(java.lang.String, java.util.Locale) * @since 1.6.0 */ public static ResourceBundle getBundle(ResourceBundle self, String bundleName, Locale locale) { Class c = ReflectionUtils.getCallingClass(); ClassLoader targetCL = c != null ? c.getClassLoader() : null; if (targetCL == null) targetCL = ClassLoader.getSystemClassLoader(); return ResourceBundle.getBundle(bundleName, locale, targetCL); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/0000755001501200150120000000000011707612046023147 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/NullProtectionStorage.java0000644001501200150120000000223511707612046030322 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.memoize; /** * A NullObject pattern implementation for ProtectionStorage * Doesn't protect any resources. * Used when the user doesn't mind to eventually have the whole memoize cache emptied by gc. * * @author Vaclav Pech */ public final class NullProtectionStorage implements ProtectionStorage{ /** * Does nothing * * @param key The key of the element to renew * @param value A value to newly associate with the key */ public void touch(final Object key, final Object value) { } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/ProtectionStorage.java0000644001501200150120000000171111707612046027465 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.memoize; /** * Protects stored resources from eviction from memory following the LRU (Last Recently Used) strategy. * The touch method can be used to renew an element and move it to the from the LRU queue. * * @author Vaclav Pech */ interface ProtectionStorage { void touch(Object key, Object value); } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/Memoize.java0000644001501200150120000001577611707612046025437 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.memoize; import groovy.lang.Closure; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.Collections; import static java.util.Arrays.asList; /** * Implements memoize for Closures. * It is supposed to be used by the Closure class itself to implement the memoize() family of methods. * * @author Vaclav Pech */ public abstract class Memoize { /** * A place-holder for null values in cache */ final static private MemoizeNullValue MEMOIZE_NULL = new MemoizeNullValue(); /** * Creates a new closure delegating to the supplied one and memoizing all return values by the arguments. * * The supplied cache is used to store the memoized values and it is the cache's responsibility to put limits * on the cache size or implement cache eviction strategy. * The LRUCache, for example, allows to set the maximum cache size constraint and implements * the LRU (Last Recently Used) eviction strategy. * * @param cache A map to hold memoized return values * @param closure The closure to memoize * @param The closure's return type * @return A new memoized closure */ public static Closure buildMemoizeFunction(final MemoizeCache cache, final Closure closure) { return new MemoizeFunction(cache, closure); } /** * Creates a new closure delegating to the supplied one and memoizing all return values by the arguments. * The memoizing closure will use SoftReferences to remember the return values allowing the garbage collector * to reclaim the memory, if needed. * * The supplied cache is used to store the memoized values and it is the cache's responsibility to put limits * on the cache size or implement cache eviction strategy. * The LRUCache, for example, allows to set the maximum cache size constraint and implements * the LRU (Last Recently Used) eviction strategy. * * If the protectedCacheSize argument is greater than 0 an optional LRU (Last Recently Used) cache of hard references * is maintained to protect recently touched memoized values against eviction by the garbage collector. * * @param protectedCacheSize The number of hard references to keep in order to prevent some (LRU) memoized return values from eviction * @param cache A map to hold memoized return values * @param closure The closure to memoize * @param The closure's return type * @return A new memoized closure */ public static Closure buildSoftReferenceMemoizeFunction(final int protectedCacheSize, final MemoizeCache cache, final Closure closure) { final ProtectionStorage lruProtectionStorage = protectedCacheSize > 0 ? new LRUProtectionStorage(protectedCacheSize) : new NullProtectionStorage(); // Nothing should be done when no elements need protection against eviction final ReferenceQueue queue = new ReferenceQueue(); return new SoftReferenceMemoizeFunction(cache, closure, lruProtectionStorage, queue); } /** * Creates a key to use in the memoize cache * * @param args The arguments supplied to the closure invocation * * @return The key - a list holding all arguments */ private static Object generateKey(final Object[] args) { if (args == null) return Collections.emptyList(); return asList(args); } /** * A place-holder for cached null values */ private static class MemoizeNullValue { @Override public boolean equals(final Object obj) { return obj instanceof MemoizeNullValue; } @Override public int hashCode() { return "MemoizeNullValue".hashCode(); } } private static class MemoizeFunction extends Closure { final MemoizeCache cache; final Closure closure; MemoizeFunction(final MemoizeCache cache, Closure closure) { super(closure.getOwner()); this.cache = cache; this.closure = closure; } @Override public V call(final Object... args) { final Object key = generateKey(args); Object result = cache.get(key); if (result == null) { result = closure.call(args); //noinspection GroovyConditionalCanBeElvis cache.put(key, result != null ? result : MEMOIZE_NULL); } return result == MEMOIZE_NULL ? null : (V) result; } } private static class SoftReferenceMemoizeFunction extends MemoizeFunction { final ProtectionStorage lruProtectionStorage; final ReferenceQueue queue; SoftReferenceMemoizeFunction(final MemoizeCache cache, Closure closure, ProtectionStorage lruProtectionStorage, ReferenceQueue queue) { super(cache, closure); this.lruProtectionStorage = lruProtectionStorage; this.queue = queue; } @Override public V call(final Object... args) { if (queue.poll() != null) cleanUpNullReferences(cache, queue); // if something has been evicted, do a clean-up final Object key = generateKey(args); final SoftReference reference = (SoftReference) cache.get(key); Object result = reference != null ? reference.get() : null; if (result == null) { result = closure.call(args); if (result == null) { result = MEMOIZE_NULL; } cache.put(key, new SoftReference(result)); } lruProtectionStorage.touch(key, result); return result == MEMOIZE_NULL ? null : (V) result; } /** * After the garbage collector has done its job, we need to clean the cache from references to all the evicted memoized values. * @param cache The cache to prune * @param queue A reference queue holding references to gc-evicted memoized values */ private static void cleanUpNullReferences(final MemoizeCache cache, final ReferenceQueue queue) { while(queue.poll() != null) {} //empty the reference queue cache.cleanUpNullReferences(); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/LRUProtectionStorage.java0000644001501200150120000000462011707612046030052 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.memoize; import java.util.LinkedHashMap; import java.util.Map; /** * Protects stored resources from eviction from memory following the LRU (Last Recently Used) strategy. * If the maximum size has been reached all newly added elements will cause the oldest element to be removed from the storage * in order not to exceed the maximum capacity. * The touch method can be used to renew an element and move it to the from the LRU queue. * * @author Vaclav Pech */ final class LRUProtectionStorage extends LinkedHashMap implements ProtectionStorage { private static final long serialVersionUID = 1L; private final int maxSize; public LRUProtectionStorage(final int maxSize) { this.maxSize = maxSize; } /** * The eldest entry should be removed when we reached the maximum cache size */ @Override protected boolean removeEldestEntry(final Map.Entry eldest) { return size() > maxSize; } /** * The touch method can be used to renew an element and move it to the from of the LRU queue. * * @param key The key of the element to renew * @param value A value to newly associate with the key */ public synchronized void touch(final Object key, final Object value) { remove(key); put(key, value); } /** * Makes sure the retrieved object is moved to the head of the LRU list */ @Override public synchronized Object get(final Object key) { final Object value = remove(key); if (value != null) put(key, value); return value; } /** * Performs a shallow clone * * @return The cloned instance */ @Override public Object clone() { return super.clone(); } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/MemoizeCache.java0000644001501200150120000000121311707612046026340 0ustar miguelmiguelpackage org.codehaus.groovy.runtime.memoize; /** * Represents a memoize cache with its essential methods * @param type of the keys * @param type of the values * * @author Vaclav Pech */ public interface MemoizeCache { V put(K key, V value); V get(K key); /** * Invoked when some of the held SoftReferences have been evicted by the garbage collector and so should be removed from the cache. * The implementation must ensure that concurrent invocations of all methods on the cache may occur from other threads * and thus should protect any shared resources. */ void cleanUpNullReferences(); } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/UnlimitedConcurrentCache.java0000644001501200150120000000232211707612046030732 0ustar miguelmiguelpackage org.codehaus.groovy.runtime.memoize; import java.lang.ref.SoftReference; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A cache backed by a ConcurrentHashMap * * @author Vaclav Pech */ public final class UnlimitedConcurrentCache implements MemoizeCache { private final ConcurrentHashMap cache = new ConcurrentHashMap(); public Object put(final Object key, final Object value) { return cache.put(key, value); } public Object get(final Object key) { return cache.get(key); } /** * Replying on the ConcurrentHashMap thread-safe iteration implementation the method will remove all entries holding * SoftReferences to gc-evicted objects. */ public void cleanUpNullReferences() { final Iterator> iterator = cache.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry entry = iterator.next(); Object entryVal = entry.getValue(); if (entryVal != null && ((SoftReference) entryVal).get() == null) cache.remove(entry.getKey(), entryVal); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/memoize/LRUCache.java0000644001501200150120000000240311707612046025377 0ustar miguelmiguelpackage org.codehaus.groovy.runtime.memoize; import java.lang.ref.SoftReference; import java.util.Collections; import java.util.Iterator; import java.util.Map; /** * A cache backed by a Collections.SynchronizedMap * * @author Vaclav Pech */ public final class LRUCache implements MemoizeCache { private final Map cache; public LRUCache(final int maxCacheSize) { cache = Collections.synchronizedMap(new LRUProtectionStorage(maxCacheSize)); } public Object put(final Object key, final Object value) { return cache.put(key, value); } public Object get(final Object key) { return cache.get(key); } /** * Replying on the Collections.SynchronizedMap thread-safe iteration implementation the method will remove all entries holding * SoftReferences to gc-evicted objects. */ public void cleanUpNullReferences() { synchronized (cache) { final Iterator> iterator = cache.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry entry = iterator.next(); if (((SoftReference) entry.getValue()).get() == null) iterator.remove(); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/0000755001501200150120000000000011707612046023133 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberPlus.java0000644001501200150120000003600211627206700027241 0ustar miguelmiguel/* * Copyright 2003-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.typehandling.NumberMath; public final class NumberNumberPlus extends NumberNumberMetaMethod { public String getName() { return "plus"; } public Object invoke(Object object, Object[] arguments) { return NumberMath.add((Number) object, (Number) arguments[0]); } /** * Add two numbers and return the result. * * @param left a Number * @param right another Number to add * @return the addition of both Numbers */ public static Number plus(Number left, Number right) { return NumberMath.add(left, right); } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (receiver instanceof Integer) { if (args[0] instanceof Integer) return new IntegerInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new IntegerLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new IntegerFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new IntegerDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Long) { if (args[0] instanceof Integer) return new LongInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new LongLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new LongFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new LongDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Float) { if (args[0] instanceof Integer) return new FloatInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new FloatLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new FloatFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new FloatDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Double) { if (args[0] instanceof Integer) return new DoubleInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new DoubleLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new DoubleFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new DoubleDouble(site, metaClass, metaMethod, params, receiver, args); } return new NumberNumberCallSite(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]) { public Object invoke(Object receiver, Object[] args) { return math.addImpl((Number) receiver, (Number) args[0]); } public Object invoke(Object receiver, Object arg) { return math.addImpl((Number) receiver, (Number) arg); } }; } private static class DoubleDouble extends NumberNumberCallSite { public DoubleDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Double) receiver + (Double) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleFloat extends NumberNumberCallSite { public DoubleFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Double) receiver + ((Float) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleLong extends NumberNumberCallSite { public DoubleLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Double) receiver + ((Long) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleInteger extends NumberNumberCallSite { public DoubleInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Double) receiver + (Integer) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatDouble extends NumberNumberCallSite { public FloatDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Float) receiver).doubleValue() + (Double) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatFloat extends NumberNumberCallSite { public FloatFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Float) receiver).doubleValue() + ((Float) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatLong extends NumberNumberCallSite { public FloatLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Float) receiver).doubleValue() + ((Long) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatInteger extends NumberNumberCallSite { public FloatInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Float) receiver).doubleValue() + ((Integer) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongDouble extends NumberNumberCallSite { public LongDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Long) receiver).doubleValue() + (Double) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongFloat extends NumberNumberCallSite { public LongFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Long) receiver).doubleValue() + ((Float) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongLong extends NumberNumberCallSite { public LongLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Long) receiver + (Long) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongInteger extends NumberNumberCallSite { public LongInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Long) receiver + ((Integer) arg).longValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerDouble extends NumberNumberCallSite { public IntegerDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Integer) receiver).doubleValue() + (Double) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerFloat extends NumberNumberCallSite { public IntegerFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Integer) receiver).doubleValue() + ((Float) arg).doubleValue(); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerLong extends NumberNumberCallSite { public IntegerLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return ((Integer) receiver).longValue() + (Long) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerInteger extends NumberNumberCallSite { public IntegerInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return (Integer) receiver + (Integer) arg; } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMultiply.java0000644001501200150120000003753511627206700030151 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.typehandling.NumberMath; public final class NumberNumberMultiply extends NumberNumberMetaMethod { public String getName() { return "multiply"; } public Object invoke(Object object, Object[] arguments) { return NumberMath.multiply((Number) object, (Number) arguments[0]); } /** * Multiply two Numbers. * * @param left a Number * @param right another Number * @return the multiplication of both */ //Note: This method is NOT called if left AND right are both BigIntegers or BigDecimals because //those classes implement a method with a better exact match. public static Number multiply(Number left, Number right) { return NumberMath.multiply(left, right); } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (receiver instanceof Integer) { if (args[0] instanceof Integer) return new IntegerInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new IntegerLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new IntegerFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new IntegerDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Long) { if (args[0] instanceof Integer) return new LongInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new LongLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new LongFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new LongDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Float) { if (args[0] instanceof Integer) return new FloatInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new FloatLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new FloatFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new FloatDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Double) { if (args[0] instanceof Integer) return new DoubleInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new DoubleLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new DoubleFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new DoubleDouble(site, metaClass, metaMethod, params, receiver, args); } return new NumberNumber(site, metaClass, metaMethod, params, receiver, args); } private static class DoubleDouble extends NumberNumberCallSite { public DoubleDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() * ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleFloat extends NumberNumberCallSite { public DoubleFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() * ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleLong extends NumberNumberCallSite { public DoubleLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() * ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleInteger extends NumberNumberCallSite { public DoubleInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() * ((Integer) arg).intValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatDouble extends NumberNumberCallSite { public FloatDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() * ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatFloat extends NumberNumberCallSite { public FloatFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() * ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatLong extends NumberNumberCallSite { public FloatLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() * ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatInteger extends NumberNumberCallSite { public FloatInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() * ((Integer) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongDouble extends NumberNumberCallSite { public LongDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() * ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongFloat extends NumberNumberCallSite { public LongFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() * ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongLong extends NumberNumberCallSite { public LongLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Long) receiver).longValue() * ((Long) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongInteger extends NumberNumberCallSite { public LongInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Long) receiver).longValue() * ((Integer) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerDouble extends NumberNumberCallSite { public IntegerDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).doubleValue() * ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerFloat extends NumberNumberCallSite { public IntegerFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).doubleValue() * ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerLong extends NumberNumberCallSite { public IntegerLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Integer) receiver).longValue() * ((Long) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerInteger extends NumberNumberCallSite { public IntegerInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Integer(((Integer) receiver).intValue() * ((Integer) arg).intValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class NumberNumber extends NumberNumberCallSite { public NumberNumber(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object invoke(Object receiver, Object[] args) { return math.multiplyImpl((Number)receiver,(Number)args[0]); } public final Object invoke(Object receiver, Object arg) { return math.multiplyImpl((Number)receiver,(Number)arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.java0000644001501200150120000003240211627206700027040 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.typehandling.NumberMath; public final class NumberNumberDiv extends NumberNumberMetaMethod { public String getName() { return "div"; } public Object invoke(Object object, Object[] arguments) { return NumberMath.divide((Number) object, (Number) arguments[0]); } /** * Divide two Numbers. * * Note: Method name different from 'divide' to avoid collision with BigInteger method that has * different semantics. We want a BigDecimal result rather than a BigInteger. * * @param left a Number * @param right another Number * @return a Number resulting of the divide operation */ public static Number div(Number left, Number right) { return NumberMath.divide(left, right); } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (receiver instanceof Integer) { if (args[0] instanceof Float) return new IntegerFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new IntegerDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Long) { if (args[0] instanceof Float) return new LongFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new LongDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Float) { if (args[0] instanceof Integer) return new FloatInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new FloatLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new FloatFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new FloatDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Double) { if (args[0] instanceof Integer) return new DoubleInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new DoubleLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new DoubleFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new DoubleDouble(site, metaClass, metaMethod, params, receiver, args); } return new NumberNumber(site, metaClass, metaMethod, params, receiver, args); } private static class IntegerFloat extends NumberNumberCallSite { public IntegerFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).doubleValue() / ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerDouble extends NumberNumberCallSite { public IntegerDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).intValue() / ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongFloat extends NumberNumberCallSite { public LongFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() / ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongDouble extends NumberNumberCallSite { public LongDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() / ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatInteger extends NumberNumberCallSite { public FloatInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() / ((Integer) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatLong extends NumberNumberCallSite { public FloatLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() / ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatFloat extends NumberNumberCallSite { public FloatFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() / ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } public final Object invoke(Object receiver, Object[] args) { return new Double(((Float) receiver).doubleValue() / ((Float) args[0]).doubleValue()); } public final Object invoke(Object receiver, Object arg) { return new Double(((Float) receiver).doubleValue() / ((Float) arg).doubleValue()); } } private static class FloatDouble extends NumberNumberCallSite { public FloatDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() / ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleInteger extends NumberNumberCallSite { public DoubleInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() / ((Integer) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } public final Object invoke(Object receiver, Object[] args) { return new Double(((Double) receiver).doubleValue() / ((Integer) args[0]).doubleValue()); } public final Object invoke(Object receiver, Object arg) { return new Double(((Double) receiver).doubleValue() / ((Integer) arg).doubleValue()); } } private static class DoubleLong extends NumberNumberCallSite { public DoubleLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() / ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleFloat extends NumberNumberCallSite { public DoubleFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() / ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleDouble extends NumberNumberCallSite { public DoubleDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() / ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class NumberNumber extends NumberNumberCallSite { public NumberNumber(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object invoke(Object receiver, Object[] args) { return math.divideImpl((Number)receiver,(Number)args[0]); } public final Object invoke(Object receiver, Object arg) { return math.divideImpl((Number)receiver,(Number)arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMetaMethod.java0000644001501200150120000001077011627206700030351 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.CallSiteAwareMetaMethod; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.NumberMath; import java.lang.reflect.Modifier; public abstract class NumberNumberMetaMethod extends CallSiteAwareMetaMethod { private static final CachedClass NUMBER_CLASS = ReflectionCache.getCachedClass(Number.class); private static final CachedClass [] NUMBER_CLASS_ARR = new CachedClass[] { NUMBER_CLASS }; protected NumberNumberMetaMethod() { parameterTypes = NUMBER_CLASS_ARR; } public int getModifiers() { return Modifier.PUBLIC; } public Class getReturnType() { return NUMBER_CLASS.getTheClass(); } public final CachedClass getDeclaringClass() { return NUMBER_CLASS; } public abstract static class NumberNumberCallSite extends PojoMetaMethodSite { final NumberMath math; public NumberNumberCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Number receiver, Number arg) { super(site, metaClass, metaMethod, params); math = NumberMath.getMath(receiver,arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus.java0000644001501200150120000003730511707612046027423 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.typehandling.NumberMath; public final class NumberNumberMinus extends NumberNumberMetaMethod { public String getName() { return "minus"; } public Object invoke(Object object, Object[] arguments) { return NumberMath.subtract((Number) object, (Number) arguments[0]); } /** * Subtraction of two Numbers. * * @param left a Number * @param right another Number to subtract to the first one * @return the subtraction */ public static Number minus(Number left, Number right) { return NumberMath.subtract(left, right); } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (receiver instanceof Integer) { if (args[0] instanceof Integer) return new IntegerInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new IntegerLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new IntegerFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new IntegerDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Long) { if (args[0] instanceof Integer) return new LongInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new LongLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new LongFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new LongDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Float) { if (args[0] instanceof Integer) return new FloatInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new FloatLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new FloatFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new FloatDouble(site, metaClass, metaMethod, params, receiver, args); } if (receiver instanceof Double) { if (args[0] instanceof Integer) return new DoubleInteger(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Long) return new DoubleLong(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Float) return new DoubleFloat(site, metaClass, metaMethod, params, receiver, args); if (args[0] instanceof Double) return new DoubleDouble(site, metaClass, metaMethod, params, receiver, args); } return new NumberNumber(site, metaClass, metaMethod, params, receiver, args); } private static class DoubleDouble extends NumberNumberCallSite { public DoubleDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() - ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleFloat extends NumberNumberCallSite { public DoubleFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() - ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleLong extends NumberNumberCallSite { public DoubleLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() - ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class DoubleInteger extends NumberNumberCallSite { public DoubleInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Double) receiver).doubleValue() - ((Integer) arg).intValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatDouble extends NumberNumberCallSite { public FloatDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() - ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatFloat extends NumberNumberCallSite { public FloatFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() - ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatLong extends NumberNumberCallSite { public FloatLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() - ((Long) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class FloatInteger extends NumberNumberCallSite { public FloatInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Float) receiver).doubleValue() - ((Integer) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongDouble extends NumberNumberCallSite { public LongDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() - ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongFloat extends NumberNumberCallSite { public LongFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Long) receiver).doubleValue() - ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongLong extends NumberNumberCallSite { public LongLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Long) receiver).longValue() - ((Long) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class LongInteger extends NumberNumberCallSite { public LongInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Long) receiver).longValue() - ((Integer) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerDouble extends NumberNumberCallSite { public IntegerDouble(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).doubleValue() - ((Double) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerFloat extends NumberNumberCallSite { public IntegerFloat(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Double(((Integer) receiver).doubleValue() - ((Float) arg).doubleValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerLong extends NumberNumberCallSite { public IntegerLong(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Long(((Integer) receiver).longValue() - ((Long) arg).longValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class IntegerInteger extends NumberNumberCallSite { public IntegerInteger(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object call(Object receiver, Object arg) throws Throwable { try { if (checkPojoMetaClass()) { return new Integer(((Integer) receiver).intValue() - ((Integer) arg).intValue()); } } catch (ClassCastException e) {// } return super.call(receiver, arg); } } private static class NumberNumber extends NumberNumberCallSite { public NumberNumber(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { super(site, metaClass, metaMethod, params, (Number) receiver, (Number) args[0]); } public final Object invoke(Object receiver, Object[] args) { return math.subtractImpl((Number)receiver,(Number)args[0]); } public final Object invoke(Object receiver, Object arg) { return math.subtractImpl((Number)receiver,(Number)arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/0000755001501200150120000000000011627206700024431 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayGetAtMetaMethod.java0000644001501200150120000000477211627206700032247 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class FloatArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(float[].class); public Class getReturnType() { return Float.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final float[] objects = (float[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof float[] && arg instanceof Integer) && checkPojoMetaClass()) { final float[] objects = (float[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayPutAtMetaMethod.java0000644001501200150120000001005111627206700032115 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class LongArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(long[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public LongArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final long[] objects = (long[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Long)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Long) DefaultTypeTransformation.castToType(ch, Long.class); } else { objects[index] = ((Number) newValue).longValue(); } } else objects[index] = (Long) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Long)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof long[] && args[0] instanceof Integer && args[1] instanceof Long) && checkPojoMetaClass()) { final long[] objects = (long[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Long) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final long[] objects = (long[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Long) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof long[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/LongArrayGetAtMetaMethod.java0000644001501200150120000000476211627206700032100 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class LongArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(long[].class); public Class getReturnType() { return Long.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final long[] objects = (long[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof long[] && arg instanceof Integer) && checkPojoMetaClass()) { final long[] objects = (long[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayGetAtMetaMethod.java0000644001501200150120000000476211627206700032104 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class ByteArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(byte[].class); public Class getReturnType() { return Byte.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final byte[] objects = (byte[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof byte[] && arg instanceof Integer) && checkPojoMetaClass()) { final byte[] objects = (byte[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayPutAtMetaMethod.java0000644001501200150120000001007511627206700032621 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class IntegerArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(int[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public IntegerArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final int[] objects = (int[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Integer)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Integer) DefaultTypeTransformation.castToType(ch, Integer.class); } else { objects[index] = ((Number) newValue).intValue(); } } else objects[index] = (Integer) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof int[] && args[0] instanceof Integer && args[1] instanceof Integer) && checkPojoMetaClass()) { final int[] objects = (int[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Integer) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final int[] objects = (int[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Integer) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof int[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/FloatArrayPutAtMetaMethod.java0000644001501200150120000001007511627206700032271 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class FloatArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(float[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public FloatArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final float[] objects = (float[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Float)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Float) DefaultTypeTransformation.castToType(ch, Float.class); } else { objects[index] = ((Number) newValue).floatValue(); } } else objects[index] = (Float) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Float)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof float[] && args[0] instanceof Integer && args[1] instanceof Float) && checkPojoMetaClass()) { final float[] objects = (float[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Float) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final float[] objects = (float[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Float) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof float[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ByteArrayPutAtMetaMethod.java0000644001501200150120000000716211627206700032132 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class ByteArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(byte[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public ByteArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final byte[] objects = (byte[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Byte)) { objects[index] = ((Number) newValue).byteValue(); } else objects[index] = (Byte) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Byte)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof byte[] && args[0] instanceof Integer && args[1] instanceof Byte) && checkPojoMetaClass()) { final byte[] objects = (byte[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Byte) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final byte[] objects = (byte[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Byte) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof byte[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayGetAtMetaMethod.java0000644001501200150120000000157611627206700031260 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; public abstract class ArrayGetAtMetaMethod extends ArrayMetaMethod { protected ArrayGetAtMetaMethod() { parameterTypes = INTEGER_CLASS_ARR; } public String getName() { return "getAt"; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayGetAtMetaMethod.java0000644001501200150120000000500211627206700032377 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class DoubleArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(double[].class); public Class getReturnType() { return Double.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final double[] objects = (double[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof double[] && arg instanceof Integer) && checkPojoMetaClass()) { final double[] objects = (double[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/IntegerArrayGetAtMetaMethod.java0000644001501200150120000000476211627206700032576 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class IntegerArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(int[].class); public Class getReturnType() { return Integer.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final int[] objects = (int[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof int[] && arg instanceof Integer) && checkPojoMetaClass()) { final int[] objects = (int[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayPutAtMetaMethod.java0000644001501200150120000000727411627206700033127 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class CharacterArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(char[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public CharacterArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final char[] objects = (char[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); objects[index] = DefaultTypeTransformation.getCharFromSizeOneString(args[1]); return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Character)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof char[] && args[0] instanceof Integer && args[1] instanceof Character) && checkPojoMetaClass()) { final char[] objects = (char[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Character) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final char[] objects = (char[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Character) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof char[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayGetAtMetaMethod.java0000644001501200150120000000523311627206700032401 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class ObjectArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass OBJECT_ARR_CLASS = ReflectionCache.OBJECT_ARRAY_CLASS; public Class getReturnType() { return Object.class; } public final CachedClass getDeclaringClass() { return OBJECT_ARR_CLASS; } public Object invoke(Object object, Object[] arguments) { final Object[] objects = (Object[]) object; return objects[normaliseIndex((Integer) arguments[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if (checkPojoMetaClass()) { try { final Object[] objects = (Object[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } catch (ClassCastException e) { if ((receiver instanceof Object[]) && (arg instanceof Integer)) throw e; } } return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayPutAtMetaMethod.java0000644001501200150120000000700311627206700032600 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class BooleanArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(boolean[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public BooleanArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final boolean[] objects = (boolean[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); objects[index] = (Boolean) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Boolean)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof boolean[] && args[0] instanceof Integer && args[1] instanceof Boolean) && checkPojoMetaClass()) { final boolean[] objects = (boolean[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Boolean) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final boolean[] objects = (boolean[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Boolean) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof boolean[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/CharacterArrayGetAtMetaMethod.java0000644001501200150120000000477411627206700033100 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class CharacterArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(char[].class); public Class getReturnType() { return Character.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final char[] objects = (char[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof char[] && arg instanceof Integer) && checkPojoMetaClass()) { final char[] objects = (char[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/DoubleArrayPutAtMetaMethod.java0000644001501200150120000001012111627206700032426 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class DoubleArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(double[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public DoubleArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final double[] objects = (double[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Double)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Double) DefaultTypeTransformation.castToType(ch, Double.class); } else { objects[index] = ((Number) newValue).doubleValue(); } } else objects[index] = (Double) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Double)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof double[] && args[0] instanceof Integer && args[1] instanceof Double) && checkPojoMetaClass()) { final double[] objects = (double[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Double) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final double[] objects = (double[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Double) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof double[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayPutAtMetaMethod.java0000644001501200150120000001007511627206700032323 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class ShortArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(short[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public ShortArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final short[] objects = (short[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Short)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Short) DefaultTypeTransformation.castToType(ch, Short.class); } else { objects[index] = ((Number) newValue).shortValue(); } } else objects[index] = (Short) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Short)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof short[] && args[0] instanceof Integer && args[1] instanceof Short) && checkPojoMetaClass()) { final short[] objects = (short[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Short) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final short[] objects = (short[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Short) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof short[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/BooleanArrayGetAtMetaMethod.java0000644001501200150120000000501211627206700032545 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class BooleanArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(boolean[].class); public Class getReturnType() { return Boolean.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final boolean[] objects = (boolean[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof boolean[] && arg instanceof Integer) && checkPojoMetaClass()) { final boolean[] objects = (boolean[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayPutAtMetaMethod.java0000644001501200150120000000155111627206700031302 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; public abstract class ArrayPutAtMetaMethod extends ArrayMetaMethod { public String getName() { return "putAt"; } public Class getReturnType() { return Void.class; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ObjectArrayPutAtMetaMethod.java0000644001501200150120000001034311627206700032430 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class ObjectArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.getCachedClass(Object.class); private static final CachedClass OBJECT_ARR_CLASS = ReflectionCache.OBJECT_ARRAY_CLASS; private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public ObjectArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return OBJECT_ARR_CLASS; } public Object invoke(Object object, Object[] arguments) { final Object[] objects = (Object[]) object; final int index = normaliseIndex((Integer) arguments[0], objects.length); objects[index] = adjustNewValue(objects, arguments[1]); return null; } private static Object adjustNewValue(Object[] objects, Object newValue) { Class arrayComponentClass = objects.getClass().getComponentType(); Object adjustedNewVal = newValue; if (newValue instanceof Number) { if (!arrayComponentClass.equals(newValue.getClass())) { adjustedNewVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass); } } else if (Character.class.isAssignableFrom(arrayComponentClass)) { adjustedNewVal = DefaultTypeTransformation.getCharFromSizeOneString(newValue); } else if (Number.class.isAssignableFrom(arrayComponentClass)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); adjustedNewVal = DefaultTypeTransformation.castToType(ch, arrayComponentClass); } } return adjustedNewVal; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final Object[] objects = (Object[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = adjustNewValue(objects, arg2); return null; } catch (ClassCastException e) { if ((receiver instanceof Object[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ArrayMetaMethod.java0000644001501200150120000000301011627206700030314 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSiteAwareMetaMethod; import java.lang.reflect.Modifier; public abstract class ArrayMetaMethod extends CallSiteAwareMetaMethod { protected static final CachedClass INTEGER_CLASS = ReflectionCache.getCachedClass(Integer.class); protected static final CachedClass[] INTEGER_CLASS_ARR = new CachedClass[]{INTEGER_CLASS}; protected static int normaliseIndex(int i, int size) { int temp = i; if (i < 0) { i += size; } if (i < 0) { throw new ArrayIndexOutOfBoundsException("Negative array index [" + temp + "] too large for array size " + size); } return i; } public int getModifiers() { return Modifier.PUBLIC; } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayGetAtMetaMethod.java0000644001501200150120000000477211627206700032301 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; public class ShortArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(short[].class); public Class getReturnType() { return Short.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final short[] objects = (short[]) object; return objects[normaliseIndex((Integer) args[0], objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object arg) throws Throwable { if ((receiver instanceof short[] && arg instanceof Integer) && checkPojoMetaClass()) { final short[] objects = (short[]) receiver; return objects[normaliseIndex((Integer) arg, objects.length)]; } else return super.call(receiver, arg); } } } groovy-1.8.6/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java0000644001501200150120000000566011627206700030226 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.runtime; /** * Keep this constant in a separate file as it is troublesome for Antlr to parse for doc purposes. */ public class EncodingGroovyMethodsSupport { static final byte[] TRANSLATE_TABLE = ( "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // \t \n \r + "\u0042\u0042\u0041\u0041\u0042\u0042\u0041\u0042" // + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // sp ! " # $ % & ' + "\u0041\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // ( ) * + , - . / + "\u0042\u0042\u0042\u003E\u0042\u0042\u0042\u003F" // 0 1 2 3 4 5 6 7 + "\u0034\u0035\u0036\u0037\u0038\u0039\u003A\u003B" // 8 9 : ; < = > ? + "\u003C\u003D\u0042\u0042\u0042\u0040\u0042\u0042" // @ A B C D E F G + "\u0042\u0000\u0001\u0002\u0003\u0004\u0005\u0006" // H I J K L M N O + "\u0007\u0008\t\n\u000B\u000C\r\u000E" // P Q R S T U V W + "\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016" // X Y Z [ \ ] ^ _ + "\u0017\u0018\u0019\u0042\u0042\u0042\u0042\u0042" // ' a b c d e f g + "\u0042\u001A\u001B\u001C\u001D\u001E\u001F\u0020" // h i j k l m n o p + "\u0021\"\u0023\u0024\u0025\u0026\u0027\u0028" // p q r s t u v w + "\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030" // x y z + "\u0031\u0032\u0033").getBytes(); }groovy-1.8.6/src/main/org/codehaus/groovy/GroovyException.java0000644001501200150120000000247111627206700024027 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy; public class GroovyException extends Exception implements GroovyExceptionInterface { private boolean fatal = true; public GroovyException() { } public GroovyException(String message) { super(message); } public GroovyException(String message, Throwable cause) { super(message, cause); } public GroovyException(boolean fatal) { super(); this.fatal = fatal; } public GroovyException(String message, boolean fatal) { super(message); this.fatal = fatal; } public boolean isFatal() { return fatal; } public void setFatal(boolean fatal) { this.fatal = fatal; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/0000755001501200150120000000000011715031256021613 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/classgen/AsmClassGenerator.java0000644001501200150120000027015011715031256026040 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.classgen.asm.*; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.syntax.RuntimeParserException; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.*; import java.lang.reflect.Modifier; import java.util.*; /** * Generates Java class versions of Groovy classes using ASM. * * @author James Strachan * @author Bing Ran * @author Jochen Theodorou * @author Alex Popescu * @author Alex Tkachman * @version $Revision$ */ public class AsmClassGenerator extends ClassGenerator { private final ClassVisitor cv; private GeneratorContext context; private String sourceFile; // fields and properties static final MethodCallerMultiAdapter setField = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setField", false, false); static final MethodCallerMultiAdapter getField = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getField", false, false); static final MethodCallerMultiAdapter setGroovyObjectField = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setGroovyObjectField", false, false); static final MethodCallerMultiAdapter getGroovyObjectField = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getGroovyObjectField", false, false); static final MethodCallerMultiAdapter setFieldOnSuper = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setFieldOnSuper", false, false); static final MethodCallerMultiAdapter getFieldOnSuper = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getFieldOnSuper", false, false); public static final MethodCallerMultiAdapter setProperty = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setProperty", false, false); static final MethodCallerMultiAdapter getProperty = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getProperty", false, false); static final MethodCallerMultiAdapter setGroovyObjectProperty = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setGroovyObjectProperty", false, false); static final MethodCallerMultiAdapter getGroovyObjectProperty = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getGroovyObjectProperty", false, false); static final MethodCallerMultiAdapter setPropertyOnSuper = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "setPropertyOnSuper", false, false); static final MethodCallerMultiAdapter getPropertyOnSuper = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "getPropertyOnSuper", false, false); // spread expressions static final MethodCaller spreadMap = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "spreadMap"); static final MethodCaller despreadList = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "despreadList"); // Closure static final MethodCaller getMethodPointer = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getMethodPointer"); // unary plus, unary minus, bitwise negation static final MethodCaller unaryPlus = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "unaryPlus"); static final MethodCaller unaryMinus = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "unaryMinus"); static final MethodCaller bitwiseNegate = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "bitwiseNegate"); // type conversions static final MethodCaller createListMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createList"); static final MethodCaller createMapMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createMap"); static final MethodCaller createRangeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createRange"); // wrapper creation methods static final MethodCaller createPojoWrapperMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createPojoWrapper"); static final MethodCaller createGroovyObjectWrapperMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createGroovyObjectWrapper"); // constructor calls with this() and super() static final MethodCaller selectConstructorAndTransformArguments = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "selectConstructorAndTransformArguments"); // exception blocks list private Map referencedClasses = new HashMap(); private boolean passingParams; public static final boolean CREATE_DEBUG_INFO = true; public static final boolean CREATE_LINE_NUMBER_INFO = true; public static final boolean ASM_DEBUG = false; // add marker in the bytecode to show source-bytecode relationship private int lineNumber = -1; private ASTNode currentASTNode = null; private Map genericParameterNames = null; private SourceUnit source; private WriterController controller; public AsmClassGenerator( SourceUnit source, GeneratorContext context, ClassVisitor classVisitor, String sourceFile ) { this.source = source; this.context = context; this.cv = classVisitor; this.sourceFile = sourceFile; genericParameterNames = new HashMap(); } public SourceUnit getSourceUnit() { return source; } // GroovyClassVisitor interface //------------------------------------------------------------------------- public void visitClass(ClassNode classNode) { referencedClasses.clear(); this.controller = new WriterController(); this.controller.init(this, context, cv, classNode); if (controller.shouldOptimizeForInt()) { OptimizingStatementWriter.setNodeMeta(controller.getTypeChooser(),classNode); } try { cv.visit( getBytecodeVersion(), adjustedClassModifiers(classNode.getModifiers()), controller.getInternalClassName(), BytecodeHelper.getGenericsSignature(classNode), controller.getInternalBaseClassName(), BytecodeHelper.getClassInternalNames(classNode.getInterfaces()) ); cv.visitSource(sourceFile, null); if (classNode.getName().endsWith("package-info")) { PackageNode packageNode = classNode.getPackage(); if (packageNode != null) { // pull them out of package node but treat them like they were on class node for (AnnotationNode an : packageNode.getAnnotations()) { // skip built-in properties if (an.isBuiltIn()) continue; if (an.hasSourceRetention()) continue; AnnotationVisitor av = getAnnotationVisitor(classNode, an, cv); visitAnnotationAttributes(an, av); av.visitEnd(); } } cv.visitEnd(); return; } else { visitAnnotations(classNode, cv); } if (classNode.isInterface()) { ClassNode owner = classNode; if (owner instanceof InnerClassNode) { owner = owner.getOuterClass(); } String outerClassName = classNode.getName(); String name = outerClassName + "$" + context.getNextInnerClassIdx(); controller.setInterfaceClassLoadingClass( new InterfaceHelperClassNode ( owner, name, 4128, ClassHelper.OBJECT_TYPE, controller.getCallSiteWriter().getCallSites())); super.visitClass(classNode); createInterfaceSyntheticStaticFields(); } else { super.visitClass(classNode); MopWriter mopWriter = new MopWriter(controller); mopWriter.createMopMethods(); controller.getCallSiteWriter().generateCallSiteArray(); createSyntheticStaticFields(); } for (Iterator iter = classNode.getInnerClasses(); iter.hasNext();) { InnerClassNode innerClass = iter.next(); makeInnerClassEntry(innerClass); } makeInnerClassEntry(classNode); cv.visitEnd(); } catch (GroovyRuntimeException e) { e.setModule(classNode.getModule()); throw e; } catch (NullPointerException npe) { throw new GroovyRuntimeException("NPE while processing "+sourceFile, npe); } } private void makeInnerClassEntry(ClassNode cn) { if (!(cn instanceof InnerClassNode)) return; InnerClassNode innerClass = (InnerClassNode) cn; String innerClassName = innerClass.getName(); String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassName); { int index = innerClassName.lastIndexOf('$'); if (index >= 0) innerClassName = innerClassName.substring(index + 1); } String outerClassName = BytecodeHelper.getClassInternalName(innerClass.getOuterClass().getName()); MethodNode enclosingMethod = innerClass.getEnclosingMethod(); if (enclosingMethod != null) { // local inner classes do not specify the outer class name outerClassName = null; innerClassName = null; } int mods = innerClass.getModifiers(); cv.visitInnerClass( innerClassInternalName, outerClassName, innerClassName, mods); } /* * Classes but not interfaces should have ACC_SUPER set */ private int adjustedClassModifiers(int modifiers) { boolean needsSuper = (modifiers & ACC_INTERFACE) == 0; modifiers = needsSuper ? modifiers | ACC_SUPER : modifiers; // eliminate static modifiers = modifiers & ~ACC_STATIC; return modifiers; } public void visitGenericType(GenericsType genericsType) { ClassNode type = genericsType.getType(); genericParameterNames.put(type.getName(), genericsType); } private String[] buildExceptions(ClassNode[] exceptions) { if (exceptions == null) return null; String[] ret = new String[exceptions.length]; for (int i = 0; i < exceptions.length; i++) { ret[i] = BytecodeHelper.getClassInternalName(exceptions[i]); } return ret; } protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { lineNumber = -1; Parameter[] parameters = node.getParameters(); String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), parameters); String signature = BytecodeHelper.getGenericsMethodSignature(node); int modifiers = node.getModifiers(); if (isVargs(node.getParameters())) modifiers |= Opcodes.ACC_VARARGS; MethodVisitor mv = cv.visitMethod(modifiers, node.getName(), methodType, signature, buildExceptions(node.getExceptions())); controller.setMethodVisitor(mv); visitAnnotations(node, mv); for (int i = 0; i < parameters.length; i++) { visitParameterAnnotations(parameters[i], i, mv); } if (controller.getClassNode().isAnnotationDefinition() && !node.isStaticConstructor()) { visitAnnotationDefault(node, mv); } else if (!node.isAbstract()) { Statement code = node.getCode(); mv.visitCode(); // fast path for getter/setters etc. if (code instanceof BytecodeSequence && ((BytecodeSequence)code).getInstructions().size() == 1 && ((BytecodeSequence)code).getInstructions().get(0) instanceof BytecodeInstruction) { ((BytecodeInstruction)((BytecodeSequence)code).getInstructions().get(0)).visit(mv); } else { visitStdMethod(node, isConstructor, parameters, code); } // we use this NOP to have a valid jump target for the various labels //mv.visitInsn(NOP); mv.visitMaxs(0, 0); } mv.visitEnd(); } private void visitStdMethod(MethodNode node, boolean isConstructor, Parameter[] parameters, Statement code) { MethodVisitor mv = controller.getMethodVisitor(); final ClassNode superClass = controller.getClassNode().getSuperClass(); if (isConstructor && (code == null || !((ConstructorNode) node).firstStatementIsSpecialConstructorCall())) { boolean hasCallToSuper = false; if (code!=null && controller.getClassNode() instanceof InnerClassNode) { // if the class not is an inner class node, there are chances that the call to super is already added // so we must ensure not to add it twice (see GROOVY-4471) if (code instanceof BlockStatement) { for (Statement statement : ((BlockStatement) code).getStatements()) { if (statement instanceof ExpressionStatement) { final Expression expression = ((ExpressionStatement) statement).getExpression(); if (expression instanceof ConstructorCallExpression) { ConstructorCallExpression call = (ConstructorCallExpression) expression; if (call.isSuperCall()) { hasCallToSuper = true; break; } } } } } } if (!hasCallToSuper) { // invokes the super class constructor mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(superClass), "", "()V"); } } controller.getCompileStack().init(node.getVariableScope(), parameters); controller.getCallSiteWriter().makeSiteEntry(); // handle body super.visitConstructorOrMethod(node, isConstructor); controller.getCompileStack().clear(); if (node.isVoidMethod()) { mv.visitInsn(RETURN); } else { // we make a dummy return for label ranges that reach here ClassNode type = node.getReturnType().redirect(); if (ClassHelper.isPrimitiveType(type)) { mv.visitLdcInsn(0); controller.getOperandStack().push(ClassHelper.int_TYPE); controller.getOperandStack().doGroovyCast(type); BytecodeHelper.doReturn(mv, type); controller.getOperandStack().remove(1); } else { mv.visitInsn(ACONST_NULL); BytecodeHelper.doReturn(mv, type); } } } void visitAnnotationDefaultExpression(AnnotationVisitor av, ClassNode type, Expression exp) { if (exp instanceof ClosureExpression) { ClassNode closureClass = controller.getClosureWriter().getOrAddClosureClass((ClosureExpression) exp, ACC_PUBLIC); Type t = Type.getType(BytecodeHelper.getTypeDescription(closureClass)); av.visit(null, t); } else if (type.isArray()) { ListExpression list = (ListExpression) exp; AnnotationVisitor avl = av.visitArray(null); ClassNode componentType = type.getComponentType(); for (Expression lExp : list.getExpressions()) { visitAnnotationDefaultExpression(avl, componentType, lExp); } } else if (ClassHelper.isPrimitiveType(type) || type.equals(ClassHelper.STRING_TYPE)) { ConstantExpression constExp = (ConstantExpression) exp; av.visit(null, constExp.getValue()); } else if (ClassHelper.CLASS_Type.equals(type)) { ClassNode clazz = exp.getType(); Type t = Type.getType(BytecodeHelper.getTypeDescription(clazz)); av.visit(null, t); } else if (type.isDerivedFrom(ClassHelper.Enum_Type)) { PropertyExpression pExp = (PropertyExpression) exp; ClassExpression cExp = (ClassExpression) pExp.getObjectExpression(); String desc = BytecodeHelper.getTypeDescription(cExp.getType()); String name = pExp.getPropertyAsString(); av.visitEnum(null, desc, name); } else if (type.implementsInterface(ClassHelper.Annotation_TYPE)) { AnnotationConstantExpression avExp = (AnnotationConstantExpression) exp; AnnotationNode value = (AnnotationNode) avExp.getValue(); AnnotationVisitor avc = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(avExp.getType())); visitAnnotationAttributes(value,avc); } else { throw new GroovyBugError("unexpected annotation type " + type.getName()); } av.visitEnd(); } private void visitAnnotationDefault(MethodNode node, MethodVisitor mv) { if (!node.hasAnnotationDefault()) return; Expression exp = ((ReturnStatement) node.getCode()).getExpression(); AnnotationVisitor av = mv.visitAnnotationDefault(); visitAnnotationDefaultExpression(av,node.getReturnType(),exp); } private static boolean isVargs(Parameter[] p) { if (p.length==0) return false; ClassNode clazz = p[p.length-1].getType(); return (clazz.isArray()); } public void visitConstructor(ConstructorNode node) { controller.setConstructorNode(node); super.visitConstructor(node); } public void visitMethod(MethodNode node) { controller.setMethodNode(node); super.visitMethod(node); } public void visitField(FieldNode fieldNode) { onLineNumber(fieldNode, "visitField: " + fieldNode.getName()); ClassNode t = fieldNode.getType(); String signature = BytecodeHelper.getGenericsBounds(t); Expression initialValueExpression = fieldNode.getInitialValueExpression(); ConstantExpression cexp = initialValueExpression instanceof ConstantExpression? (ConstantExpression) initialValueExpression :null; if (cexp!=null) { cexp = Verifier.transformToPrimitiveConstantIfPossible(cexp); } Object value = cexp!=null && ClassHelper.isStaticConstantInitializerType(cexp.getType()) && cexp.getType().equals(t) && fieldNode.isStatic() && fieldNode.isFinal() ?cexp.getValue() // GROOVY-5150 :null; if (value!=null) { // byte, char and short require an extra cast if (ClassHelper.byte_TYPE.equals(t) || ClassHelper.short_TYPE.equals(t)) { value = ((Number) value).intValue(); } else if (ClassHelper.char_TYPE.equals(t)) { value = Integer.valueOf((Character)value); } } FieldVisitor fv = cv.visitField( fieldNode.getModifiers(), fieldNode.getName(), BytecodeHelper.getTypeDescription(t), signature, value); visitAnnotations(fieldNode, fv); fv.visitEnd(); } public void visitProperty(PropertyNode statement) { // the verifier created the field and the setter/getter methods, so here is // not really something to do onLineNumber(statement, "visitProperty:" + statement.getField().getName()); controller.setMethodNode(null); } // GroovyCodeVisitor interface //------------------------------------------------------------------------- // Statements //------------------------------------------------------------------------- protected void visitStatement(Statement statement) { throw new GroovyBugError("visitStatement should not be visited here."); } @Override public void visitCatchStatement(CatchStatement statement) { statement.getCode().visit(this); } public void visitBlockStatement(BlockStatement block) { controller.getStatementWriter().writeBlockStatement(block); } public void visitForLoop(ForStatement loop) { controller.getStatementWriter().writeForStatement(loop); } public void visitWhileLoop( WhileStatement loop) { controller.getStatementWriter().writeWhileLoop(loop); } public void visitDoWhileLoop(DoWhileStatement loop) { controller.getStatementWriter().writeDoWhileLoop(loop); } public void visitIfElse(IfStatement ifElse) { controller.getStatementWriter().writeIfElse(ifElse); } public void visitAssertStatement(AssertStatement statement) { controller.getStatementWriter().writeAssert(statement); } public void visitTryCatchFinally(TryCatchStatement statement) { controller.getStatementWriter().writeTryCatchFinally(statement); } public void visitSwitch(SwitchStatement statement) { controller.getStatementWriter().writeSwitch(statement); } public void visitCaseStatement(CaseStatement statement) {} public void visitBreakStatement(BreakStatement statement) { controller.getStatementWriter().writeBreak(statement); } public void visitContinueStatement(ContinueStatement statement) { controller.getStatementWriter().writeContinue(statement); } public void visitSynchronizedStatement(SynchronizedStatement statement) { controller.getStatementWriter().writeSynchronized(statement); } public void visitThrowStatement(ThrowStatement statement) { controller.getStatementWriter().writeThrow(statement); } public void visitReturnStatement(ReturnStatement statement) { controller.getStatementWriter().writeReturn(statement); } public void visitExpressionStatement(ExpressionStatement statement) { controller.getStatementWriter().writeExpressionStatement(statement); } // Expressions //------------------------------------------------------------------------- public void visitTernaryExpression(TernaryExpression expression) { onLineNumber(expression, "visitTernaryExpression"); controller.getBinaryExpHelper().evaluateTernary(expression); } public void visitDeclarationExpression(DeclarationExpression expression) { onLineNumber(expression, "visitDeclarationExpression: \"" + expression.getText() + "\""); controller.getBinaryExpHelper().evaluateEqual(expression,true); } public void visitBinaryExpression(BinaryExpression expression) { onLineNumber(expression, "visitBinaryExpression: \"" + expression.getOperation().getText() + "\" "); controller.getBinaryExpHelper().eval(expression); controller.getAssertionWriter().record(expression.getOperation()); } public void visitPostfixExpression(PostfixExpression expression) { controller.getBinaryExpHelper().evaluatePostfixMethod(expression); controller.getAssertionWriter().record(expression); } public void throwException(String s) { throw new RuntimeParserException(s, currentASTNode); } public void visitPrefixExpression(PrefixExpression expression) { controller.getBinaryExpHelper().evaluatePrefixMethod(expression); controller.getAssertionWriter().record(expression); } public void visitClosureExpression(ClosureExpression expression) { controller.getClosureWriter().writeClosure(expression); } /** * Loads either this object or if we're inside a closure then load the top level owner */ protected void loadThisOrOwner() { if (isInnerClass()) { visitFieldExpression(new FieldExpression(controller.getClassNode().getDeclaredField("owner"))); } else { loadThis(); } } /** * Generate byte code for constants * * @see Class field types */ public void visitConstantExpression(ConstantExpression expression) { final String constantName = expression.getConstantName(); if (controller.isStaticConstructor() || constantName == null) { controller.getOperandStack().pushConstant(expression); } else { controller.getMethodVisitor().visitFieldInsn(GETSTATIC, controller.getInternalClassName(),constantName, BytecodeHelper.getTypeDescription(expression.getType())); controller.getOperandStack().push(expression.getType()); } } public void visitSpreadExpression(SpreadExpression expression) { throw new GroovyBugError("SpreadExpression should not be visited here"); } public void visitSpreadMapExpression(SpreadMapExpression expression) { Expression subExpression = expression.getExpression(); // to not record the underlying MapExpression twice, // we disable the assertion tracker // see http://jira.codehaus.org/browse/GROOVY-3421 controller.getAssertionWriter().disableTracker(); subExpression.visit(this); controller.getOperandStack().box(); spreadMap.call(controller.getMethodVisitor()); controller.getAssertionWriter().reenableTracker(); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); } public void visitMethodPointerExpression(MethodPointerExpression expression) { Expression subExpression = expression.getExpression(); subExpression.visit(this); controller.getOperandStack().box(); controller.getOperandStack().pushDynamicName(expression.getMethodName()); getMethodPointer.call(controller.getMethodVisitor()); controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE,2); } public void visitUnaryMinusExpression(UnaryMinusExpression expression) { Expression subExpression = expression.getExpression(); subExpression.visit(this); controller.getOperandStack().box(); unaryMinus.call(controller.getMethodVisitor()); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); controller.getAssertionWriter().record(expression); } public void visitUnaryPlusExpression(UnaryPlusExpression expression) { Expression subExpression = expression.getExpression(); subExpression.visit(this); controller.getOperandStack().box(); unaryPlus.call(controller.getMethodVisitor()); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); controller.getAssertionWriter().record(expression); } public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) { Expression subExpression = expression.getExpression(); subExpression.visit(this); controller.getOperandStack().box(); bitwiseNegate.call(controller.getMethodVisitor()); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); controller.getAssertionWriter().record(expression); } public void visitCastExpression(CastExpression castExpression) { ClassNode type = castExpression.getType(); castExpression.getExpression().visit(this); if (castExpression.isCoerce()) { controller.getOperandStack().doAsType(type); } else { controller.getOperandStack().doGroovyCast(type); } } public void visitNotExpression(NotExpression expression) { Expression subExpression = expression.getExpression(); int mark = controller.getOperandStack().getStackLength(); subExpression.visit(this); controller.getOperandStack().castToBool(mark, true); BytecodeHelper.negateBoolean(controller.getMethodVisitor()); controller.getAssertionWriter().record(expression); } /** * return a primitive boolean value of the BooleanExpression. * * @param expression */ public void visitBooleanExpression(BooleanExpression expression) { controller.getCompileStack().pushBooleanExpression(); int mark = controller.getOperandStack().getStackLength(); Expression inner = expression.getExpression(); inner.visit(this); controller.getOperandStack().castToBool(mark, true); controller.getCompileStack().pop(); } public void visitMethodCallExpression(MethodCallExpression call) { onLineNumber(call, "visitMethodCallExpression: \"" + call.getMethod() + "\":"); controller.getInvocationWriter().writeInvokeMethod(call); controller.getAssertionWriter().record(call.getMethod()); } protected boolean emptyArguments(Expression arguments) { return argumentSize(arguments) == 0; } public static boolean containsSpreadExpression(Expression arguments) { List args = null; if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; args = tupleExpression.getExpressions(); } else if (arguments instanceof ListExpression) { ListExpression le = (ListExpression) arguments; args = le.getExpressions(); } else { return arguments instanceof SpreadExpression; } for (Iterator iter = args.iterator(); iter.hasNext();) { if (iter.next() instanceof SpreadExpression) return true; } return false; } public static int argumentSize(Expression arguments) { if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; int size = tupleExpression.getExpressions().size(); return size; } return 1; } public void visitStaticMethodCallExpression(StaticMethodCallExpression call) { onLineNumber(call, "visitStaticMethodCallExpression: \"" + call.getMethod() + "\":"); controller.getInvocationWriter().writeInvokeStaticMethod(call); controller.getAssertionWriter().record(call); } private void visitSpecialConstructorCall(ConstructorCallExpression call) { if (controller.getClosureWriter().addGeneratedClosureConstructorCall(call)) return; ClassNode callNode = controller.getClassNode(); if (call.isSuperCall()) callNode = callNode.getSuperClass(); List constructors = sortConstructors(call, callNode); if (!makeDirectConstructorCall(constructors, call, callNode)) { makeMOPBasedConstructorCall(constructors, call, callNode); } } // we match only on the number of arguments, not anything else private static ConstructorNode getMatchingConstructor(List constructors, List argumentList) { ConstructorNode lastMatch = null; for (int i=0; i constructors, ConstructorCallExpression call, ClassNode callNode) { if (!controller.isConstructor()) return false; Expression arguments = call.getArguments(); List argumentList; if (arguments instanceof TupleExpression) { argumentList = ((TupleExpression) arguments).getExpressions(); } else { argumentList = new ArrayList(); argumentList.add(arguments); } for (Expression expression : argumentList) { if (expression instanceof SpreadExpression) return false; } ConstructorNode cn = getMatchingConstructor(constructors, argumentList); if (cn==null) return false; MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); Parameter[] params = cn.getParameters(); mv.visitVarInsn(ALOAD, 0); for (int i=0; i", descriptor); return true; } private void makeMOPBasedConstructorCall(List constructors, ConstructorCallExpression call, ClassNode callNode) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); call.getArguments().visit(this); // keep Object[] on stack mv.visitInsn(DUP); // to select the constructor we need also the number of // available constructors and the class we want to make // the call on BytecodeHelper.pushConstant(mv, constructors.size()); visitClassExpression(new ClassExpression(callNode)); operandStack.remove(1); // removes one Object[] leaves the int containing the // call flags and the constructor number selectConstructorAndTransformArguments.call(mv); // Object[],int -> int,Object[],int // we need to examine the flags and maybe change the // Object[] later, so this reordering will do the job mv.visitInsn(DUP_X1); // test if rewrap flag is set mv.visitInsn(ICONST_1); mv.visitInsn(IAND); Label afterIf = new Label(); mv.visitJumpInsn(IFEQ, afterIf); // true part, so rewrap using the first argument mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitTypeInsn(CHECKCAST, "[Ljava/lang/Object;"); mv.visitLabel(afterIf); // here the stack is int,Object[], but we need the // the int for our table, so swap it mv.visitInsn(SWAP); //load "this" if (controller.isConstructor()) { mv.visitVarInsn(ALOAD, 0); } else { mv.visitTypeInsn(NEW, BytecodeHelper.getClassInternalName(callNode)); } mv.visitInsn(SWAP); //prepare switch with >>8 mv.visitIntInsn(BIPUSH, 8); mv.visitInsn(ISHR); Label[] targets = new Label[constructors.size()]; int[] indices = new int[constructors.size()]; for (int i = 0; i < targets.length; i++) { targets[i] = new Label(); indices[i] = i; } // create switch targets Label defaultLabel = new Label(); Label afterSwitch = new Label(); mv.visitLookupSwitchInsn(defaultLabel, indices, targets); for (int i = 0; i < targets.length; i++) { mv.visitLabel(targets[i]); // to keep the stack height, we need to leave // one Object[] on the stack as last element. At the // same time, we need the Object[] on top of the stack // to extract the parameters. if (controller.isConstructor()) { // in this case we need one "this", so a SWAP will exchange // "this" and Object[], a DUP_X1 will then copy the Object[] /// to the last place in the stack: // Object[],this -SWAP-> this,Object[] // this,Object[] -DUP_X1-> Object[],this,Object[] mv.visitInsn(SWAP); mv.visitInsn(DUP_X1); } else { // in this case we need two "this" in between and the Object[] // at the bottom of the stack as well as on top for our invokeSpecial // So we do DUP_X1, DUP2_X1, POP // Object[],this -DUP_X1-> this,Object[],this // this,Object[],this -DUP2_X1-> Object[],this,this,Object[],this // Object[],this,this,Object[],this -POP-> Object[],this,this,Object[] mv.visitInsn(DUP_X1); mv.visitInsn(DUP2_X1); mv.visitInsn(POP); } ConstructorNode cn = constructors.get(i); String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, cn.getParameters()); // unwrap the Object[] and make transformations if needed // that means, to duplicate the Object[], make a cast with possible // unboxing and then swap it with the Object[] for each parameter Parameter[] parameters = cn.getParameters(); for (int p = 0; p < parameters.length; p++) { operandStack.push(ClassHelper.OBJECT_TYPE); mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, p); mv.visitInsn(AALOAD); operandStack.push(ClassHelper.OBJECT_TYPE); ClassNode type = parameters[p].getType(); operandStack.doGroovyCast(type); operandStack.swap(); operandStack.remove(2); } // at the end we remove the Object[] mv.visitInsn(POP); // make the constructor call mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "", descriptor); mv.visitJumpInsn(GOTO, afterSwitch); } mv.visitLabel(defaultLabel); // this part should never be reached! mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException"); mv.visitInsn(DUP); mv.visitLdcInsn("illegal constructor number"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); mv.visitLabel(afterSwitch); // For a special constructor call inside a constructor we don't need // any result object on the stack, for outside the constructor we do. // to keep the stack height for the able we kept one object as dummy // result on the stack, which we can remove now if inside a constructor. if (!controller.isConstructor()) { // in case we are not in a constructor we have an additional // object on the stack, the result of our constructor call // which we want to keep, so we swap with the dummy object and // do normal removal of it. In the end, the call result will be // on the stack then mv.visitInsn(SWAP); operandStack.push(callNode); // for call result } mv.visitInsn(POP); } private List sortConstructors(ConstructorCallExpression call, ClassNode callNode) { // sort in a new list to prevent side effects List constructors = new ArrayList(callNode.getDeclaredConstructors()); Comparator comp = new Comparator() { public int compare(Object arg0, Object arg1) { ConstructorNode c0 = (ConstructorNode) arg0; ConstructorNode c1 = (ConstructorNode) arg1; String descriptor0 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c0.getParameters()); String descriptor1 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c1.getParameters()); return descriptor0.compareTo(descriptor1); } }; Collections.sort(constructors, comp); return constructors; } public void visitConstructorCallExpression(ConstructorCallExpression call) { onLineNumber(call, "visitConstructorCallExpression: \"" + call.getType().getName() + "\":"); if (call.isSpecialCall()) { controller.getCompileStack().pushInSpecialConstructorCall(); visitSpecialConstructorCall(call); controller.getCompileStack().pop(); return; } controller.getInvocationWriter().writeInvokeConstructor(call); controller.getAssertionWriter().record(call); } private static String makeFieldClassName(ClassNode type) { String internalName = BytecodeHelper.getClassInternalName(type); StringBuffer ret = new StringBuffer(internalName.length()); for (int i = 0; i < internalName.length(); i++) { char c = internalName.charAt(i); if (c == '/') { ret.append('$'); } else if (c == ';') { //append nothing -> delete ';' } else { ret.append(c); } } return ret.toString(); } private static String getStaticFieldName(ClassNode type) { ClassNode componentType = type; String prefix = ""; for (; componentType.isArray(); componentType = componentType.getComponentType()) { prefix += "$"; } if (prefix.length() != 0) prefix = "array" + prefix; String name = prefix + "$class$" + makeFieldClassName(componentType); return name; } private void visitAttributeOrProperty(PropertyExpression expression, MethodCallerMultiAdapter adapter) { MethodVisitor mv = controller.getMethodVisitor(); Expression objectExpression = expression.getObjectExpression(); ClassNode classNode = controller.getClassNode(); if (isThisOrSuper(objectExpression)) { // let's use the field expression if it's available String name = expression.getPropertyAsString(); if (name != null) { FieldNode field = null; boolean privateSuperField = false; if (isSuperExpression(objectExpression)) { field = classNode.getSuperClass().getDeclaredField(name); if (field != null && ((field.getModifiers() & ACC_PRIVATE) != 0)) { privateSuperField = true; } } else { if (controller.isNotExplicitThisInClosure(expression.isImplicitThis())) { field = classNode.getDeclaredField(name); if (field==null && classNode instanceof InnerClassNode) { ClassNode outer = classNode.getOuterClass(); FieldNode outerClassField; while (outer!=null) { outerClassField = outer.getDeclaredField(name); if (outerClassField!=null && outerClassField.isStatic() && outerClassField.isFinal()) { if (outer!=classNode.getOuterClass() && Modifier.isPrivate(outerClassField.getModifiers())) { throw new GroovyBugError("Trying to access private constant field ["+outerClassField.getDeclaringClass()+"#"+outerClassField.getName()+"] from inner class"); } PropertyExpression pexp = new PropertyExpression( new ClassExpression(outer), expression.getProperty() ); pexp.visit(controller.getAcg()); return; } outer = outer.getSuperClass(); } } } } if (field != null && !privateSuperField) {//GROOVY-4497: don't visit super field if it is private visitFieldExpression(new FieldExpression(field)); return; } } if (isSuperExpression(objectExpression)) { String prefix; if (controller.getCompileStack().isLHS()) { prefix = "set"; } else { prefix = "get"; } String propName = prefix + MetaClassHelper.capitalize(name); visitMethodCallExpression(new MethodCallExpression(objectExpression, propName, MethodCallExpression.NO_ARGUMENTS)); return; } } final String propName = expression.getPropertyAsString(); //TODO: add support for super here too if (expression.getObjectExpression() instanceof ClassExpression && propName!=null && propName.equals("this")) { // we have something like A.B.this, and need to make it // into this.this$0.this$0, where this.this$0 returns // A.B and this.this$0.this$0 return A. ClassNode type = objectExpression.getType(); ClassNode iterType = classNode; mv.visitVarInsn(ALOAD, 0); while (!iterType.equals(type)) { String ownerName = BytecodeHelper.getClassInternalName(iterType); iterType = iterType.getOuterClass(); String typeName = BytecodeHelper.getTypeDescription(iterType); mv.visitFieldInsn(GETFIELD, ownerName, "this$0", typeName); } controller.getOperandStack().push(type); return; } if (adapter == getProperty && !expression.isSpreadSafe() && propName != null) { controller.getCallSiteWriter().makeGetPropertySite(objectExpression, propName, expression.isSafe(), expression.isImplicitThis()); } else if (adapter == getGroovyObjectProperty && !expression.isSpreadSafe() && propName != null) { controller.getCallSiteWriter().makeGroovyObjectGetPropertySite(objectExpression, propName, expression.isSafe(), expression.isImplicitThis()); } else { if (controller.getCompileStack().isLHS()) controller.getOperandStack().box(); controller.getInvocationWriter().makeCall( expression, objectExpression, // receiver new CastExpression(ClassHelper.STRING_TYPE, expression.getProperty()), // messageName MethodCallExpression.NO_ARGUMENTS, adapter, expression.isSafe(), expression.isSpreadSafe(), expression.isImplicitThis() ); } } public void visitPropertyExpression(PropertyExpression expression) { Expression objectExpression = expression.getObjectExpression(); OperandStack operandStack = controller.getOperandStack(); int mark = operandStack.getStackLength()-1; MethodCallerMultiAdapter adapter; if (controller.getCompileStack().isLHS()) { //operandStack.box(); adapter = setProperty; if (isGroovyObject(objectExpression)) adapter = setGroovyObjectProperty; if (controller.isStaticContext() && isThisOrSuper(objectExpression)) adapter = setProperty; } else { adapter = getProperty; if (isGroovyObject(objectExpression)) adapter = getGroovyObjectProperty; if (controller.isStaticContext() && isThisOrSuper(objectExpression)) adapter = getProperty; } visitAttributeOrProperty(expression, adapter); if (controller.getCompileStack().isLHS()) { // remove surplus values operandStack.remove(operandStack.getStackLength()-mark); } else { controller.getAssertionWriter().record(expression.getProperty()); } } public void visitAttributeExpression(AttributeExpression expression) { Expression objectExpression = expression.getObjectExpression(); MethodCallerMultiAdapter adapter; if (controller.getCompileStack().isLHS()) { adapter = setField; if (isGroovyObject(objectExpression)) adapter = setGroovyObjectField; if (usesSuper(expression)) adapter = setFieldOnSuper; } else { adapter = getField; if (isGroovyObject(objectExpression)) adapter = getGroovyObjectField; if (usesSuper(expression)) adapter = getFieldOnSuper; } visitAttributeOrProperty(expression, adapter); if (!controller.getCompileStack().isLHS()) { controller.getAssertionWriter().record(expression.getProperty()); } else { controller.getOperandStack().remove(2); } } private static boolean usesSuper(PropertyExpression pe) { Expression expression = pe.getObjectExpression(); if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; String variable = varExp.getName(); return variable.equals("super"); } return false; } private static boolean isGroovyObject(Expression objectExpression) { return isThisExpression(objectExpression) || objectExpression.getType().isDerivedFromGroovyObject() && !(objectExpression instanceof ClassExpression); } public void visitFieldExpression(FieldExpression expression) { FieldNode field = expression.getField(); if (field.isStatic()) { if (controller.getCompileStack().isLHS()) { storeStaticField(expression); } else { loadStaticField(expression); } } else { if (controller.getCompileStack().isLHS()) { storeThisInstanceField(expression); } else { loadInstanceField(expression); } } if (controller.getCompileStack().isLHS()) controller.getAssertionWriter().record(expression); } /** * @param fldExp */ public void loadStaticField(FieldExpression fldExp) { MethodVisitor mv = controller.getMethodVisitor(); FieldNode field = fldExp.getField(); boolean holder = field.isHolder() && !controller.isInClosureConstructor(); ClassNode type = field.getType(); String ownerName = (field.getOwner().equals(controller.getClassNode())) ? controller.getInternalClassName() : BytecodeHelper.getClassInternalName(field.getOwner()); if (holder) { mv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type)); mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;"); controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); } else { mv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type)); controller.getOperandStack().push(field.getType()); } } /** * RHS instance field. should move most of the code in the BytecodeHelper * * @param fldExp */ public void loadInstanceField(FieldExpression fldExp) { MethodVisitor mv = controller.getMethodVisitor(); FieldNode field = fldExp.getField(); boolean holder = field.isHolder() && !controller.isInClosureConstructor(); ClassNode type = field.getType(); String ownerName = (field.getOwner().equals(controller.getClassNode())) ? controller.getInternalClassName() : BytecodeHelper.getClassInternalName(field.getOwner()); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type)); if (holder) { mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;"); controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); } else { controller.getOperandStack().push(field.getType()); } } private void storeThisInstanceField(FieldExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); FieldNode field = expression.getField(); boolean setReferenceFromReference = field.isHolder() && expression.isUseReferenceDirectly(); String ownerName = (field.getOwner().equals(controller.getClassNode())) ? controller.getInternalClassName() : BytecodeHelper.getClassInternalName(field.getOwner()); OperandStack operandStack = controller.getOperandStack(); if (setReferenceFromReference) { // rhs is ready to use reference, just put it in the field mv.visitVarInsn(ALOAD, 0); operandStack.push(controller.getClassNode()); operandStack.swap(); mv.visitFieldInsn(PUTFIELD, ownerName, field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } else if (field.isHolder()){ // rhs is normal value, set the value in the Reference operandStack.doGroovyCast(field.getOriginType()); operandStack.box(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType())); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V"); } else { // rhs is normal value, set normal value operandStack.doGroovyCast(field.getOriginType()); mv.visitVarInsn(ALOAD, 0); operandStack.push(controller.getClassNode()); operandStack.swap(); mv.visitFieldInsn(PUTFIELD, ownerName, field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } } private void storeStaticField(FieldExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); FieldNode field = expression.getField(); boolean holder = field.isHolder() && !controller.isInClosureConstructor(); controller.getOperandStack().doGroovyCast(field); String ownerName = (field.getOwner().equals(controller.getClassNode())) ? controller.getInternalClassName() : BytecodeHelper.getClassInternalName(field.getOwner()); if (holder) { controller.getOperandStack().box(); mv.visitFieldInsn(GETSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType())); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V"); } else { mv.visitFieldInsn(PUTSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType())); } controller.getOperandStack().remove(1); } /** * Visits a bare (unqualified) variable expression. */ public void visitVariableExpression(VariableExpression expression) { String variableName = expression.getName(); //----------------------------------------------------------------------- // SPECIAL CASES // "this" for static methods is the Class instance ClassNode classNode = controller.getClassNode(); //if (controller.isInClosure()) classNode = controller.getOutermostClass(); if (variableName.equals("this")) { if (controller.isStaticMethod() || (!controller.getCompileStack().isImplicitThis() && controller.isStaticContext())) { if (controller.isInClosure()) classNode = controller.getOutermostClass(); visitClassExpression(new ClassExpression(classNode)); } else { loadThis(); } return; } // "super" also requires special handling if (variableName.equals("super")) { if (controller.isStaticMethod()) { visitClassExpression(new ClassExpression(classNode.getSuperClass())); } else { loadThis(); } return; } BytecodeVariable variable = controller.getCompileStack().getVariable(variableName, false); if (variable == null) { processClassVariable(variableName); } else { controller.getOperandStack().loadOrStoreVariable(variable, expression.isUseReferenceDirectly()); } if (!controller.getCompileStack().isLHS()) controller.getAssertionWriter().record(expression); } private void loadThis() { MethodVisitor mv = controller.getMethodVisitor(); mv.visitVarInsn(ALOAD, 0); if (controller.isInClosure() && !controller.getCompileStack().isImplicitThis()) { mv.visitMethodInsn( INVOKEVIRTUAL, "groovy/lang/Closure", "getThisObject", "()Ljava/lang/Object;" ); controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); // controller.getOperandStack().push(controller.getClassNode().getOuterClass()); } else { controller.getOperandStack().push(controller.getClassNode()); } } private void processClassVariable(String name) { if (passingParams && controller.isInScriptBody()) { //TODO: check if this part is actually used MethodVisitor mv = controller.getMethodVisitor(); // let's create a ScriptReference to pass into the closure mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference"); mv.visitInsn(DUP); loadThisOrOwner(); mv.visitLdcInsn(name); mv.visitMethodInsn( INVOKESPECIAL, "org/codehaus/groovy/runtime/ScriptReference", "", "(Lgroovy/lang/Script;Ljava/lang/String;)V"); } else { PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, name); pexp.setImplicitThis(true); visitPropertyExpression(pexp); } } protected void createInterfaceSyntheticStaticFields() { ClassNode icl = controller.getInterfaceClassLoadingClass(); if (referencedClasses.isEmpty()) { Iterator it = controller.getClassNode().getInnerClasses(); while(it.hasNext()) { InnerClassNode inner = it.next(); if (inner==icl) { it.remove(); return; } } return; } addInnerClass(icl); for (String staticFieldName : referencedClasses.keySet()) { // generate a field node icl.addField(staticFieldName, ACC_STATIC + ACC_SYNTHETIC, ClassHelper.CLASS_Type.getPlainNodeReference(), new ClassExpression(referencedClasses.get(staticFieldName))); } } protected void createSyntheticStaticFields() { MethodVisitor mv = controller.getMethodVisitor(); for (String staticFieldName : referencedClasses.keySet()) { // generate a field node FieldNode fn = controller.getClassNode().getDeclaredField(staticFieldName); if (fn != null) { boolean type = fn.getType().redirect() == ClassHelper.CLASS_Type; boolean modifiers = fn.getModifiers() == ACC_STATIC + ACC_SYNTHETIC; if (!type || !modifiers) { String text = ""; if (!type) text = " with wrong type: " + fn.getType() + " (java.lang.Class needed)"; if (!modifiers) text = " with wrong modifiers: " + fn.getModifiers() + " (" + (ACC_STATIC + ACC_SYNTHETIC) + " needed)"; throwException( "tried to set a static synthetic field " + staticFieldName + " in " + controller.getClassNode().getName() + " for class resolving, but found already a node of that" + " name " + text); } } else { cv.visitField(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, staticFieldName, "Ljava/lang/Class;", null, null); } mv = cv.visitMethod(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, "$get$" + staticFieldName,"()Ljava/lang/Class;",null, null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC,controller.getInternalClassName(),staticFieldName,"Ljava/lang/Class;"); mv.visitInsn(DUP); Label l0 = new Label(); mv.visitJumpInsn(IFNONNULL,l0); mv.visitInsn(POP); mv.visitLdcInsn(BytecodeHelper.getClassLoadingTypeDescription(referencedClasses.get(staticFieldName))); mv.visitMethodInsn(INVOKESTATIC,controller.getInternalClassName(),"class$","(Ljava/lang/String;)Ljava/lang/Class;"); mv.visitInsn(DUP); mv.visitFieldInsn(PUTSTATIC,controller.getInternalClassName(),staticFieldName,"Ljava/lang/Class;"); mv.visitLabel(l0); mv.visitInsn(ARETURN); mv.visitMaxs(0,0); mv.visitEnd(); } mv = cv.visitMethod( ACC_STATIC + ACC_SYNTHETIC, "class$", "(Ljava/lang/String;)Ljava/lang/Class;", null, null); Label l0 = new Label(); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); Label l1 = new Label(); mv.visitLabel(l1); mv.visitInsn(ARETURN); Label l2 = new Label(); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 1); mv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError"); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ClassNotFoundException", "getMessage", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); mv.visitTryCatchBlock(l0, l2, l2, "java/lang/ClassNotFoundException"); // br using l2 as the 2nd param seems create the right table entry mv.visitMaxs(3, 2); } /** * load class object on stack */ public void visitClassExpression(ClassExpression expression) { ClassNode type = expression.getType(); MethodVisitor mv = controller.getMethodVisitor(); if (ClassHelper.isPrimitiveType(type)) { ClassNode objectType = ClassHelper.getWrapper(type); mv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(objectType), "TYPE", "Ljava/lang/Class;"); } else { String staticFieldName = getStaticFieldName(type); referencedClasses.put(staticFieldName,type); String internalClassName = controller.getInternalClassName(); if (controller.getClassNode().isInterface()) { internalClassName = BytecodeHelper.getClassInternalName(controller.getInterfaceClassLoadingClass()); mv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;"); } else { mv.visitMethodInsn(INVOKESTATIC, internalClassName, "$get$" + staticFieldName, "()Ljava/lang/Class;"); } } controller.getOperandStack().push(ClassHelper.CLASS_Type); } public void visitRangeExpression(RangeExpression expression) { OperandStack operandStack = controller.getOperandStack(); expression.getFrom().visit(this); operandStack.box(); expression.getTo().visit(this); operandStack.box(); operandStack.pushBool(expression.isInclusive()); createRangeMethod.call(controller.getMethodVisitor()); operandStack.replace(ClassHelper.RANGE_TYPE, 3); } public void visitMapEntryExpression(MapEntryExpression expression) { throw new GroovyBugError("MapEntryExpression should not be visited here"); } public void visitMapExpression(MapExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); List entries = expression.getMapEntryExpressions(); int size = entries.size(); BytecodeHelper.pushConstant(mv, size * 2); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int i = 0; for (Iterator iter = entries.iterator(); iter.hasNext();) { Object object = iter.next(); MapEntryExpression entry = (MapEntryExpression) object; mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i++); entry.getKeyExpression().visit(this); controller.getOperandStack().box(); mv.visitInsn(AASTORE); mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i++); entry.getValueExpression().visit(this); controller.getOperandStack().box(); mv.visitInsn(AASTORE); controller.getOperandStack().remove(2); } createMapMethod.call(mv); controller.getOperandStack().push(ClassHelper.MAP_TYPE); } public void visitArgumentlistExpression(ArgumentListExpression ale) { if (containsSpreadExpression(ale)) { despreadList(ale.getExpressions(), true); } else { visitTupleExpression(ale, true); } } public void despreadList(List expressions, boolean wrap) { ArrayList spreadIndexes = new ArrayList(); ArrayList spreadExpressions = new ArrayList(); ArrayList normalArguments = new ArrayList(); for (int i = 0; i < expressions.size(); i++) { Object expr = expressions.get(i); if (!(expr instanceof SpreadExpression)) { normalArguments.add(expr); } else { spreadIndexes.add(new ConstantExpression(Integer.valueOf(i - spreadExpressions.size()),true)); spreadExpressions.add(((SpreadExpression) expr).getExpression()); } } //load normal arguments as array visitTupleExpression(new ArgumentListExpression(normalArguments), wrap); //load spread expressions as array (new TupleExpression(spreadExpressions)).visit(this); //load insertion index (new ArrayExpression(ClassHelper.int_TYPE, spreadIndexes, null)).visit(this); controller.getOperandStack().remove(1); despreadList.call(controller.getMethodVisitor()); } public void visitTupleExpression(TupleExpression expression) { visitTupleExpression(expression, false); } void visitTupleExpression(TupleExpression expression, boolean useWrapper) { MethodVisitor mv = controller.getMethodVisitor(); int size = expression.getExpressions().size(); BytecodeHelper.pushConstant(mv, size); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); for (int i = 0; i < size; i++) { mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i); Expression argument = expression.getExpression(i); argument.visit(this); controller.getOperandStack().box(); if (useWrapper && argument instanceof CastExpression) loadWrapper(argument); mv.visitInsn(AASTORE); controller.getOperandStack().remove(1); } } public void loadWrapper(Expression argument) { MethodVisitor mv = controller.getMethodVisitor(); ClassNode goalClass = argument.getType(); visitClassExpression(new ClassExpression(goalClass)); if (goalClass.isDerivedFromGroovyObject()) { createGroovyObjectWrapperMethod.call(mv); } else { createPojoWrapperMethod.call(mv); } controller.getOperandStack().remove(1); } public void visitArrayExpression(ArrayExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); ClassNode elementType = expression.getElementType(); String arrayTypeName = BytecodeHelper.getClassInternalName(elementType); List sizeExpression = expression.getSizeExpression(); int size = 0; int dimensions = 0; if (sizeExpression != null) { for (Iterator iter = sizeExpression.iterator(); iter.hasNext();) { Expression element = (Expression) iter.next(); if (element == ConstantExpression.EMPTY_EXPRESSION) break; dimensions++; // let's convert to an int element.visit(this); controller.getOperandStack().doGroovyCast(ClassHelper.int_TYPE); } controller.getOperandStack().remove(dimensions); } else { size = expression.getExpressions().size(); BytecodeHelper.pushConstant(mv, size); } int storeIns = AASTORE; if (sizeExpression != null) { arrayTypeName = BytecodeHelper.getTypeDescription(expression.getType()); mv.visitMultiANewArrayInsn(arrayTypeName, dimensions); } else if (ClassHelper.isPrimitiveType(elementType)) { int primType = 0; if (elementType == ClassHelper.boolean_TYPE) { primType = T_BOOLEAN; storeIns = BASTORE; } else if (elementType == ClassHelper.char_TYPE) { primType = T_CHAR; storeIns = CASTORE; } else if (elementType == ClassHelper.float_TYPE) { primType = T_FLOAT; storeIns = FASTORE; } else if (elementType == ClassHelper.double_TYPE) { primType = T_DOUBLE; storeIns = DASTORE; } else if (elementType == ClassHelper.byte_TYPE) { primType = T_BYTE; storeIns = BASTORE; } else if (elementType == ClassHelper.short_TYPE) { primType = T_SHORT; storeIns = SASTORE; } else if (elementType == ClassHelper.int_TYPE) { primType = T_INT; storeIns = IASTORE; } else if (elementType == ClassHelper.long_TYPE) { primType = T_LONG; storeIns = LASTORE; } mv.visitIntInsn(NEWARRAY, primType); } else { mv.visitTypeInsn(ANEWARRAY, arrayTypeName); } for (int i = 0; i < size; i++) { mv.visitInsn(DUP); BytecodeHelper.pushConstant(mv, i); Expression elementExpression = expression.getExpression(i); if (elementExpression == null) { ConstantExpression.NULL.visit(this); } else { if (!elementType.equals(elementExpression.getType())) { visitCastExpression(new CastExpression(elementType, elementExpression, true)); } else { elementExpression.visit(this); } } mv.visitInsn(storeIns); controller.getOperandStack().remove(1); } controller.getOperandStack().push(expression.getType()); } public void visitClosureListExpression(ClosureListExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); controller.getCompileStack().pushVariableScope(expression.getVariableScope()); List expressions = expression.getExpressions(); final int size = expressions.size(); // init declarations LinkedList declarations = new LinkedList(); for (int i = 0; i < size; i++) { Expression expr = expressions.get(i); if (expr instanceof DeclarationExpression) { declarations.add((DeclarationExpression) expr); DeclarationExpression de = (DeclarationExpression) expr; BinaryExpression be = new BinaryExpression( de.getLeftExpression(), de.getOperation(), de.getRightExpression()); expressions.set(i, be); de.setRightExpression(ConstantExpression.NULL); visitDeclarationExpression(de); } } LinkedList instructions = new LinkedList(); BytecodeSequence seq = new BytecodeSequence(instructions); BlockStatement bs = new BlockStatement(); bs.addStatement(seq); Parameter closureIndex = new Parameter(ClassHelper.int_TYPE, "__closureIndex"); ClosureExpression ce = new ClosureExpression(new Parameter[]{closureIndex}, bs); ce.setVariableScope(expression.getVariableScope()); // to keep stack height put a null on stack instructions.add(ConstantExpression.NULL); // init table final Label dflt = new Label(); final Label tableEnd = new Label(); final Label[] labels = new Label[size]; instructions.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ILOAD, 1); mv.visitTableSwitchInsn(0, size - 1, dflt, labels); } }); // visit cases for (int i = 0; i < size; i++) { final Label label = new Label(); Object expr = expressions.get(i); final boolean isStatement = expr instanceof Statement; labels[i] = label; instructions.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitLabel(label); // expressions will leave a value on stack, statements not // so expressions need to pop the alibi null if (!isStatement) mv.visitInsn(POP); } }); instructions.add(expr); instructions.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitJumpInsn(GOTO, tableEnd); } }); } // default case { instructions.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitLabel(dflt); } }); ConstantExpression text = new ConstantExpression("invalid index for closure"); ConstructorCallExpression cce = new ConstructorCallExpression(ClassHelper.make(IllegalArgumentException.class), text); ThrowStatement ts = new ThrowStatement(cce); instructions.add(ts); } // return instructions.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitLabel(tableEnd); mv.visitInsn(ARETURN); } }); // load main Closure visitClosureExpression(ce); // we need later an array to store the curried // closures, so we create it here and ave it // in a temporary variable BytecodeHelper.pushConstant(mv, size); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int listArrayVar = controller.getCompileStack().defineTemporaryVariable("_listOfClosures", true); // add curried versions for (int i = 0; i < size; i++) { // stack: closure // we need to create a curried closure version // so we store the type on stack mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/CurriedClosure"); // stack: closure, type // for a constructor call we need the type two times // and the closure after them mv.visitInsn(DUP2); mv.visitInsn(SWAP); // stack: closure,type,type,closure // so we can create the curried closure mv.visitInsn(ICONST_1); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); mv.visitInsn(DUP); mv.visitInsn(ICONST_0); mv.visitLdcInsn(i); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); mv.visitInsn(AASTORE); mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/CurriedClosure", "", "(Lgroovy/lang/Closure;[Ljava/lang/Object;)V"); // stack: closure,curriedClosure // we need to save the result mv.visitVarInsn(ALOAD, listArrayVar); mv.visitInsn(SWAP); BytecodeHelper.pushConstant(mv, i); mv.visitInsn(SWAP); mv.visitInsn(AASTORE); // stack: closure } // we don't need the closure any longer, so remove it mv.visitInsn(POP); // we load the array and create a list from it mv.visitVarInsn(ALOAD, listArrayVar); createListMethod.call(mv); // remove the temporary variable to keep the // stack clean controller.getCompileStack().removeVar(listArrayVar); controller.getOperandStack().pop(); } public void visitBytecodeSequence(BytecodeSequence bytecodeSequence) { MethodVisitor mv = controller.getMethodVisitor(); List instructions = bytecodeSequence.getInstructions(); int mark = controller.getOperandStack().getStackLength(); for (Iterator iterator = instructions.iterator(); iterator.hasNext();) { Object part = iterator.next(); if (part == EmptyExpression.INSTANCE) { mv.visitInsn(ACONST_NULL); } else if (part instanceof Expression) { ((Expression) part).visit(this); } else if (part instanceof Statement) { Statement stm = (Statement) part; stm.visit(this); mv.visitInsn(ACONST_NULL); } else { BytecodeInstruction runner = (BytecodeInstruction) part; runner.visit(mv); } } controller.getOperandStack().remove(mark-controller.getOperandStack().getStackLength()); } public void visitListExpression(ListExpression expression) { onLineNumber(expression,"ListExpression" ); int size = expression.getExpressions().size(); boolean containsSpreadExpression = containsSpreadExpression(expression); boolean containsOnlyConstants = !containsSpreadExpression && containsOnlyConstants(expression); OperandStack operandStack = controller.getOperandStack(); if (!containsSpreadExpression) { MethodVisitor mv = controller.getMethodVisitor(); BytecodeHelper.pushConstant(mv, size); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int maxInit = 1000; if (size expressions = expression.getExpressions(); List methods = new ArrayList(); MethodVisitor oldMv = mv; int index = 0; int methodIndex = 0; while (index", "([Ljava/lang/Object;[Ljava/lang/String;)V"); controller.getOperandStack().push(ClassHelper.GSTRING_TYPE); } /** * Note: ignore it. Annotation generation needs the current visitor. */ public void visitAnnotations(AnnotatedNode node) { } private void visitAnnotations(AnnotatedNode targetNode, Object visitor) { for (AnnotationNode an : targetNode.getAnnotations()) { // skip built-in properties if (an.isBuiltIn()) continue; if (an.hasSourceRetention()) continue; AnnotationVisitor av = getAnnotationVisitor(targetNode, an, visitor); visitAnnotationAttributes(an, av); av.visitEnd(); } } private void visitParameterAnnotations(Parameter parameter, int paramNumber, MethodVisitor mv) { for (AnnotationNode an : parameter.getAnnotations()) { // skip built-in properties if (an.isBuiltIn()) continue; if (an.hasSourceRetention()) continue; final String annotationDescriptor = BytecodeHelper.getTypeDescription(an.getClassNode()); AnnotationVisitor av = mv.visitParameterAnnotation(paramNumber, annotationDescriptor, an.hasRuntimeRetention()); visitAnnotationAttributes(an, av); av.visitEnd(); } } private AnnotationVisitor getAnnotationVisitor(AnnotatedNode targetNode, AnnotationNode an, Object visitor) { final String annotationDescriptor = BytecodeHelper.getTypeDescription(an.getClassNode()); if (targetNode instanceof MethodNode) { return ((MethodVisitor) visitor).visitAnnotation(annotationDescriptor, an.hasRuntimeRetention()); } else if (targetNode instanceof FieldNode) { return ((FieldVisitor) visitor).visitAnnotation(annotationDescriptor, an.hasRuntimeRetention()); } else if (targetNode instanceof ClassNode) { return ((ClassVisitor) visitor).visitAnnotation(annotationDescriptor, an.hasRuntimeRetention()); } throwException("Cannot create an AnnotationVisitor. Please report Groovy bug"); return null; } /** * Generate the annotation attributes. * @param an the node with an annotation * @param av the visitor to use */ private void visitAnnotationAttributes(AnnotationNode an, AnnotationVisitor av) { Map constantAttrs = new HashMap(); Map enumAttrs = new HashMap(); Map atAttrs = new HashMap(); Map arrayAttrs = new HashMap(); for (String name : an.getMembers().keySet()) { Expression expr = an.getMember(name); if (expr instanceof AnnotationConstantExpression) { atAttrs.put(name, ((AnnotationConstantExpression) expr).getValue()); } else if (expr instanceof ConstantExpression) { constantAttrs.put(name, ((ConstantExpression) expr).getValue()); } else if (expr instanceof ClassExpression) { constantAttrs.put(name, Type.getType(BytecodeHelper.getTypeDescription((expr.getType())))); } else if (expr instanceof PropertyExpression) { enumAttrs.put(name, (PropertyExpression) expr); } else if (expr instanceof ListExpression) { arrayAttrs.put(name, (ListExpression) expr); } else if (expr instanceof ClosureExpression) { ClassNode closureClass = controller.getClosureWriter().getOrAddClosureClass((ClosureExpression) expr, ACC_PUBLIC); constantAttrs.put(name, Type.getType(BytecodeHelper.getTypeDescription(closureClass))); } } for (Map.Entry entry : constantAttrs.entrySet()) { av.visit((String) entry.getKey(), entry.getValue()); } for (Map.Entry entry : enumAttrs.entrySet()) { PropertyExpression propExp = (PropertyExpression) entry.getValue(); av.visitEnum((String) entry.getKey(), BytecodeHelper.getTypeDescription(propExp.getObjectExpression().getType()), String.valueOf(((ConstantExpression) propExp.getProperty()).getValue())); } for (Map.Entry entry : atAttrs.entrySet()) { AnnotationNode atNode = (AnnotationNode) entry.getValue(); AnnotationVisitor av2 = av.visitAnnotation((String) entry.getKey(), BytecodeHelper.getTypeDescription(atNode.getClassNode())); visitAnnotationAttributes(atNode, av2); av2.visitEnd(); } visitArrayAttributes(an, arrayAttrs, av); } private void visitArrayAttributes(AnnotationNode an, Map arrayAttr, AnnotationVisitor av) { if (arrayAttr.isEmpty()) return; for (Map.Entry entry : arrayAttr.entrySet()) { AnnotationVisitor av2 = av.visitArray((String) entry.getKey()); List values = ((ListExpression) entry.getValue()).getExpressions(); if (!values.isEmpty()) { int arrayElementType = determineCommonArrayType(values); for (Expression exprChild : values) { visitAnnotationArrayElement(exprChild, arrayElementType, av2); } } av2.visitEnd(); } } private int determineCommonArrayType(List values) { Expression expr = (Expression) values.get(0); int arrayElementType = -1; if (expr instanceof AnnotationConstantExpression) { arrayElementType = 1; } else if (expr instanceof ConstantExpression) { arrayElementType = 2; } else if (expr instanceof ClassExpression) { arrayElementType = 3; } else if (expr instanceof PropertyExpression) { arrayElementType = 4; } return arrayElementType; } private void visitAnnotationArrayElement(Expression expr, int arrayElementType, AnnotationVisitor av) { switch (arrayElementType) { case 1: AnnotationNode atAttr = (AnnotationNode) ((AnnotationConstantExpression) expr).getValue(); AnnotationVisitor av2 = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(atAttr.getClassNode())); visitAnnotationAttributes(atAttr, av2); av2.visitEnd(); break; case 2: av.visit(null, ((ConstantExpression) expr).getValue()); break; case 3: av.visit(null, Type.getType(BytecodeHelper.getTypeDescription(expr.getType()))); break; case 4: PropertyExpression propExpr = (PropertyExpression) expr; av.visitEnum(null, BytecodeHelper.getTypeDescription(propExpr.getObjectExpression().getType()), String.valueOf(((ConstantExpression) propExpr.getProperty()).getValue())); break; } } // Implementation methods //------------------------------------------------------------------------- public void visitBytecodeExpression(BytecodeExpression cle) { cle.visit(controller.getMethodVisitor()); controller.getOperandStack().push(cle.getType()); } public static boolean isThisExpression(Expression expression) { if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; return varExp.getName().equals("this"); } return false; } private static boolean isSuperExpression(Expression expression) { if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; return varExp.getName().equals("super"); } return false; } private static boolean isThisOrSuper(Expression expression) { return isThisExpression(expression) || isSuperExpression(expression); } public void onLineNumber(ASTNode statement, String message) { MethodVisitor mv = controller.getMethodVisitor(); if (statement==null) return; int line = statement.getLineNumber(); this.currentASTNode = statement; if (line < 0) return; if (!ASM_DEBUG && line==lineNumber) return; lineNumber = line; if (mv != null) { Label l = new Label(); mv.visitLabel(l); mv.visitLineNumber(line, l); } } private boolean isInnerClass() { return controller.getClassNode() instanceof InnerClassNode; } protected CompileUnit getCompileUnit() { CompileUnit answer = controller.getClassNode().getCompileUnit(); if (answer == null) { answer = context.getCompileUnit(); } return answer; } protected int getBytecodeVersion() { return Opcodes.V1_5; } public boolean addInnerClass(ClassNode innerClass) { innerClass.setModule(controller.getClassNode().getModule()); return innerClasses.add(innerClass); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/GeneratorContext.java0000644001501200150120000000540411667450312025760 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.CompileUnit; import org.codehaus.groovy.ast.MethodNode; /** * A context shared across generations of a class and its inner classes * * @author James Strachan * @version $Revision$ */ public class GeneratorContext { private int innerClassIdx = 1; private int closureClassIdx = 1; private CompileUnit compileUnit; public GeneratorContext(CompileUnit compileUnit) { this.compileUnit = compileUnit; } public GeneratorContext(CompileUnit compileUnit, int innerClassOffset) { this.compileUnit = compileUnit; this.innerClassIdx = innerClassOffset; } public int getNextInnerClassIdx() { return innerClassIdx++; } public CompileUnit getCompileUnit() { return compileUnit; } public String getNextClosureInnerName(ClassNode owner, ClassNode enclosingClass, MethodNode enclosingMethod) { String ownerShortName = owner.getNameWithoutPackage(); String classShortName = enclosingClass.getNameWithoutPackage(); if (classShortName.equals(ownerShortName)) { classShortName = ""; } else { classShortName += "_"; } // remove $ int dp = classShortName.lastIndexOf("$"); if (dp >= 0) { classShortName = classShortName.substring(++dp); } // remove leading _ if (classShortName.startsWith("_")) { classShortName = classShortName.substring(1); } String methodName = ""; if (enclosingMethod != null) { methodName = enclosingMethod.getName() + "_"; if (enclosingClass.isDerivedFrom(ClassHelper.CLOSURE_TYPE)) { methodName = ""; } methodName = methodName.replace('<', '_'); methodName = methodName.replace('>', '_'); methodName = methodName.replaceAll(" ", "_"); } return "_" + classShortName + methodName + "closure" + closureClassIdx++; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/BytecodeSequence.java0000644001501200150120000000506611707612044025715 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.stmt.Statement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This class represents a sequence of BytecodeInstructions * or ASTNodes. The evaluation is depending on the type of * the visitor. * * @see BytecodeInstruction * @see ASTNode */ public class BytecodeSequence extends Statement { private final List instructions; public BytecodeSequence(List instructions) { this.instructions = instructions; } public BytecodeSequence(BytecodeInstruction instruction) { this.instructions = new ArrayList(1); this.instructions.add(instruction); } /** * Delegates to the visit method used for this class. * If the visitor is a ClassGenerator, then * {@link ClassGenerator#visitBytecodeSequence(BytecodeSequence)} * is called with this instance. If the visitor is no * ClassGenerator, then this method will call visit on * each ASTNode element sorted by this class. If one * element is a BytecodeInstruction, then it will be skipped * as it is no ASTNode. * * @param visitor the visitor * @see ClassGenerator */ public void visit(GroovyCodeVisitor visitor) { if (visitor instanceof ClassGenerator) { ClassGenerator gen = (ClassGenerator) visitor; gen.visitBytecodeSequence(this); return; } for (Iterator iterator = instructions.iterator(); iterator.hasNext();) { Object part = (Object) iterator.next(); if (part instanceof ASTNode) { ((ASTNode)part).visit(visitor); } } } public List getInstructions() { return instructions; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/VariableScopeVisitor.java0000644001501200150120000004770411707612044026572 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.Types; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import static java.lang.reflect.Modifier.isFinal; /** * goes through an AST and initializes the scopes * * @author Jochen Theodorou */ public class VariableScopeVisitor extends ClassCodeVisitorSupport { private VariableScope currentScope = null; private VariableScope headScope = new VariableScope(); private ClassNode currentClass = null; private SourceUnit source; private boolean inPropertyExpression = false; private boolean isSpecialConstructorCall = false; private boolean inConstructor = false; private LinkedList stateStack = new LinkedList(); private class StateStackElement { VariableScope scope; ClassNode clazz; boolean inConstructor; StateStackElement() { scope = VariableScopeVisitor.this.currentScope; clazz = VariableScopeVisitor.this.currentClass; inConstructor = VariableScopeVisitor.this.inConstructor; } } public VariableScopeVisitor(SourceUnit source) { this.source = source; currentScope = headScope; } // ------------------------------ // helper methods //------------------------------ private void pushState(boolean isStatic) { stateStack.add(new StateStackElement()); currentScope = new VariableScope(currentScope); currentScope.setInStaticContext(isStatic); } private void pushState() { pushState(currentScope.isInStaticContext()); } private void popState() { StateStackElement element = (StateStackElement) stateStack.removeLast(); currentScope = element.scope; currentClass = element.clazz; inConstructor = element.inConstructor; } private void declare(Parameter[] parameters, ASTNode node) { for (Parameter parameter : parameters) { if (parameter.hasInitialExpression()) { parameter.getInitialExpression().visit(this); } declare(parameter, node); } } private void declare(VariableExpression vex) { vex.setInStaticContext(currentScope.isInStaticContext()); declare(vex, vex); vex.setAccessedVariable(vex); } private void declare(Variable var, ASTNode expr) { String scopeType = "scope"; String variableType = "variable"; if (expr.getClass() == FieldNode.class) { scopeType = "class"; variableType = "field"; } else if (expr.getClass() == PropertyNode.class) { scopeType = "class"; variableType = "property"; } StringBuilder msg = new StringBuilder(); msg.append("The current ").append(scopeType); msg.append(" already contains a ").append(variableType); msg.append(" of the name ").append(var.getName()); if (currentScope.getDeclaredVariable(var.getName()) != null) { addError(msg.toString(), expr); return; } for (VariableScope scope = currentScope.getParent(); scope != null; scope = scope.getParent()) { // if we are in a class and no variable is declared until // now, then we can break the loop, because we are allowed // to declare a variable of the same name as a class member if (scope.getClassScope() != null) break; if (scope.getDeclaredVariable(var.getName()) != null) { // variable already declared addError(msg.toString(), expr); break; } } // declare the variable even if there was an error to allow more checks currentScope.putDeclaredVariable(var); } protected SourceUnit getSourceUnit() { return source; } private Variable findClassMember(ClassNode cn, String name) { if (cn == null) return null; if (cn.isScript()) { return new DynamicVariable(name, false); } for (FieldNode fn : cn.getFields()) { if (fn.getName().equals(name)) return fn; } for (MethodNode mn : cn.getMethods()) { String pName = getPropertyName(mn); if (pName != null && pName.equals(name)) return new PropertyNode(pName, mn.getModifiers(), getPropertyType(mn), cn, null, null, null); } for (PropertyNode pn : cn.getProperties()) { if (pn.getName().equals(name)) return pn; } Variable ret = findClassMember(cn.getSuperClass(), name); if (ret != null) return ret; return findClassMember(cn.getOuterClass(), name); } private ClassNode getPropertyType(MethodNode m) { if (m.getReturnType() != ClassHelper.VOID_TYPE) { return m.getReturnType(); } return m.getParameters()[0].getType(); } private String getPropertyName(MethodNode m) { String name = m.getName(); if (!(name.startsWith("set") || name.startsWith("get"))) return null; String pname = name.substring(3); if (pname.length() == 0) return null; pname = java.beans.Introspector.decapitalize(pname); if (name.startsWith("get") && (m.getReturnType() == ClassHelper.VOID_TYPE || m.getParameters().length != 0)) { return null; } if (name.startsWith("set") && m.getParameters().length != 1) { return null; } return pname; } // ------------------------------- // different Variable based checks // ------------------------------- private Variable checkVariableNameForDeclaration(String name, Expression expression) { if ("super".equals(name) || "this".equals(name)) return null; VariableScope scope = currentScope; Variable var = new DynamicVariable(name, currentScope.isInStaticContext()); // try to find a declaration of a variable while (true) { Variable var1; var1 = scope.getDeclaredVariable(var.getName()); if (var1 != null) { var = var1; break; } var1 = scope.getReferencedLocalVariable(var.getName()); if (var1 != null) { var = var1; break; } var1 = scope.getReferencedClassVariable(var.getName()); if (var1 != null) { var = var1; break; } ClassNode classScope = scope.getClassScope(); if (classScope != null) { Variable member = findClassMember(classScope, var.getName()); if (member != null) { boolean staticScope = currentScope.isInStaticContext() || isSpecialConstructorCall; boolean staticMember = member.isInStaticContext(); // We don't allow a static context (e.g. a static method) to access // a non-static variable (e.g. a non-static field). if (!(staticScope && !staticMember)) var = member; } break; } scope = scope.getParent(); } VariableScope end = scope; scope = currentScope; while (scope != end) { if (end.isClassScope() || (end.isReferencedClassVariable(name) && end.getDeclaredVariable(name) == null)) { scope.putReferencedClassVariable(var); } else { //var.setClosureSharedVariable(var.isClosureSharedVariable() || inClosure); scope.putReferencedLocalVariable(var); } scope = scope.getParent(); } return var; } /** * a property on "this", like this.x is transformed to a * direct field access, so we need to check the * static context here * * @param pe the property expression to check */ private void checkPropertyOnExplicitThis(PropertyExpression pe) { if (!currentScope.isInStaticContext()) return; Expression object = pe.getObjectExpression(); if (!(object instanceof VariableExpression)) return; VariableExpression ve = (VariableExpression) object; if (!ve.getName().equals("this")) return; String name = pe.getPropertyAsString(); if (name == null || name.equals("class")) return; Variable member = findClassMember(currentClass, name); if (member == null) return; checkVariableContextAccess(member, pe); } private void checkVariableContextAccess(Variable v, Expression expr) { if (inPropertyExpression || v.isInStaticContext() || !currentScope.isInStaticContext()) return; String msg = v.getName() + " is declared in a dynamic context, but you tried to" + " access it from a static context."; addError(msg, expr); // declare a static variable to be able to continue the check DynamicVariable v2 = new DynamicVariable(v.getName(), currentScope.isInStaticContext()); currentScope.putDeclaredVariable(v2); } // ------------------------------ // code visit // ------------------------------ public void visitBlockStatement(BlockStatement block) { pushState(); block.setVariableScope(currentScope); super.visitBlockStatement(block); popState(); } public void visitForLoop(ForStatement forLoop) { pushState(); forLoop.setVariableScope(currentScope); Parameter p = forLoop.getVariable(); p.setInStaticContext(currentScope.isInStaticContext()); if (p != ForStatement.FOR_LOOP_DUMMY) declare(p, forLoop); super.visitForLoop(forLoop); popState(); } public void visitDeclarationExpression(DeclarationExpression expression) { // visit right side first to avoid the usage of a // variable before its declaration expression.getRightExpression().visit(this); if (expression.isMultipleAssignmentDeclaration()) { TupleExpression list = expression.getTupleExpression(); for (Expression e : list.getExpressions()) { declare((VariableExpression) e); } } else { declare(expression.getVariableExpression()); } } @Override public void visitBinaryExpression(BinaryExpression be) { super.visitBinaryExpression(be); switch (be.getOperation().getType()) { case Types.EQUAL: // = assignment case Types.BITWISE_AND_EQUAL: case Types.BITWISE_OR_EQUAL: case Types.BITWISE_XOR_EQUAL: case Types.PLUS_EQUAL: case Types.MINUS_EQUAL: case Types.MULTIPLY_EQUAL: case Types.DIVIDE_EQUAL: case Types.INTDIV_EQUAL: case Types.MOD_EQUAL: case Types.POWER_EQUAL: case Types.LEFT_SHIFT_EQUAL: case Types.RIGHT_SHIFT_EQUAL: case Types.RIGHT_SHIFT_UNSIGNED_EQUAL: checkFinalFieldAccess(be.getLeftExpression()); break; default: break; } } private void checkFinalFieldAccess(Expression expression) { // currently not looking for PropertyExpression: dealt with at runtime using ReadOnlyPropertyException if (!(expression instanceof VariableExpression) && !(expression instanceof TupleExpression)) return; if (expression instanceof TupleExpression) { TupleExpression list = (TupleExpression) expression; for (Expression e : list.getExpressions()) { checkForFinal(expression, (VariableExpression) e); } } else { checkForFinal(expression, (VariableExpression) expression); } } // TODO handle local variables private void checkForFinal(final Expression expression, VariableExpression ve) { Variable v = ve.getAccessedVariable(); boolean isFinal = isFinal(v.getModifiers()); boolean isParameter = v instanceof Parameter; if (isFinal && isParameter) { addError("Cannot assign a value to final variable '" + v.getName() + "'", expression); } } public void visitVariableExpression(VariableExpression expression) { String name = expression.getName(); Variable v = checkVariableNameForDeclaration(name, expression); if (v == null) return; expression.setAccessedVariable(v); checkVariableContextAccess(v, expression); } public void visitPropertyExpression(PropertyExpression expression) { boolean ipe = inPropertyExpression; inPropertyExpression = true; expression.getObjectExpression().visit(this); inPropertyExpression = false; expression.getProperty().visit(this); checkPropertyOnExplicitThis(expression); inPropertyExpression = ipe; } public void visitClosureExpression(ClosureExpression expression) { pushState(); expression.setVariableScope(currentScope); if (expression.isParameterSpecified()) { Parameter[] parameters = expression.getParameters(); for (Parameter parameter : parameters) { parameter.setInStaticContext(currentScope.isInStaticContext()); if (parameter.hasInitialExpression()) { parameter.getInitialExpression().visit(this); } declare(parameter, expression); } } else if (expression.getParameters() != null) { Parameter var = new Parameter(ClassHelper.OBJECT_TYPE, "it"); var.setInStaticContext(currentScope.isInStaticContext()); currentScope.putDeclaredVariable(var); } super.visitClosureExpression(expression); markClosureSharedVariables(); popState(); } private void markClosureSharedVariables() { VariableScope scope = currentScope; for (Iterator it = scope.getReferencedLocalVariablesIterator(); it.hasNext(); ) { it.next().setClosureSharedVariable(true); } } public void visitCatchStatement(CatchStatement statement) { pushState(); Parameter p = statement.getVariable(); p.setInStaticContext(currentScope.isInStaticContext()); declare(p, statement); super.visitCatchStatement(statement); popState(); } public void visitFieldExpression(FieldExpression expression) { String name = expression.getFieldName(); //TODO: change that to get the correct scope Variable v = checkVariableNameForDeclaration(name, expression); checkVariableContextAccess(v, expression); } // ------------------------------ // class visit // ------------------------------ public void visitClass(ClassNode node) { // AIC are already done, doing them here again will lead // to wrong scopes if (node instanceof InnerClassNode) { InnerClassNode in = (InnerClassNode) node; if (in.isAnonymous()) return; } pushState(); currentClass = node; currentScope.setClassScope(node); super.visitClass(node); popState(); } protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { pushState(node.isStatic()); inConstructor = isConstructor; node.setVariableScope(currentScope); visitAnnotations(node); // GROOVY-2156 Parameter[] parameters = node.getParameters(); for (Parameter parameter : parameters) { visitAnnotations(parameter); } declare(node.getParameters(), node); visitClassCodeContainer(node.getCode()); popState(); } public void visitMethodCallExpression(MethodCallExpression call) { if (call.isImplicitThis() && call.getMethod() instanceof ConstantExpression) { ConstantExpression methodNameConstant = (ConstantExpression) call.getMethod(); Object value = methodNameConstant.getText(); if (!(value instanceof String)) { throw new GroovyBugError("tried to make a method call with a non-String constant method name."); } String methodName = (String) value; Variable v = checkVariableNameForDeclaration(methodName, call); if (v != null && !(v instanceof DynamicVariable)) { checkVariableContextAccess(v, call); } if (v instanceof VariableExpression || v instanceof Parameter) { VariableExpression object = new VariableExpression(v); object.setSourcePosition(methodNameConstant); call.setObjectExpression(object); ConstantExpression method = new ConstantExpression("call"); method.setSourcePosition(methodNameConstant); // important for GROOVY-4344 call.setMethod(method); } } super.visitMethodCallExpression(call); } public void visitConstructorCallExpression(ConstructorCallExpression call) { isSpecialConstructorCall = call.isSpecialCall(); super.visitConstructorCallExpression(call); isSpecialConstructorCall = false; if (!call.isUsingAnonymousInnerClass()) return; pushState(); InnerClassNode innerClass = (InnerClassNode) call.getType(); innerClass.setVariableScope(currentScope); for (MethodNode method : innerClass.getMethods()) { Parameter[] parameters = method.getParameters(); if (parameters.length == 0) parameters = null; // null means no implicit "it" ClosureExpression cl = new ClosureExpression(parameters, method.getCode()); visitClosureExpression(cl); } for (FieldNode field : innerClass.getFields()) { final Expression expression = field.getInitialExpression(); if (expression != null) { expression.visit(this); } } for (Statement statement : innerClass.getObjectInitializerStatements()) { statement.visit(this); } markClosureSharedVariables(); popState(); } public void visitProperty(PropertyNode node) { pushState(node.isStatic()); super.visitProperty(node); popState(); } public void visitField(FieldNode node) { pushState(node.isStatic()); super.visitField(node); popState(); } public void visitAnnotations(AnnotatedNode node) { List annotations = node.getAnnotations(); if (annotations.isEmpty()) return; for (AnnotationNode an : annotations) { // skip built-in properties if (an.isBuiltIn()) continue; for (Map.Entry member : an.getMembers().entrySet()) { Expression annMemberValue = member.getValue(); annMemberValue.visit(this); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java0000644001501200150120000002235411707612044030140 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import static org.objectweb.asm.Opcodes.*; import static org.codehaus.groovy.classgen.InnerClassVisitorHelper.*; public class InnerClassCompletionVisitor { public void visitClass(ClassNode node) { InnerClassNode innerClass = null; if (!node.isEnum() && !node.isInterface() && node instanceof InnerClassNode) { innerClass = (InnerClassNode) node; } if (node.isEnum() || node.isInterface()) return; addDispatcherMethods(node); if (innerClass == null) return; addDefaultMethods(innerClass); } private String getTypeDescriptor(ClassNode node, boolean isStatic) { return BytecodeHelper.getTypeDescription(getClassNode(node, isStatic)); } private String getInternalName(ClassNode node, boolean isStatic) { return BytecodeHelper.getClassInternalName(getClassNode(node, isStatic)); } private void addDispatcherMethods(ClassNode classNode) { final int objectDistance = getObjectDistance(classNode); // since we added an anonymous inner class we should also // add the dispatcher methods // add method dispatcher Parameter[] parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "args") }; MethodNode method = classNode.addSyntheticMethod( "this$dist$invoke$" + objectDistance, ACC_PUBLIC + ACC_SYNTHETIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); BlockStatement block = new BlockStatement(); setMethodDispatcherCode(block, VariableExpression.THIS_EXPRESSION, parameters); method.setCode(block); // add property setter parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "value") }; method = classNode.addSyntheticMethod( "this$dist$set$" + objectDistance, ACC_PUBLIC + ACC_SYNTHETIC, ClassHelper.VOID_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); block = new BlockStatement(); setPropertySetterDispatcher(block, VariableExpression.THIS_EXPRESSION, parameters); method.setCode(block); // add property getter parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name") }; method = classNode.addSyntheticMethod( "this$dist$get$" + objectDistance, ACC_PUBLIC + ACC_SYNTHETIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); block = new BlockStatement(); setPropertyGetterDispatcher(block, VariableExpression.THIS_EXPRESSION, parameters); method.setCode(block); } private void addDefaultMethods(InnerClassNode node) { final boolean isStatic = isStatic(node); ClassNode outerClass = node.getOuterClass(); final String classInternalName = org.codehaus.groovy.classgen.asm.BytecodeHelper.getClassInternalName(node); final String outerClassInternalName = getInternalName(outerClass, isStatic); final String outerClassDescriptor = getTypeDescriptor(outerClass, isStatic); final int objectDistance = getObjectDistance(outerClass); // add method dispatcher Parameter[] parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "args") }; MethodNode method = node.addSyntheticMethod( "methodMissing", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); BlockStatement block = new BlockStatement(); if (isStatic) { setMethodDispatcherCode(block, new ClassExpression(outerClass), parameters); } else { block.addStatement( new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classInternalName, "this$0", outerClassDescriptor); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, outerClassInternalName, "this$dist$invoke$" + objectDistance, "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(ARETURN); } }) ); } method.setCode(block); // add property getter dispatcher parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "val") }; method = node.addSyntheticMethod( "propertyMissing", Opcodes.ACC_PUBLIC, ClassHelper.VOID_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); block = new BlockStatement(); if (isStatic) { setPropertySetterDispatcher(block, new ClassExpression(node.getOuterClass()), parameters); } else { block.addStatement( new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classInternalName, "this$0", outerClassDescriptor); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, outerClassInternalName, "this$dist$set$" + objectDistance, "(Ljava/lang/String;Ljava/lang/Object;)V"); mv.visitInsn(RETURN); } }) ); } method.setCode(block); // add property setter dispatcher parameters = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "name") }; method = node.addSyntheticMethod( "propertyMissing", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, null ); block = new BlockStatement(); if (isStatic) { setPropertyGetterDispatcher(block, new ClassExpression(node.getOuterClass()), parameters); } else { block.addStatement( new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classInternalName, "this$0", outerClassDescriptor); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, outerClassInternalName, "this$dist$get$" + objectDistance, "(Ljava/lang/String;)Ljava/lang/Object;"); mv.visitInsn(ARETURN); } }) ); } method.setCode(block); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/DummyClassGenerator.java0000644001501200150120000001376711707612044026425 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.Iterator; /** * To generate a class that has all the fields and methods, except that fields are not initialized * and methods are empty. It's intended for being used as a place holder during code generation * of reference to the "this" class itself. * * @author James Strachan * @author Bing Ran * @version $Revision$ */ public class DummyClassGenerator extends ClassGenerator { private ClassVisitor cv; private MethodVisitor mv; private GeneratorContext context; // current class details private ClassNode classNode; private String internalClassName; private String internalBaseClassName; public DummyClassGenerator( GeneratorContext context, ClassVisitor classVisitor, ClassLoader classLoader, String sourceFile) { this.context = context; this.cv = classVisitor; } // GroovyClassVisitor interface //------------------------------------------------------------------------- public void visitClass(ClassNode classNode) { try { this.classNode = classNode; this.internalClassName = BytecodeHelper.getClassInternalName(classNode); //System.out.println("Generating class: " + classNode.getName()); this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass()); cv.visit( Opcodes.V1_3, classNode.getModifiers(), internalClassName, (String) null, internalBaseClassName, BytecodeHelper.getClassInternalNames(classNode.getInterfaces()) ); classNode.visitContents(this); for (Iterator iter = innerClasses.iterator(); iter.hasNext();) { ClassNode innerClass = (ClassNode) iter.next(); ClassNode innerClassType = innerClass; String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassType); String outerClassName = internalClassName; // default for inner classes MethodNode enclosingMethod = innerClass.getEnclosingMethod(); if (enclosingMethod != null) { // local inner classes do not specify the outer class name outerClassName = null; } cv.visitInnerClass( innerClassInternalName, outerClassName, innerClassType.getName(), innerClass.getModifiers()); } cv.visitEnd(); } catch (GroovyRuntimeException e) { e.setModule(classNode.getModule()); throw e; } } public void visitConstructor(ConstructorNode node) { visitParameters(node, node.getParameters()); String methodType = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, node.getParameters()); mv = cv.visitMethod(node.getModifiers(), "", methodType, null, null); mv.visitTypeInsn(NEW, "java/lang/RuntimeException"); mv.visitInsn(DUP); mv.visitLdcInsn("not intended for execution"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); } public void visitMethod(MethodNode node) { visitParameters(node, node.getParameters()); String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), node.getParameters()); mv = cv.visitMethod(node.getModifiers(), node.getName(), methodType, null, null); mv.visitTypeInsn(NEW, "java/lang/RuntimeException"); mv.visitInsn(DUP); mv.visitLdcInsn("not intended for execution"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); } public void visitField(FieldNode fieldNode) { cv.visitField( fieldNode.getModifiers(), fieldNode.getName(), BytecodeHelper.getTypeDescription(fieldNode.getType()), null, //fieldValue, //br all the sudden that one cannot init the field here. init is done in static initializer and instance initializer. null); } /** * Creates a getter, setter and field */ public void visitProperty(PropertyNode statement) { } protected CompileUnit getCompileUnit() { CompileUnit answer = classNode.getCompileUnit(); if (answer == null) { answer = context.getCompileUnit(); } return answer; } protected void visitParameters(ASTNode node, Parameter[] parameters) { for (int i = 0, size = parameters.length; i < size; i++) { visitParameter(node, parameters[i]); } } protected void visitParameter(ASTNode node, Parameter parameter) { } public void visitAnnotations(AnnotatedNode node) { } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/ClassGenerator.java0000644001501200150120000000301511707612044025372 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import java.util.LinkedList; /** * Abstract base class for generator of Java class versions of Groovy AST classes * * @author James Strachan * @author Russel Winder * @version $Revision$ */ public abstract class ClassGenerator extends ClassCodeVisitorSupport implements Opcodes { // inner classes created while generating bytecode protected LinkedList innerClasses = new LinkedList(); public LinkedList getInnerClasses() { return innerClasses; } protected SourceUnit getSourceUnit() { return null; } public void visitBytecodeSequence(BytecodeSequence bytecodeSequence) { } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/package.html0000644001501200150120000000025711627206700024100 0ustar miguelmiguel package org.codehaus.groovy.classgen.*

      Generates Java classes for Groovy classes using ASM.

      groovy-1.8.6/src/main/org/codehaus/groovy/classgen/EnumCompletionVisitor.java0000644001501200150120000001205611707612044027001 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.List; /** * Enums have a parent constructor with two arguments from java.lang.Enum. * This visitor adds those two arguments into manually created constructors * and performs the necessary super call. */ public class EnumCompletionVisitor extends ClassCodeVisitorSupport { private final SourceUnit sourceUnit; public EnumCompletionVisitor(CompilationUnit cu, SourceUnit su) { sourceUnit = su; } public void visitClass(ClassNode node) { if (!node.isEnum()) return; completeEnum(node); } protected SourceUnit getSourceUnit() { return sourceUnit; } private void completeEnum(ClassNode enumClass) { addConstructor(enumClass); } private void addConstructor(ClassNode enumClass) { // first look if there are declared constructors List ctors = new ArrayList(enumClass.getDeclaredConstructors()); if (ctors.size() == 0) { // add default constructor ConstructorNode init = new ConstructorNode(Opcodes.ACC_PUBLIC, new Parameter[0], ClassNode.EMPTY_ARRAY, new BlockStatement()); enumClass.addConstructor(init); ctors.add(init); } // for each constructor: // if constructor does not define a call to super, then transform constructor // to get String,int parameters at beginning and add call super(String,int) for (ConstructorNode ctor : ctors) { transformConstructor(ctor); } } private void transformConstructor(ConstructorNode ctor) { boolean chainedThisConstructorCall = false; ConstructorCallExpression cce = null; if (ctor.firstStatementIsSpecialConstructorCall()) { Statement code = ctor.getFirstStatement(); cce = (ConstructorCallExpression) ((ExpressionStatement) code).getExpression(); if (cce.isSuperCall()) return; // must be call to this(...) chainedThisConstructorCall = true; } // we need to add parameters Parameter[] oldP = ctor.getParameters(); Parameter[] newP = new Parameter[oldP.length + 2]; String stringParameterName = getUniqueVariableName("__str", ctor.getCode()); newP[0] = new Parameter(ClassHelper.STRING_TYPE, stringParameterName); String intParameterName = getUniqueVariableName("__int", ctor.getCode()); newP[1] = new Parameter(ClassHelper.int_TYPE, intParameterName); System.arraycopy(oldP, 0, newP, 2, oldP.length); ctor.setParameters(newP); if (chainedThisConstructorCall) { TupleExpression args = (TupleExpression) cce.getArguments(); List argsExprs = args.getExpressions(); argsExprs.add(0, new VariableExpression(stringParameterName)); argsExprs.add(1, new VariableExpression(intParameterName)); } else { // and a super call cce = new ConstructorCallExpression( ClassNode.SUPER, new ArgumentListExpression( new VariableExpression(stringParameterName), new VariableExpression(intParameterName) ) ); BlockStatement code = new BlockStatement(); code.addStatement(new ExpressionStatement(cce)); Statement oldCode = ctor.getCode(); if (oldCode != null) code.addStatement(oldCode); ctor.setCode(code); } } private String getUniqueVariableName(final String name, Statement code) { if (code == null) return name; final Object[] found = new Object[1]; CodeVisitorSupport cv = new CodeVisitorSupport() { public void visitVariableExpression(VariableExpression expression) { if (expression.getName().equals(name)) found[0] = Boolean.TRUE; } }; code.visit(cv); if (found[0] != null) return getUniqueVariableName("_" + name, code); return name; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/0000755001501200150120000000000011715031256022373 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryLongExpressionHelper.java0000644001501200150120000000713611707612046030534 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import static org.objectweb.asm.Opcodes.*; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; /** * @author Jochen "blackdrag" Theodorou */ public class BinaryLongExpressionHelper extends BinaryExpressionWriter { public BinaryLongExpressionHelper(WriterController controller) { super(controller); } protected void doubleTwoOperands(MethodVisitor mv) { /* since there is no DUP4 we have to do this: DUP2_X1 POP2 DUP2_X1 DUP2_X1 POP2 DUP2_X1 */ mv.visitInsn(DUP2_X1); mv.visitInsn(POP2); mv.visitInsn(DUP2_X1); mv.visitInsn(DUP2_X1); mv.visitInsn(POP2); mv.visitInsn(DUP2_X1); } protected void removeTwoOperands(MethodVisitor mv) { mv.visitInsn(POP2); mv.visitInsn(POP2); } private static final MethodCaller longArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "lArrayGet"), longArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "lArraySet"); protected MethodCaller getArrayGetCaller() { return longArrayGet; } protected MethodCaller getArraySetCaller() { return longArraySet; } private static final int[] bitOp = { LOR, // BITWISE_OR / PIPE 340 LAND, // BITWISE_AND 341 LXOR, // BIWISE_XOR 342 }; protected int getBitwiseOperationBytecode(int type) { return bitOp[type]; } protected int getCompareCode() { return LCMP; } protected ClassNode getNormalOpResultType() { return ClassHelper.long_TYPE; } private static final int[] shiftOp = { LSHL, // LEFT_SHIFT 280 LSHR, // RIGHT_SHIFT 281 LUSHR // RIGHT_SHIFT_UNSIGNED 282 }; protected int getShiftOperationBytecode(int type) { return shiftOp[type]; } private static final int[] stdOperations = { LADD, // PLUS 200 LSUB, // MINUS 201 LMUL, // MULTIPLY 202 0, // DIV, (203) but we don't want that one LDIV, // INTDIV 204 LREM, // MOD 203 }; protected int getStandardOperationBytecode(int type) { return stdOperations[type]; } protected void writeMinusMinus(MethodVisitor mv) { mv.visitInsn(LCONST_1); mv.visitInsn(LSUB); } protected void writePlusPlus(MethodVisitor mv) { mv.visitInsn(LCONST_1); mv.visitInsn(LADD); } protected ClassNode getDevisionOpResultType() { return ClassHelper.BigDecimal_TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BytecodeVariable.java0000644001501200150120000000624711707612046026456 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.objectweb.asm.Label; /** * Represents compile time variable metadata while compiling a method. * * @author James Strachan * @author Jochen Theodorou * @version $Revision$ */ public class BytecodeVariable { public static final BytecodeVariable THIS_VARIABLE = new BytecodeVariable(); public static final BytecodeVariable SUPER_VARIABLE = new BytecodeVariable(); private int index; private ClassNode type; private String name; private final int prevCurrent; private boolean holder; // br for setting on the LocalVariableTable in the class file // these fields should probably go to jvm Operand class private Label startLabel = null; private Label endLabel = null; private boolean dynamicTyped; private BytecodeVariable(){ dynamicTyped = true; index=0; holder=false; prevCurrent=0; } public BytecodeVariable(int index, ClassNode type, String name, int prevCurrent) { this.index = index; this.type = type; this.name = name; this.prevCurrent = prevCurrent; } public String getName() { return name; } public ClassNode getType() { return type; } /** * @return the stack index for this variable */ public int getIndex() { return index; } /** * @return is this local variable shared in other scopes (and so must use a ValueHolder) */ public boolean isHolder() { return holder; } public void setHolder(boolean holder) { this.holder = holder; } public Label getStartLabel() { return startLabel; } public void setStartLabel(Label startLabel) { this.startLabel = startLabel; } public Label getEndLabel() { return endLabel; } public void setEndLabel(Label endLabel) { this.endLabel = endLabel; } public String toString() { return name + "(index=" + index + ",type=" + type + ",holder="+holder+")"; } public void setType(ClassNode type) { this.type = type; dynamicTyped |= type==ClassHelper.DYNAMIC_TYPE; } public void setDynamicTyped(boolean b) { dynamicTyped = b; } public boolean isDynamicTyped() { return dynamicTyped; } public int getPrevIndex() { return prevCurrent; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryBooleanExpressionHelper.java0000644001501200150120000000622111715031256031203 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; /** * @author Jochen "blackdrag" Theodorou */ public class BinaryBooleanExpressionHelper extends BinaryIntExpressionHelper { public BinaryBooleanExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller boolArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "zArrayGet"), boolArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "zArraySet"); @Override protected MethodCaller getArrayGetCaller() { return boolArrayGet; } @Override protected MethodCaller getArraySetCaller() { return boolArraySet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.boolean_TYPE; } public boolean writePostOrPrefixMethod(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override protected boolean writeStdOperators(int type, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } protected boolean writeDivision(boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } protected int getBitwiseOperationBytecode(int type) { return -1; } protected ClassNode getNormalOpResultType() { return ClassHelper.boolean_TYPE; } protected ClassNode getDevisionOpResultType() { return ClassHelper.boolean_TYPE; } protected int getShiftOperationBytecode(int type) { return -1; } protected int getStandardOperationBytecode(int type) { return -1; } protected void removeTwoOperands(MethodVisitor mv) { throw new GroovyBugError("should not reach here"); } protected void writePlusPlus(MethodVisitor mv) { throw new GroovyBugError("should not reach here"); } protected void writeMinusMinus(MethodVisitor mv) { throw new GroovyBugError("should not reach here"); } protected void doubleTwoOperands(MethodVisitor mv) { throw new GroovyBugError("should not reach here"); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java0000644001501200150120000010560711715031256027713 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ElvisOperatorExpression; import org.codehaus.groovy.ast.expr.EmptyExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PostfixExpression; import org.codehaus.groovy.ast.expr.PrefixExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.TernaryExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.tools.WideningCategories; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.BytecodeExpression; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.codehaus.groovy.syntax.Types.*; import static org.objectweb.asm.Opcodes.*; public class BinaryExpressionHelper { //compare private static final MethodCaller compareEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareEqual"); private static final MethodCaller compareNotEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareNotEqual"); private static final MethodCaller compareToMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareTo"); private static final MethodCaller compareLessThanMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareLessThan"); private static final MethodCaller compareLessThanEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareLessThanEqual"); private static final MethodCaller compareGreaterThanMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareGreaterThan"); private static final MethodCaller compareGreaterThanEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareGreaterThanEqual"); //regexpr private static final MethodCaller findRegexMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "findRegex"); private static final MethodCaller matchRegexMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "matchRegex"); // isCase private static final MethodCaller isCaseMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "isCase"); private WriterController controller; public BinaryExpressionHelper(WriterController wc) { this.controller = wc; } public WriterController getController(){ return controller; } public void eval(BinaryExpression expression) { switch (expression.getOperation().getType()) { case EQUAL: // = assignment evaluateEqual(expression, false); break; case COMPARE_EQUAL: // == evaluateCompareExpression(compareEqualMethod, expression); break; case COMPARE_NOT_EQUAL: evaluateCompareExpression(compareNotEqualMethod, expression); break; case COMPARE_TO: evaluateCompareTo(expression); break; case COMPARE_GREATER_THAN: evaluateCompareExpression(compareGreaterThanMethod, expression); break; case COMPARE_GREATER_THAN_EQUAL: evaluateCompareExpression(compareGreaterThanEqualMethod, expression); break; case COMPARE_LESS_THAN: evaluateCompareExpression(compareLessThanMethod, expression); break; case COMPARE_LESS_THAN_EQUAL: evaluateCompareExpression(compareLessThanEqualMethod, expression); break; case LOGICAL_AND: evaluateLogicalAndExpression(expression); break; case LOGICAL_OR: evaluateLogicalOrExpression(expression); break; case BITWISE_AND: evaluateBinaryExpression("and", expression); break; case BITWISE_AND_EQUAL: evaluateBinaryExpressionWithAssignment("and", expression); break; case BITWISE_OR: evaluateBinaryExpression("or", expression); break; case BITWISE_OR_EQUAL: evaluateBinaryExpressionWithAssignment("or", expression); break; case BITWISE_XOR: evaluateBinaryExpression("xor", expression); break; case BITWISE_XOR_EQUAL: evaluateBinaryExpressionWithAssignment("xor", expression); break; case PLUS: evaluateBinaryExpression("plus", expression); break; case PLUS_EQUAL: evaluateBinaryExpressionWithAssignment("plus", expression); break; case MINUS: evaluateBinaryExpression("minus", expression); break; case MINUS_EQUAL: evaluateBinaryExpressionWithAssignment("minus", expression); break; case MULTIPLY: evaluateBinaryExpression("multiply", expression); break; case MULTIPLY_EQUAL: evaluateBinaryExpressionWithAssignment("multiply", expression); break; case DIVIDE: evaluateBinaryExpression("div", expression); break; case DIVIDE_EQUAL: //SPG don't use divide since BigInteger implements directly //and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result evaluateBinaryExpressionWithAssignment("div", expression); break; case INTDIV: evaluateBinaryExpression("intdiv", expression); break; case INTDIV_EQUAL: evaluateBinaryExpressionWithAssignment("intdiv", expression); break; case MOD: evaluateBinaryExpression("mod", expression); break; case MOD_EQUAL: evaluateBinaryExpressionWithAssignment("mod", expression); break; case POWER: evaluateBinaryExpression("power", expression); break; case POWER_EQUAL: evaluateBinaryExpressionWithAssignment("power", expression); break; case LEFT_SHIFT: evaluateBinaryExpression("leftShift", expression); break; case LEFT_SHIFT_EQUAL: evaluateBinaryExpressionWithAssignment("leftShift", expression); break; case RIGHT_SHIFT: evaluateBinaryExpression("rightShift", expression); break; case RIGHT_SHIFT_EQUAL: evaluateBinaryExpressionWithAssignment("rightShift", expression); break; case RIGHT_SHIFT_UNSIGNED: evaluateBinaryExpression("rightShiftUnsigned", expression); break; case RIGHT_SHIFT_UNSIGNED_EQUAL: evaluateBinaryExpressionWithAssignment("rightShiftUnsigned", expression); break; case KEYWORD_INSTANCEOF: evaluateInstanceof(expression); break; case FIND_REGEX: evaluateCompareExpression(findRegexMethod, expression); break; case MATCH_REGEX: evaluateCompareExpression(matchRegexMethod, expression); break; case LEFT_SQUARE_BRACKET: if (controller.getCompileStack().isLHS()) { evaluateEqual(expression, false); } else { evaluateBinaryExpression("getAt", expression); } break; case KEYWORD_IN: evaluateCompareExpression(isCaseMethod, expression); break; default: throw new GroovyBugError("Operation: " + expression.getOperation() + " not supported"); } } protected void assignToArray(Expression parrent, Expression receiver, Expression index, Expression rhsValueLoader) { // let's replace this assignment to a subscript operator with a // method call // e.g. x[5] = 10 // -> (x, [], 5), =, 10 // -> methodCall(x, "putAt", [5, 10]) ArgumentListExpression ae = new ArgumentListExpression(index,rhsValueLoader); controller.getCallSiteWriter().makeCallSite(receiver, "putAt", ae, false, false, false, false); controller.getOperandStack().pop(); // return value of assignment rhsValueLoader.visit(controller.getAcg()); } public void evaluateEqual(BinaryExpression expression, boolean defineVariable) { AsmClassGenerator acg = controller.getAcg(); CompileStack compileStack = controller.getCompileStack(); OperandStack operandStack = controller.getOperandStack(); Expression rightExpression = expression.getRightExpression(); Expression leftExpression = expression.getLeftExpression(); if ( defineVariable && rightExpression instanceof EmptyExpression && !(leftExpression instanceof TupleExpression) ) { VariableExpression ve = (VariableExpression) leftExpression; BytecodeVariable var = compileStack.defineVariable(ve, false); operandStack.loadOrStoreVariable(var, false); return; } // let's evaluate the RHS and store the result ClassNode rhsType; if (rightExpression instanceof EmptyExpression) { rhsType = leftExpression.getType(); loadInitValue(rhsType); } else { rightExpression.visit(acg); //rhsType = getCastType(rightExpression); rhsType = controller.getOperandStack().getTopOperand(); } boolean directAssignment = defineVariable && !(leftExpression instanceof TupleExpression); int rhsValueId; if (directAssignment) { VariableExpression var = (VariableExpression) leftExpression; rhsType = controller.getTypeChooser().resolveType(var, controller.getClassNode()); operandStack.doGroovyCast(rhsType); rhsValueId = compileStack.defineVariable(var, rhsType, true).getIndex(); } else { rhsValueId = compileStack.defineTemporaryVariable("$rhs", rhsType, true); } //TODO: if rhs is VariableSlotLoader already, then skip crating a new one BytecodeExpression rhsValueLoader = new VariableSlotLoader(rhsType,rhsValueId,operandStack); // assignment for subscript if (leftExpression instanceof BinaryExpression) { BinaryExpression leftBinExpr = (BinaryExpression) leftExpression; if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) { assignToArray(expression, leftBinExpr.getLeftExpression(), leftBinExpr.getRightExpression(), rhsValueLoader); } compileStack.removeVar(rhsValueId); return; } compileStack.pushLHS(true); // multiple declaration if (leftExpression instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) leftExpression; int i = 0; for (Expression e : tuple.getExpressions()) { VariableExpression var = (VariableExpression) e; MethodCallExpression call = new MethodCallExpression( rhsValueLoader, "getAt", new ArgumentListExpression(new ConstantExpression(i))); call.visit(acg); i++; if (defineVariable) { operandStack.doGroovyCast(var); compileStack.defineVariable(var, true); operandStack.remove(1); } else { acg.visitVariableExpression(var); } } } // single declaration else if (defineVariable) { rhsValueLoader.visit(acg); operandStack.remove(1); compileStack.popLHS(); return; } // normal assignment else { int mark = operandStack.getStackLength(); // to leave a copy of the rightExpression value on the stack after the assignment. rhsValueLoader.visit(acg); ClassNode type = controller.getTypeChooser().resolveType(leftExpression, controller.getClassNode()); operandStack.doGroovyCast(type); leftExpression.visit(acg); operandStack.remove(operandStack.getStackLength()-mark); } compileStack.popLHS(); // return value of assignment rhsValueLoader.visit(acg); compileStack.removeVar(rhsValueId); } private void loadInitValue(ClassNode type) { MethodVisitor mv = controller.getMethodVisitor(); if (ClassHelper.isPrimitiveType(type)) { mv.visitLdcInsn(0); } else { mv.visitInsn(ACONST_NULL); } controller.getOperandStack().push(type); } protected void evaluateCompareExpression(MethodCaller compareMethod, BinaryExpression expression) { Expression leftExp = expression.getLeftExpression(); Expression rightExp = expression.getRightExpression(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); leftExp.visit(acg); operandStack.box(); rightExp.visit(acg); operandStack.box(); compareMethod.call(controller.getMethodVisitor()); ClassNode resType = ClassHelper.boolean_TYPE; if (compareMethod==findRegexMethod) { resType = ClassHelper.OBJECT_TYPE; } operandStack.replace(resType,2); } private void evaluateCompareTo(BinaryExpression expression) { Expression leftExpression = expression.getLeftExpression(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); leftExpression.visit(acg); operandStack.box(); // if the right hand side is a boolean expression, we need to autobox Expression rightExpression = expression.getRightExpression(); rightExpression.visit(acg); operandStack.box(); compareToMethod.call(controller.getMethodVisitor()); operandStack.replace(ClassHelper.Integer_TYPE,2); } private void evaluateLogicalAndExpression(BinaryExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); expression.getLeftExpression().visit(acg); operandStack.doGroovyCast(ClassHelper.boolean_TYPE); Label falseCase = operandStack.jump(IFEQ); expression.getRightExpression().visit(acg); operandStack.doGroovyCast(ClassHelper.boolean_TYPE); operandStack.jump(IFEQ,falseCase); ConstantExpression.PRIM_TRUE.visit(acg); Label trueCase = new Label(); mv.visitJumpInsn(GOTO, trueCase); mv.visitLabel(falseCase); ConstantExpression.PRIM_FALSE.visit(acg); mv.visitLabel(trueCase); operandStack.remove(1); // have to remove 1 because of the GOTO } private void evaluateLogicalOrExpression(BinaryExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); Label end = new Label(); expression.getLeftExpression().visit(acg); operandStack.doGroovyCast(ClassHelper.boolean_TYPE); Label trueCase = operandStack.jump(IFNE); expression.getRightExpression().visit(acg); operandStack.doGroovyCast(ClassHelper.boolean_TYPE); Label falseCase = operandStack.jump(IFEQ); mv.visitLabel(trueCase); ConstantExpression.PRIM_TRUE.visit(acg); operandStack.jump(GOTO, end); mv.visitLabel(falseCase); ConstantExpression.PRIM_FALSE.visit(acg); mv.visitLabel(end); } protected void evaluateBinaryExpression(String message, BinaryExpression binExp) { CompileStack compileStack = controller.getCompileStack(); Expression receiver = binExp.getLeftExpression(); Expression arguments = binExp.getRightExpression(); // ensure VariableArguments are read, not stored compileStack.pushLHS(false); controller.getCallSiteWriter().makeInvocation(receiver, message, arguments); compileStack.popLHS(); } protected void evaluateBinaryExpressionWithAssignment(String method, BinaryExpression expression) { Expression leftExpression = expression.getLeftExpression(); MethodVisitor mv = controller.getMethodVisitor(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); CompileStack compileStack = controller.getCompileStack(); if (leftExpression instanceof BinaryExpression) { BinaryExpression leftBinExpr = (BinaryExpression) leftExpression; if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) { // e.g. x[a] += b // -> subscript=a, x[subscript], =, x[subscript] + b // -> subscript=a, methodCall_3(x, "putAt", [subscript, methodCall_2(methodCall_1(x, "getAt", [subscript]), "plus", b)]) Expression subscriptExpression = leftBinExpr.getRightExpression(); subscriptExpression.visit(acg); // value(subscript) operandStack.box(); int subscriptValueId = compileStack.defineTemporaryVariable("$subscript", ClassHelper.OBJECT_TYPE, true); // method calls from outer to inner (most inner will be called first): controller.getCallSiteWriter().prepareCallSite("putAt"); controller.getCallSiteWriter().prepareCallSite(method); controller.getCallSiteWriter().prepareCallSite("getAt"); // getAt call //x = receiver leftBinExpr.getLeftExpression().visit(acg); operandStack.box(); // we save that value for later operandStack.dup(); int xValueId = compileStack.defineTemporaryVariable("$xValue", ClassHelper.OBJECT_TYPE, true); // subscript = argument to getAt call operandStack.load(ClassHelper.OBJECT_TYPE, subscriptValueId); // invoke getAt mv.visitMethodInsn(INVOKEINTERFACE, "org/codehaus/groovy/runtime/callsite/CallSite", "call","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); operandStack.replace(ClassHelper.OBJECT_TYPE, 2); //x[subscript] with type Object now on stack // call with method (e.g. "plus") // receiver is the result from the getAt before // load b expression.getRightExpression().visit(acg); operandStack.box(); // invoke "method" mv.visitMethodInsn(INVOKEINTERFACE, "org/codehaus/groovy/runtime/callsite/CallSite", "call","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); operandStack.replace(ClassHelper.OBJECT_TYPE, 2); //RHS with type Object now on stack // let us save that value for the return int resultValueId = compileStack.defineTemporaryVariable("$result", ClassHelper.OBJECT_TYPE, true); // call for putAt // receiver for putAt is x, the arguments will be the subscript // value and the value of the RHS. // load receiver x operandStack.load(ClassHelper.OBJECT_TYPE, xValueId); operandStack.load(ClassHelper.OBJECT_TYPE, subscriptValueId); operandStack.load(ClassHelper.OBJECT_TYPE, resultValueId); // invoke putAt mv.visitMethodInsn(INVOKEINTERFACE, "org/codehaus/groovy/runtime/callsite/CallSite", "call","(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); operandStack.replace(ClassHelper.OBJECT_TYPE, 3); // remove result of putAt and keep the result on stack operandStack.pop(); operandStack.load(ClassHelper.OBJECT_TYPE, resultValueId); compileStack.removeVar(resultValueId); compileStack.removeVar(xValueId); compileStack.removeVar(subscriptValueId); return; } } evaluateBinaryExpression(method, expression); // br to leave a copy of rvalue on the stack. see also isPopRequired() operandStack.dup(); controller.getCompileStack().pushLHS(true); leftExpression.visit(acg); controller.getCompileStack().popLHS(); } private void evaluateInstanceof(BinaryExpression expression) { OperandStack operandStack = controller.getOperandStack(); expression.getLeftExpression().visit(controller.getAcg()); operandStack.box(); Expression rightExp = expression.getRightExpression(); ClassNode classType; if (rightExp instanceof ClassExpression) { ClassExpression classExp = (ClassExpression) rightExp; classType = classExp.getType(); } else { throw new RuntimeException( "Right hand side of the instanceof keyword must be a class name, not: " + rightExp); } String classInternalName = BytecodeHelper.getClassInternalName(classType); controller.getMethodVisitor().visitTypeInsn(INSTANCEOF, classInternalName); operandStack.replace(ClassHelper.boolean_TYPE); } public MethodCaller getIsCaseMethod() { return isCaseMethod; } private void evaluatePostfixMethod(int op, String method, Expression expression, Expression orig) { CompileStack compileStack = controller.getCompileStack(); final OperandStack operandStack = controller.getOperandStack(); // load Expressions VariableSlotLoader usesSubscript = loadWithSubscript(expression); // save copy for later operandStack.dup(); ClassNode expressionType = operandStack.getTopOperand(); int tempIdx = compileStack.defineTemporaryVariable("postfix_" + method, expressionType, true); // execute Method execMethodAndStoreForSubscriptOperator(op,method,expression,usesSubscript,orig); // remove the result of the method call operandStack.pop(); //reload saved value operandStack.load(expressionType, tempIdx); compileStack.removeVar(tempIdx); if (usesSubscript!=null) compileStack.removeVar(usesSubscript.getIndex()); } public void evaluatePostfixMethod(PostfixExpression expression) { int op = expression.getOperation().getType(); switch (op) { case Types.PLUS_PLUS: evaluatePostfixMethod(op, "next", expression.getExpression(), expression); break; case Types.MINUS_MINUS: evaluatePostfixMethod(op, "previous", expression.getExpression(), expression); break; } } public void evaluatePrefixMethod(PrefixExpression expression) { int type = expression.getOperation().getType(); switch (type) { case Types.PLUS_PLUS: evaluatePrefixMethod(type, "next", expression.getExpression(), expression); break; case Types.MINUS_MINUS: evaluatePrefixMethod(type, "previous", expression.getExpression(), expression); break; } } private void evaluatePrefixMethod(int op, String method, Expression expression, Expression orig) { // load Expressions VariableSlotLoader usesSubscript = loadWithSubscript(expression); // execute Method execMethodAndStoreForSubscriptOperator(op,method,expression,usesSubscript,orig); // new value is already on stack, so nothing to do here if (usesSubscript!=null) controller.getCompileStack().removeVar(usesSubscript.getIndex()); } private VariableSlotLoader loadWithSubscript(Expression expression) { final OperandStack operandStack = controller.getOperandStack(); // if we have a BinaryExpression, let us check if it is with // subscription if (expression instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) expression; if (be.getOperation().getType()==Types.LEFT_SQUARE_BRACKET) { // right expression is the subscript expression // we store the result of the subscription on the stack Expression subscript = be.getRightExpression(); subscript.visit(controller.getAcg()); operandStack.box(); //TODO: maybe not box here anymore, but need subscript type then int id = controller.getCompileStack().defineTemporaryVariable("$subscript", true); VariableSlotLoader subscriptExpression = new VariableSlotLoader(id,operandStack); // do modified visit BinaryExpression newBe = new BinaryExpression(be.getLeftExpression(), be.getOperation(), subscriptExpression); newBe.setSourcePosition(be); newBe.visit(controller.getAcg()); return subscriptExpression; } } // normal loading of expression expression.visit(controller.getAcg()); return null; } private void execMethodAndStoreForSubscriptOperator(int op, String method, Expression expression, VariableSlotLoader usesSubscript, Expression orig) { final OperandStack operandStack = controller.getOperandStack(); writePostOrPrefixMethod(op,method,expression,orig); // we need special code for arrays to store the result (like for a[1]++) if (usesSubscript!=null) { CompileStack compileStack = controller.getCompileStack(); BinaryExpression be = (BinaryExpression) expression; ClassNode methodResultType = operandStack.getTopOperand(); final int resultIdx = compileStack.defineTemporaryVariable("postfix_" + method, methodResultType, true); BytecodeExpression methodResultLoader = new VariableSlotLoader(methodResultType, resultIdx, operandStack); // execute the assignment, this will leave the right side // (here the method call result) on the stack assignToArray(be, be.getLeftExpression(), usesSubscript, methodResultLoader); compileStack.removeVar(resultIdx); } // here we handle a.b++ and a++ else if (expression instanceof VariableExpression || expression instanceof FieldExpression || expression instanceof PropertyExpression) { operandStack.dup(); controller.getCompileStack().pushLHS(true); expression.visit(controller.getAcg()); controller.getCompileStack().popLHS(); } // other cases don't need storing, so nothing to be done for them } protected void writePostOrPrefixMethod(int op, String method, Expression expression, Expression orig) { final OperandStack operandStack = controller.getOperandStack(); // at this point the receiver will be already on the stack. // in a[1]++ the method will be "++" aka "next" and the receiver a[1] ClassNode BEType = controller.getTypeChooser().resolveType(expression, controller.getClassNode()); Expression callSiteReceiverSwap = new BytecodeExpression(BEType) { @Override public void visit(MethodVisitor mv) { // CallSite is normally not showing up on the // operandStack, so we place a dummy here with same // slot length. operandStack.push(ClassHelper.OBJECT_TYPE); // change (receiver,callsite) to (callsite,receiver) operandStack.swap(); setType(operandStack.getTopOperand()); // no need to keep any of those on the operand stack // after this expression is processed, the operand stack // will contain callSiteReceiverSwap.getType() operandStack.remove(2); } }; // execute method // this will load the callsite and the receiver normally in the wrong // order since the receiver is already present, but before the callsite // Therefore we use callSiteReceiverSwap to correct the order. // After this call the JVM operand stack will contain the the result of // the method call... usually simply Object in operandStack controller.getCallSiteWriter().makeCallSite( callSiteReceiverSwap, method, MethodCallExpression.NO_ARGUMENTS, false, false, false, false); // now rhs is completely done and we need only to store. In a[1]++ this // would be a.getAt(1).next() for the rhs, "lhs" code is a.putAt(1, rhs) } private void evaluateElvisOperatorExpression(ElvisOperatorExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); CompileStack compileStack = controller.getCompileStack(); OperandStack operandStack = controller.getOperandStack(); TypeChooser typeChooser = controller.getTypeChooser(); Expression boolPart = expression.getBooleanExpression().getExpression(); Expression falsePart = expression.getFalseExpression(); ClassNode truePartType = typeChooser.resolveType(boolPart, controller.getClassNode()); ClassNode falsePartType = typeChooser.resolveType(falsePart, controller.getClassNode()); ClassNode common = WideningCategories.firstCommonSuperType(truePartType, falsePartType); // x?:y is equal to x?x:y, which evals to // var t=x; boolean(t)?t:y // first we load x, dup it, convert the dupped to boolean, then // jump depending on the value. For true we are done, for false we // have to load y, thus we first remove x and then load y. // But since x and y may have different stack lengths, this cannot work // Thus we have to have to do the following: // Be X the type of x, Y the type of y and S the common supertype of // X and Y, then we have to see x?:y as // var t=x;boolean(t)?S(t):S(y) // so we load x, dup it, store the value in a local variable (t), then // do boolean conversion. In the true part load t and cast it to S, // in the false part load y and cast y to S // load x, dup it, store one in $t and cast the remaining one to boolean int mark = operandStack.getStackLength(); boolPart.visit(controller.getAcg()); operandStack.dup(); int retValueId = compileStack.defineTemporaryVariable("$t", truePartType, true); operandStack.castToBool(mark,true); Label l0 = operandStack.jump(IFEQ); // true part: load $t and cast to S operandStack.load(truePartType, retValueId); operandStack.doGroovyCast(common); Label l1 = new Label(); mv.visitJumpInsn(GOTO, l1); // false part: load false expression and cast to S mv.visitLabel(l0); falsePart.visit(controller.getAcg()); operandStack.doGroovyCast(common); // finish and cleanup mv.visitLabel(l1); compileStack.removeVar(retValueId); controller.getOperandStack().replace(common, 2); } private void evaluateNormalTernary(TernaryExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); TypeChooser typeChooser = controller.getTypeChooser(); Expression boolPart = expression.getBooleanExpression(); Expression truePart = expression.getTrueExpression(); Expression falsePart = expression.getFalseExpression(); ClassNode truePartType = typeChooser.resolveType(truePart, controller.getClassNode()); ClassNode falsePartType = typeChooser.resolveType(falsePart, controller.getClassNode()); ClassNode common = WideningCategories.firstCommonSuperType(truePartType, falsePartType); // we compile b?x:y as // boolean(b)?S(x):S(y), S = common super type of x,y // so we load b, do boolean conversion. // In the true part load x and cast it to S, // in the false part load y and cast y to S // load b and convert to boolean int mark = operandStack.getStackLength(); boolPart.visit(controller.getAcg()); operandStack.castToBool(mark,true); Label l0 = operandStack.jump(IFEQ); // true part: load x and cast to S truePart.visit(controller.getAcg()); operandStack.doGroovyCast(common); Label l1 = new Label(); mv.visitJumpInsn(GOTO, l1); // false part: load y and cast to S mv.visitLabel(l0); falsePart.visit(controller.getAcg()); operandStack.doGroovyCast(common); // finish and cleanup mv.visitLabel(l1); controller.getOperandStack().replace(common, 2); } public void evaluateTernary(TernaryExpression expression) { if (expression instanceof ElvisOperatorExpression) { evaluateElvisOperatorExpression((ElvisOperatorExpression) expression); } else { evaluateNormalTernary(expression); } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/MethodCallerMultiAdapter.java0000644001501200150120000000705611707612046030130 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.objectweb.asm.MethodVisitor; public class MethodCallerMultiAdapter { private MethodCaller[] methods; boolean skipSpreadSafeAndSafe; public static final int MAX_ARGS = 0; public static MethodCallerMultiAdapter newStatic(Class theClass, String baseName, boolean createNArgs, boolean skipSpreadSafeAndSafe) { MethodCallerMultiAdapter mcma = new MethodCallerMultiAdapter(); mcma.skipSpreadSafeAndSafe = skipSpreadSafeAndSafe; if (createNArgs) { int numberOfBaseMethods = mcma.numberOfBaseMethods(); mcma.methods = new MethodCaller[(MAX_ARGS + 2) * numberOfBaseMethods]; for (int i = 0; i <= MAX_ARGS; i++) { mcma.methods[i * numberOfBaseMethods] = MethodCaller.newStatic(theClass, baseName + i); if (skipSpreadSafeAndSafe) continue; mcma.methods[i * numberOfBaseMethods + 1] = MethodCaller.newStatic(theClass, baseName + i + "Safe"); mcma.methods[i * numberOfBaseMethods + 2] = MethodCaller.newStatic(theClass, baseName + i + "SpreadSafe"); } mcma.methods[(MAX_ARGS + 1) * numberOfBaseMethods] = MethodCaller.newStatic(theClass, baseName + "N"); if (!skipSpreadSafeAndSafe) { mcma.methods[(MAX_ARGS + 1) * numberOfBaseMethods + 1] = MethodCaller.newStatic(theClass, baseName + "N" + "Safe"); mcma.methods[(MAX_ARGS + 1) * numberOfBaseMethods + 2] = MethodCaller.newStatic(theClass, baseName + "N" + "SpreadSafe"); } } else if (!skipSpreadSafeAndSafe) { mcma.methods = new MethodCaller[]{ MethodCaller.newStatic(theClass, baseName), MethodCaller.newStatic(theClass, baseName + "Safe"), MethodCaller.newStatic(theClass, baseName + "SpreadSafe") }; } else { mcma.methods = new MethodCaller[]{ MethodCaller.newStatic(theClass, baseName) }; } return mcma; } /** * @param methodVisitor * @param numberOfArguments a value >0 describing how many arguments are additionally used for the method call * @param safe * @param spreadSafe */ public void call(MethodVisitor methodVisitor, int numberOfArguments, boolean safe, boolean spreadSafe) { int offset = 0; if (safe && !skipSpreadSafeAndSafe) offset = 1; if (spreadSafe && !skipSpreadSafeAndSafe) offset = 2; if (numberOfArguments > MAX_ARGS || numberOfArguments < 0) { offset += (MAX_ARGS + 1) * numberOfBaseMethods(); } else { offset += numberOfArguments * numberOfBaseMethods(); } methods[offset].call(methodVisitor); } private int numberOfBaseMethods() { if (skipSpreadSafeAndSafe) return 1; return 3; } }groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/WriterController.java0000644001501200150120000002233711715031256026565 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.Map; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.InterfaceHelperClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; public class WriterController { private AsmClassGenerator acg; private MethodVisitor methodVisitor; private CompileStack compileStack; private OperandStack operandStack; private ClassNode classNode; private CallSiteWriter callSiteWriter; private ClassVisitor cv; private ClosureWriter closureWriter; private String internalClassName; private InvocationWriter invocationWriter; private BinaryExpressionHelper binaryExpHelper, fastPathBinaryExpHelper; private AssertionWriter assertionWriter; private String internalBaseClassName; private ClassNode outermostClass; private MethodNode methodNode; private SourceUnit sourceUnit; private ConstructorNode constructorNode; private GeneratorContext context; private InterfaceHelperClassNode interfaceClassLoadingClass; public boolean optimizeForInt = true; private StatementWriter statementWriter; private boolean fastPath = false; private TypeChooser typeChooser; public void init(AsmClassGenerator asmClassGenerator, GeneratorContext gcon, ClassVisitor cv, ClassNode cn) { Map optOptions = cn.getCompileUnit().getConfig().getOptimizationOptions(); if (optOptions.isEmpty()) { // IGNORE } else if (optOptions.get("all")==Boolean.FALSE) { optimizeForInt=false; // set other optimizations options to false here } else { if (optOptions.get("int")==Boolean.FALSE) optimizeForInt=false; // set other optimizations options to false here } this.classNode = cn; this.outermostClass = null; this.internalClassName = BytecodeHelper.getClassInternalName(classNode); this.callSiteWriter = new CallSiteWriter(this); this.invocationWriter = new InvocationWriter(this); this.binaryExpHelper = new BinaryExpressionHelper(this); if (optimizeForInt) { this.fastPathBinaryExpHelper = new BinaryExpressionMultiTypeDispatcher(this); } else { this.fastPathBinaryExpHelper = this.binaryExpHelper; } this.operandStack = new OperandStack(this); this.assertionWriter = new AssertionWriter(this); this.closureWriter = new ClosureWriter(this); this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass()); this.acg = asmClassGenerator; this.sourceUnit = acg.getSourceUnit(); this.context = gcon; this.compileStack = new CompileStack(this); this.cv = cv; if (optimizeForInt) { this.statementWriter = new OptimizingStatementWriter(this); } else { this.statementWriter = new StatementWriter(this); } this.typeChooser = new StatementMetaTypeChooser(); } public AsmClassGenerator getAcg() { return acg; } public void setMethodVisitor(MethodVisitor methodVisitor) { this.methodVisitor = methodVisitor; } public MethodVisitor getMethodVisitor() { return methodVisitor; } public CompileStack getCompileStack() { return compileStack; } public OperandStack getOperandStack() { return operandStack; } public ClassNode getClassNode() { return classNode; } public CallSiteWriter getCallSiteWriter() { return callSiteWriter; } public ClassVisitor getClassVisitor() { return cv; } public ClosureWriter getClosureWriter() { return closureWriter; } public ClassVisitor getCv() { return cv; } public String getInternalClassName() { return internalClassName; } public InvocationWriter getInvocationWriter() { return invocationWriter; } public BinaryExpressionHelper getBinaryExpHelper() { if (fastPath) { return fastPathBinaryExpHelper; } else { return binaryExpHelper; } } public AssertionWriter getAssertionWriter() { return assertionWriter; } public TypeChooser getTypeChooser() { return typeChooser; } public String getInternalBaseClassName() { return internalBaseClassName; } public MethodNode getMethodNode() { return methodNode; } public void setMethodNode(MethodNode mn) { methodNode = mn; constructorNode = null; } public ConstructorNode getConstructorNode(){ return constructorNode; } public void setConstructorNode(ConstructorNode cn) { constructorNode = cn; methodNode = null; } public boolean isNotClinit() { return methodNode == null || !methodNode.getName().equals(""); } public SourceUnit getSourceUnit() { return sourceUnit; } public boolean isStaticContext() { if (compileStack!=null && compileStack.getScope()!=null) { return compileStack.getScope().isInStaticContext(); } if (!isInClosure()) return false; if (constructorNode != null) return false; return classNode.isStaticClass() || methodNode.isStatic(); } public boolean isInClosure() { return classNode.getOuterClass() != null && classNode.getSuperClass() == ClassHelper.CLOSURE_TYPE; } public boolean isInClosureConstructor() { return constructorNode != null && classNode.getOuterClass() != null && classNode.getSuperClass() == ClassHelper.CLOSURE_TYPE; } public boolean isNotExplicitThisInClosure(boolean implicitThis) { return implicitThis || !isInClosure(); } public boolean isStaticMethod() { return methodNode != null && methodNode.isStatic(); } public ClassNode getReturnType() { if (methodNode != null) { return methodNode.getReturnType(); } else if (constructorNode != null) { return constructorNode.getReturnType(); } else { throw new GroovyBugError("I spotted a return that is neither in a method nor in a constructor... I can not handle that"); } } public boolean isStaticConstructor() { return methodNode != null && methodNode.getName().equals(""); } public boolean isConstructor() { return constructorNode!=null; } /** * @return true if we are in a script body, where all variables declared are no longer * local variables but are properties */ public boolean isInScriptBody() { if (classNode.isScriptBody()) { return true; } else { return classNode.isScript() && methodNode != null && methodNode.getName().equals("run"); } } public String getClassName() { String className; if (!classNode.isInterface() || interfaceClassLoadingClass == null) { className = internalClassName; } else { className = BytecodeHelper.getClassInternalName(interfaceClassLoadingClass); } return className; } public ClassNode getOutermostClass() { if (outermostClass == null) { outermostClass = classNode; while (outermostClass instanceof InnerClassNode) { outermostClass = outermostClass.getOuterClass(); } } return outermostClass; } public GeneratorContext getContext() { return context; } public void setInterfaceClassLoadingClass(InterfaceHelperClassNode ihc) { interfaceClassLoadingClass = ihc; } public InterfaceHelperClassNode getInterfaceClassLoadingClass() { return interfaceClassLoadingClass; } public boolean shouldOptimizeForInt() { return optimizeForInt; } public StatementWriter getStatementWriter() { return statementWriter; } public void switchToFastPath() { fastPath = true; } public void switchToSlowPath() { fastPath = false; } public boolean isFastPath() { return fastPath; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/CompileStack.java0000644001501200150120000007263711713765676025655 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.VariableScope; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.*; /** * This class is a helper for AsmClassGenerator. It manages * different aspects of the code of a code block like * handling labels, defining variables, and scopes. * After a MethodNode is visited clear should be called, for * initialization the method init should be used. *

      * Some Notes: *

        *
      • every push method will require a later pop call *
      • method parameters may define a category 2 variable, so * don't ignore the type stored in the variable object *
      • the index of the variable may not be as assumed when * the variable is a parameter of a method because the * parameter may be used in a closure, so don't ignore * the stored variable index *
      • the names of temporary variables can be ignored. The names * are only used for debugging and do not conflict with each * other or normal variables. For accessing, the index of the * variable must be used. *
      • never mix temporary and normal variables by changes to this class. * While the name is very important for a normal variable, it is only a * helper construct for temporary variables. That means for example a * name for a temporary variable can be used multiple times without * conflict. So mixing them both may lead to the problem that a normal * or temporary variable is hidden or even removed. That must not happen! *
      * * * @see org.codehaus.groovy.classgen.AsmClassGenerator * @author Jochen Theodorou */ public class CompileStack implements Opcodes { /** * @todo remove optimization of this.foo -> this.@foo * */ // state flag private boolean clear=true; // current scope private VariableScope scope; // current label for continue private Label continueLabel; // current label for break private Label breakLabel; // available variables on stack private Map stackVariables = new HashMap(); // index of the last variable on stack private int currentVariableIndex = 1; // index for the next variable on stack private int nextVariableIndex = 1; // currently temporary variables in use private final LinkedList temporaryVariables = new LinkedList(); // overall used variables for a method/constructor private final LinkedList usedVariables = new LinkedList(); // map containing named labels of parenting blocks private Map superBlockNamedLabels = new HashMap(); // map containing named labels of current block private Map currentBlockNamedLabels = new HashMap(); // list containing finally blocks // such a block is created by synchronized or finally and // must be called for break/continue/return private LinkedList finallyBlocks = new LinkedList(); private LinkedList visitedBlocks = new LinkedList(); private Label thisStartLabel, thisEndLabel; // private MethodVisitor mv; // helper to handle different stack based variables private final LinkedList stateStack = new LinkedList(); // handle different states for the implicit "this" private LinkedList implicitThisStack = new LinkedList(); // handle different states for being on the left hand side private LinkedList lhsStack = new LinkedList(); { implicitThisStack.add(false); lhsStack.add(false); } // defines the first variable index usable after // all parameters of a method private int localVariableOffset; // this is used to store the goals for a "break foo" call // in a loop where foo is a label. private final Map namedLoopBreakLabel = new HashMap(); // this is used to store the goals for a "continue foo" call // in a loop where foo is a label. private final Map namedLoopContinueLabel = new HashMap(); private String className; private LinkedList typedExceptions = new LinkedList(); private LinkedList untypedExceptions = new LinkedList(); // stores if on left-hand-side during compilation private boolean lhs; // stores if implicit or explicit this is used. private boolean implicitThis; private WriterController controller; private boolean inSpecialConstructallCall; protected static class LabelRange { public Label start; public Label end; } public static class BlockRecorder { private boolean isEmpty = true; public Runnable excludedStatement; public LinkedList ranges; public BlockRecorder() { ranges = new LinkedList(); } public BlockRecorder(Runnable excludedStatement) { this(); this.excludedStatement = excludedStatement; } public void startRange(Label start) { LabelRange range = new LabelRange(); range.start = start; ranges.add(range); isEmpty = false; } public void closeRange(Label end) { ranges.getLast().end = end; } } private class ExceptionTableEntry { Label start,end,goal; String sig; } private class StateStackElement { final VariableScope scope; final Label continueLabel; final Label breakLabel; final Map stackVariables; final Map currentBlockNamedLabels; final LinkedList finallyBlocks; final boolean inSpecialConstructallCall; StateStackElement() { scope = CompileStack.this.scope; continueLabel = CompileStack.this.continueLabel; breakLabel = CompileStack.this.breakLabel; stackVariables = CompileStack.this.stackVariables; currentBlockNamedLabels = CompileStack.this.currentBlockNamedLabels; finallyBlocks = CompileStack.this.finallyBlocks; inSpecialConstructallCall = CompileStack.this.inSpecialConstructallCall; } } public CompileStack(WriterController wc) { this.controller = wc; } public void pushState() { stateStack.add(new StateStackElement()); stackVariables = new HashMap(stackVariables); finallyBlocks = new LinkedList(finallyBlocks); } private void popState() { if (stateStack.size()==0) { throw new GroovyBugError("Tried to do a pop on the compile stack without push."); } StateStackElement element = (StateStackElement) stateStack.removeLast(); scope = element.scope; continueLabel = element.continueLabel; breakLabel = element.breakLabel; stackVariables = element.stackVariables; finallyBlocks = element.finallyBlocks; inSpecialConstructallCall = element.inSpecialConstructallCall; } public Label getContinueLabel() { return continueLabel; } public Label getBreakLabel() { return breakLabel; } public void removeVar(int tempIndex) { final BytecodeVariable head = (BytecodeVariable) temporaryVariables.removeFirst(); if (head.getIndex() != tempIndex) { temporaryVariables.addFirst(head); throw new GroovyBugError( "CompileStack#removeVar: tried to remove a temporary " + "variable with index "+ tempIndex + " in wrong order. " + "Current temporary variables=" + temporaryVariables); } } private void setEndLabels(){ Label endLabel = new Label(); controller.getMethodVisitor().visitLabel(endLabel); for (Iterator iter = stackVariables.values().iterator(); iter.hasNext();) { BytecodeVariable var = (BytecodeVariable) iter.next(); var.setEndLabel(endLabel); } thisEndLabel = endLabel; } public void pop() { setEndLabels(); popState(); } public VariableScope getScope() { return scope; } /** * creates a temporary variable. * * @param var defines type and name * @param store defines if the toplevel argument of the stack should be stored * @return the index used for this temporary variable */ public int defineTemporaryVariable(org.codehaus.groovy.ast.Variable var, boolean store) { return defineTemporaryVariable(var.getName(), var.getType(),store); } public BytecodeVariable getVariable(String variableName ) { return getVariable(variableName,true); } /** * Returns a normal variable. *

      * If mustExist is true and the normal variable doesn't exist, * then this method will throw a GroovyBugError. It is not the intention of * this method to let this happen! And the exception should not be used for * flow control - it is just acting as an assertion. If the exception is thrown * then it indicates a bug in the class using CompileStack. * This method can also not be used to return a temporary variable. * Temporary variables are not normal variables. * * @param variableName name of the variable * @param mustExist throw exception if variable does not exist * @return the normal variable or null if not found (and mustExist not true) */ public BytecodeVariable getVariable(String variableName, boolean mustExist) { if (variableName.equals("this")) return BytecodeVariable.THIS_VARIABLE; if (variableName.equals("super")) return BytecodeVariable.SUPER_VARIABLE; BytecodeVariable v = (BytecodeVariable) stackVariables.get(variableName); if (v == null && mustExist) throw new GroovyBugError("tried to get a variable with the name " + variableName + " as stack variable, but a variable with this name was not created"); return v; } /** * creates a temporary variable. * * @param name defines type and name * @param store defines if the toplevel argument of the stack should be stored * @return the index used for this temporary variable */ public int defineTemporaryVariable(String name,boolean store) { return defineTemporaryVariable(name, ClassHelper.DYNAMIC_TYPE,store); } /** * creates a temporary variable. * * @param name defines the name * @param node defines the node * @param store defines if the toplevel argument of the stack should be stored * @return the index used for this temporary variable */ public int defineTemporaryVariable(String name, ClassNode node, boolean store) { BytecodeVariable answer = defineVar(name, node, false, false); temporaryVariables.addFirst(answer); // TRICK: we add at the beginning so when we find for remove or get we always have the last one usedVariables.removeLast(); if (store) controller.getOperandStack().storeVar(answer); return answer.getIndex(); } private void resetVariableIndex(boolean isStatic) { temporaryVariables.clear(); if (!isStatic) { currentVariableIndex=1; nextVariableIndex=1; } else { currentVariableIndex=0; nextVariableIndex=0; } } /** * Clears the state of the class. This method should be called * after a MethodNode is visited. Note that a call to init will * fail if clear is not called before */ public void clear() { if (stateStack.size()>1) { int size = stateStack.size()-1; throw new GroovyBugError("the compile stack contains "+size+" more push instruction"+(size==1?"":"s")+" than pops."); } if (lhsStack.size()>1) { int size = lhsStack.size()-1; throw new GroovyBugError("lhs stack is supposed to be empty, but has " + size + " elements left."); } if (implicitThisStack.size()>1) { int size = implicitThisStack.size()-1; throw new GroovyBugError("implicit 'this' stack is supposed to be empty, but has " + size + " elements left."); } clear = true; MethodVisitor mv = controller.getMethodVisitor(); // br experiment with local var table so debuggers can retrieve variable names if (true) {//AsmClassGenerator.CREATE_DEBUG_INFO) { if (thisEndLabel==null) setEndLabels(); if (!scope.isInStaticContext()) { // write "this" mv.visitLocalVariable("this", className, null, thisStartLabel, thisEndLabel, 0); } for (Iterator iterator = usedVariables.iterator(); iterator.hasNext();) { BytecodeVariable v = (BytecodeVariable) iterator.next(); ClassNode t = v.getType(); if (v.isHolder()) t = ClassHelper.REFERENCE_TYPE; String type = BytecodeHelper.getTypeDescription(t); Label start = v.getStartLabel(); Label end = v.getEndLabel(); mv.visitLocalVariable(v.getName(), type, null, start, end, v.getIndex()); } } //exception table writing for (ExceptionTableEntry ep : typedExceptions) { mv.visitTryCatchBlock(ep.start, ep.end, ep.goal, ep.sig); } //exception table writing for (ExceptionTableEntry ep : untypedExceptions) { mv.visitTryCatchBlock(ep.start, ep.end, ep.goal, ep.sig); } pop(); typedExceptions.clear(); untypedExceptions.clear(); stackVariables.clear(); usedVariables.clear(); scope = null; finallyBlocks.clear(); mv=null; resetVariableIndex(false); superBlockNamedLabels.clear(); currentBlockNamedLabels.clear(); namedLoopBreakLabel.clear(); namedLoopContinueLabel.clear(); continueLabel=null; breakLabel=null; thisStartLabel=null; thisEndLabel=null; mv = null; } public void addExceptionBlock (Label start, Label end, Label goal, String sig) { // this code is in an extra method to avoid // lazy initialization issues ExceptionTableEntry ep = new ExceptionTableEntry(); ep.start = start; ep.end = end; ep.sig = sig; ep.goal = goal; if (sig==null) { untypedExceptions.add(ep); } else { typedExceptions.add(ep); } } /** * initializes this class for a MethodNode. This method will * automatically define variables for the method parameters * and will create references if needed. The created variables * can be accessed by calling getVariable(). * */ public void init(VariableScope el, Parameter[] parameters) { if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before"); clear=false; pushVariableScope(el); defineMethodVariables(parameters,el.isInStaticContext()); this.className = BytecodeHelper.getTypeDescription(controller.getClassNode()); } /** * Causes the statestack to add an element and sets * the given scope as new current variable scope. Creates * a element for the state stack so pop has to be called later */ public void pushVariableScope(VariableScope el) { pushState(); scope = el; superBlockNamedLabels = new HashMap(superBlockNamedLabels); superBlockNamedLabels.putAll(currentBlockNamedLabels); currentBlockNamedLabels = new HashMap(); } /** * Should be called when decending into a loop that defines * also a scope. Calls pushVariableScope and prepares labels * for a loop structure. Creates a element for the state stack * so pop has to be called later */ public void pushLoop(VariableScope el, String labelName) { pushVariableScope(el); initLoopLabels(labelName); } private void initLoopLabels(String labelName) { continueLabel = new Label(); breakLabel = new Label(); if (labelName!=null) { namedLoopBreakLabel.put(labelName,breakLabel); namedLoopContinueLabel.put(labelName,continueLabel); } } /** * Should be called when decending into a loop that does * not define a scope. Creates a element for the state stack * so pop has to be called later */ public void pushLoop(String labelName) { pushState(); initLoopLabels(labelName); } /** * Used for break foo inside a loop to end the * execution of the marked loop. This method will return the * break label of the loop if there is one found for the name. * If not, the current break label is returned. */ public Label getNamedBreakLabel(String name) { Label label = getBreakLabel(); Label endLabel = null; if (name!=null) endLabel = (Label) namedLoopBreakLabel.get(name); if (endLabel!=null) label = endLabel; return label; } /** * Used for continue foo inside a loop to continue * the execution of the marked loop. This method will return * the break label of the loop if there is one found for the * name. If not, getLabel is used. */ public Label getNamedContinueLabel(String name) { Label label = getLabel(name); Label endLabel = null; if (name!=null) endLabel = (Label) namedLoopContinueLabel.get(name); if (endLabel!=null) label = endLabel; return label; } /** * Creates a new break label and a element for the state stack * so pop has to be called later */ public Label pushSwitch(){ pushState(); breakLabel = new Label(); return breakLabel; } /** * because a boolean Expression may not be evaluated completely * it is important to keep the registers clean */ public void pushBooleanExpression(){ pushState(); } private BytecodeVariable defineVar(String name, ClassNode type, boolean holder, boolean useReferenceDirectly) { int prevCurrent = currentVariableIndex; makeNextVariableID(type,useReferenceDirectly); int index = currentVariableIndex; if (holder && !useReferenceDirectly) index = localVariableOffset++; BytecodeVariable answer = new BytecodeVariable(index, type, name, prevCurrent); usedVariables.add(answer); answer.setHolder(holder); return answer; } private void makeLocalVariablesOffset(Parameter[] paras,boolean isInStaticContext) { resetVariableIndex(isInStaticContext); for (int i = 0; i < paras.length; i++) { makeNextVariableID(paras[i].getType(),false); } localVariableOffset = nextVariableIndex; resetVariableIndex(isInStaticContext); } private void defineMethodVariables(Parameter[] paras, boolean isInStaticContext) { Label startLabel = new Label(); thisStartLabel = startLabel; controller.getMethodVisitor().visitLabel(startLabel); makeLocalVariablesOffset(paras,isInStaticContext); for (int i = 0; i < paras.length; i++) { String name = paras[i].getName(); BytecodeVariable answer; ClassNode type = paras[i].getType(); if (paras[i].isClosureSharedVariable()) { boolean useExistingReference = paras[i].getNodeMetaData(ClosureWriter.UseExistingReference.class) != null; answer = defineVar(name, paras[i].getOriginType(), true, useExistingReference); answer.setStartLabel(startLabel); if (!useExistingReference) { controller.getOperandStack().load(type,currentVariableIndex); controller.getOperandStack().box(); // GROOVY-4237, the original variable should always appear // in the variable index, otherwise some programs get into // trouble. So we define a dummy variable for the packaging // phase and let it end right away before the normal // reference will be used Label newStart = new Label(); controller.getMethodVisitor().visitLabel(newStart); BytecodeVariable var = new BytecodeVariable(currentVariableIndex, paras[i].getOriginType(), name, currentVariableIndex); var.setStartLabel(startLabel); var.setEndLabel(newStart); usedVariables.add(var); answer.setStartLabel(newStart); createReference(answer); } } else { answer = defineVar(name, type, false, false); answer.setStartLabel(startLabel); } stackVariables.put(name, answer); } nextVariableIndex = localVariableOffset; } private void createReference(BytecodeVariable reference) { MethodVisitor mv = controller.getMethodVisitor(); mv.visitTypeInsn(NEW, "groovy/lang/Reference"); mv.visitInsn(DUP_X1); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "", "(Ljava/lang/Object;)V"); mv.visitVarInsn(ASTORE, reference.getIndex()); } private void pushInitValue(ClassNode type, MethodVisitor mv) { if (ClassHelper.isPrimitiveType(type)) { if (type==ClassHelper.long_TYPE) { mv.visitInsn(LCONST_0); } else if (type==ClassHelper.double_TYPE) { mv.visitInsn(DCONST_0); } else if (type==ClassHelper.float_TYPE) { mv.visitInsn(FCONST_0); } else { mv.visitLdcInsn(0); } } else { mv.visitInsn(ACONST_NULL); } } /** * Defines a new Variable using an AST variable. * @param initFromStack if true the last element of the * stack will be used to initialize * the new variable. If false null * will be used. */ public BytecodeVariable defineVariable(Variable v, boolean initFromStack) { return defineVariable(v, v.getOriginType(), initFromStack); } public BytecodeVariable defineVariable(Variable v, ClassNode variableType, boolean initFromStack) { //TODO: any usage of this method should have different operand stack hanlding // then the remove(1) here and there in this one can be removed and others // can be changed String name = v.getName(); BytecodeVariable answer = defineVar(name, variableType, v.isClosureSharedVariable(), v.isClosureSharedVariable()); stackVariables.put(name, answer); MethodVisitor mv = controller.getMethodVisitor(); Label startLabel = new Label(); answer.setStartLabel(startLabel); ClassNode type = answer.getType().redirect(); OperandStack operandStack = controller.getOperandStack(); if (!initFromStack) pushInitValue(type, mv); operandStack.push(answer.getType()); if (answer.isHolder()) { operandStack.box(); operandStack.remove(1); createReference(answer); } else { operandStack.storeVar(answer); } mv.visitLabel(startLabel); return answer; } /** * @param name the name of the variable of interest * @return true if a variable is already defined */ public boolean containsVariable(String name) { return stackVariables.containsKey(name); } /** * Calculates the index of the next free register stores it * and sets the current variable index to the old value */ private void makeNextVariableID(ClassNode type, boolean useReferenceDirectly) { currentVariableIndex = nextVariableIndex; if ((type==ClassHelper.long_TYPE || type==ClassHelper.double_TYPE) && !useReferenceDirectly) { nextVariableIndex++; } nextVariableIndex++; } /** * Returns the label for the given name */ public Label getLabel(String name) { if (name==null) return null; Label l = (Label) superBlockNamedLabels.get(name); if (l==null) l = createLocalLabel(name); return l; } /** * creates a new named label */ public Label createLocalLabel(String name) { Label l = (Label) currentBlockNamedLabels.get(name); if (l==null) { l = new Label(); currentBlockNamedLabels.put(name,l); } return l; } public void applyFinallyBlocks(Label label, boolean isBreakLabel) { // first find the state defining the label. That is the state // directly after the state not knowing this label. If no state // in the list knows that label, then the defining state is the // current state. StateStackElement result = null; for (ListIterator iter = stateStack.listIterator(stateStack.size()); iter.hasPrevious();) { StateStackElement element = (StateStackElement) iter.previous(); if (!element.currentBlockNamedLabels.values().contains(label)) { if (isBreakLabel && element.breakLabel != label) { result = element; break; } if (!isBreakLabel && element.continueLabel != label) { result = element; break; } } } List blocksToRemove; if (result==null) { // all Blocks do know the label, so use all finally blocks blocksToRemove = (List) Collections.EMPTY_LIST; } else { blocksToRemove = result.finallyBlocks; } List blocks = new LinkedList(finallyBlocks); blocks.removeAll(blocksToRemove); applyBlockRecorder(blocks); } private void applyBlockRecorder(List blocks) { if (blocks.size()==0 || blocks.size()==visitedBlocks.size()) return; MethodVisitor mv = controller.getMethodVisitor(); Label end = new Label(); mv.visitInsn(NOP); mv.visitLabel(end); Label newStart = new Label(); for (BlockRecorder fb : blocks) { if (visitedBlocks.contains(fb)) continue; fb.closeRange(end); // we exclude the finally block from the exception table // here to avoid double visiting of finally statements fb.excludedStatement.run(); fb.startRange(newStart); } mv.visitInsn(NOP); mv.visitLabel(newStart); } public void applyBlockRecorder() { applyBlockRecorder(finallyBlocks); } public boolean hasBlockRecorder() { return !finallyBlocks.isEmpty(); } public void pushBlockRecorder(BlockRecorder recorder) { pushState(); finallyBlocks.addFirst(recorder); } public void pushBlockRecorderVisit(BlockRecorder finallyBlock) { visitedBlocks.add(finallyBlock); } public void popBlockRecorderVisit(BlockRecorder finallyBlock) { visitedBlocks.remove(finallyBlock); } public void writeExceptionTable(BlockRecorder block, Label goal, String sig) { if (block.isEmpty) return; MethodVisitor mv = controller.getMethodVisitor(); for (LabelRange range : block.ranges) { mv.visitTryCatchBlock(range.start, range.end, goal, sig); } } // public MethodVisitor getMethodVisitor() { // return mv; // } public boolean isLHS() { return lhs; } public void pushLHS(boolean lhs) { lhsStack.add(lhs); this.lhs = lhs; } public void popLHS() { lhsStack.removeLast(); this.lhs = lhsStack.getLast(); } public void pushImplicitThis(boolean implicitThis) { implicitThisStack.add(implicitThis); this.implicitThis = implicitThis; } public boolean isImplicitThis() { return implicitThis; } public void popImplicitThis() { implicitThisStack.removeLast(); this.implicitThis = implicitThisStack.getLast(); } public boolean isInSpecialConstructorCall() { return inSpecialConstructallCall; } public void pushInSpecialConstructorCall() { pushState(); inSpecialConstructallCall = true; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/AssertionWriter.java0000644001501200150120000002566111707612046026417 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.control.Janitor; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.runtime.powerassert.SourceText; import org.codehaus.groovy.runtime.powerassert.SourceTextNotAvailableException; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; public class AssertionWriter { // assert private static final MethodCaller assertFailedMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "assertFailed"); private static class AssertionTracker { int recorderIndex; SourceText sourceText; } private WriterController controller; private AssertionTracker assertionTracker; private AssertionTracker disabledTracker; public AssertionWriter(WriterController wc) { this.controller = wc; } public void writeAssertStatement(AssertStatement statement) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); boolean rewriteAssert = true; // don't rewrite assertions with message rewriteAssert = statement.getMessageExpression() == ConstantExpression.NULL; AssertionTracker oldTracker = assertionTracker; Janitor janitor = new Janitor(); final Label tryStart = new Label(); if (rewriteAssert){ assertionTracker = new AssertionTracker(); try { // because source position seems to be more reliable for statements // than for expressions, we get the source text for the whole statement assertionTracker.sourceText = new SourceText(statement, controller.getSourceUnit(), janitor); mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/powerassert/ValueRecorder"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/powerassert/ValueRecorder", "", "()V"); //TODO: maybe use more specialized type here controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); assertionTracker.recorderIndex = controller.getCompileStack().defineTemporaryVariable("recorder", true); mv.visitLabel(tryStart); } catch (SourceTextNotAvailableException e) { // don't rewrite assertions w/o source text rewriteAssert = false; } } statement.getBooleanExpression().visit(controller.getAcg()); Label exceptionThrower = operandStack.jump(IFEQ); // do nothing, but clear the value recorder if (rewriteAssert) { //clean up assertion recorder mv.visitVarInsn(ALOAD, assertionTracker.recorderIndex); mv.visitMethodInsn( INVOKEVIRTUAL, "org/codehaus/groovy/runtime/powerassert/ValueRecorder", "clear", "()V"); } Label afterAssert = new Label(); mv.visitJumpInsn(GOTO, afterAssert); mv.visitLabel(exceptionThrower); if (rewriteAssert) { mv.visitLdcInsn(assertionTracker.sourceText.getNormalizedText()); mv.visitVarInsn(ALOAD, assertionTracker.recorderIndex); mv.visitMethodInsn( INVOKESTATIC, "org/codehaus/groovy/runtime/powerassert/AssertionRenderer", "render", "(Ljava/lang/String;Lorg/codehaus/groovy/runtime/powerassert/ValueRecorder;)Ljava/lang/String;" ); } else { writeSourcelessAssertText(statement); } operandStack.push(ClassHelper.STRING_TYPE); AssertionTracker savedTracker = assertionTracker; assertionTracker = null; // now the optional exception expression statement.getMessageExpression().visit(controller.getAcg()); operandStack.box(); assertFailedMethod.call(mv); operandStack.remove(2); // assertFailed called static with 2 arguments if (rewriteAssert) { final Label tryEnd = new Label(); mv.visitLabel(tryEnd); mv.visitJumpInsn(GOTO, afterAssert); // finally block to clean assertion recorder final Label catchAny = new Label(); mv.visitLabel(catchAny); mv.visitVarInsn(ALOAD, savedTracker.recorderIndex); mv.visitMethodInsn( INVOKEVIRTUAL, "org/codehaus/groovy/runtime/powerassert/ValueRecorder", "clear", "()V"); mv.visitInsn(ATHROW); // add catch any block to exception table controller.getCompileStack().addExceptionBlock(tryStart, tryEnd, catchAny, null); } mv.visitLabel(afterAssert); if (rewriteAssert) { controller.getCompileStack().removeVar(savedTracker.recorderIndex); } assertionTracker = oldTracker; // close possibly open file handles from getting a sample for // power asserts janitor.cleanup(); } private void writeSourcelessAssertText(AssertStatement statement) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); BooleanExpression booleanExpression = statement.getBooleanExpression(); // push expression string onto stack String expressionText = booleanExpression.getText(); List list = new ArrayList(); addVariableNames(booleanExpression, list); if (list.isEmpty()) { mv.visitLdcInsn(expressionText); } else { boolean first = true; // let's create a new expression mv.visitTypeInsn(NEW, "java/lang/StringBuffer"); mv.visitInsn(DUP); mv.visitLdcInsn(expressionText + ". Values: "); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "", "(Ljava/lang/String;)V"); //TODO: maybe use more special type StringBuffer here operandStack.push(ClassHelper.OBJECT_TYPE); int tempIndex = controller.getCompileStack().defineTemporaryVariable("assert", true); for (String name : list) { String text = name + " = "; if (first) { first = false; } else { text = ", " + text; } mv.visitVarInsn(ALOAD, tempIndex); mv.visitLdcInsn(text); mv.visitMethodInsn( INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;"); mv.visitInsn(POP); mv.visitVarInsn(ALOAD, tempIndex); new VariableExpression(name).visit(controller.getAcg()); operandStack.box(); mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "toString", "(Ljava/lang/Object;)Ljava/lang/String;"); mv.visitMethodInsn( INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); mv.visitInsn(POP); operandStack.remove(1); } mv.visitVarInsn(ALOAD, tempIndex); controller.getCompileStack().removeVar(tempIndex); } } public void record(Expression expression) { if (assertionTracker==null) return; record(assertionTracker.sourceText.getNormalizedColumn(expression.getLineNumber(), expression.getColumnNumber())); } public void record(Token op) { if (assertionTracker==null) return; record(assertionTracker.sourceText.getNormalizedColumn(op.getStartLine(), op.getStartColumn())); } private void record(int normalizedColumn) { if (assertionTracker==null) return; MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); operandStack.dup(); operandStack.box(); mv.visitVarInsn(ALOAD, assertionTracker.recorderIndex); operandStack.push(ClassHelper.OBJECT_TYPE); //helper.swapWithObject(ClassHelper.OBJECT_TYPE); operandStack.swap(); mv.visitLdcInsn(normalizedColumn); mv.visitMethodInsn( INVOKEVIRTUAL, "org/codehaus/groovy/runtime/powerassert/ValueRecorder", "record", "(Ljava/lang/Object;I)Ljava/lang/Object;"); mv.visitInsn(POP); operandStack.remove(2); } private void addVariableNames(Expression expression, List list) { if (expression instanceof BooleanExpression) { BooleanExpression boolExp = (BooleanExpression) expression; addVariableNames(boolExp.getExpression(), list); } else if (expression instanceof BinaryExpression) { BinaryExpression binExp = (BinaryExpression) expression; addVariableNames(binExp.getLeftExpression(), list); addVariableNames(binExp.getRightExpression(), list); } else if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; list.add(varExp.getName()); } } public void disableTracker() { if (assertionTracker==null) return; disabledTracker = assertionTracker; assertionTracker = null; } public void reenableTracker() { if (disabledTracker==null) return; assertionTracker = disabledTracker; disabledTracker = null; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryFloatExpressionHelper.java0000644001501200150120000000634111707612046030677 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import static org.objectweb.asm.Opcodes.*; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; /** * @author Jochen "blackdrag" Theodorou */ public class BinaryFloatExpressionHelper extends BinaryExpressionWriter { public BinaryFloatExpressionHelper(WriterController controller) { super(controller); } protected void doubleTwoOperands(MethodVisitor mv) { mv.visitInsn(DUP2); } private static final MethodCaller floatArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "fArrayGet"), floatArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "fArraySet"); protected MethodCaller getArrayGetCaller() { return floatArrayGet; } protected MethodCaller getArraySetCaller() { return floatArraySet; } protected boolean writeBitwiseOp(int type, boolean simulate) { if (!simulate) throw new GroovyBugError("should not reach here"); return false; } protected int getBitwiseOperationBytecode(int type) { return -1; } protected int getCompareCode() { return FCMPG; } protected ClassNode getNormalOpResultType() { return ClassHelper.float_TYPE; } protected boolean writeShiftOp(int type, boolean simulate) { if (!simulate) throw new GroovyBugError("should not reach here"); return false; } protected int getShiftOperationBytecode(int type) { return -1; } private static final int[] stdOperations = { FADD, // PLUS 200 FSUB, // MINUS 201 FMUL, // MULTIPLY 202 0, // DIV, (203) but we don't want that one FDIV, // INTDIV 204 FREM, // MOD 203 }; protected int getStandardOperationBytecode(int type) { return stdOperations[type]; } protected void removeTwoOperands(MethodVisitor mv) { mv.visitInsn(POP2); } protected void writeMinusMinus(MethodVisitor mv) { mv.visitInsn(FCONST_1); mv.visitInsn(FSUB); } protected void writePlusPlus(MethodVisitor mv) { mv.visitInsn(FCONST_1); mv.visitInsn(FADD); } protected ClassNode getDevisionOpResultType() { return ClassHelper.BigDecimal_TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/StatementMetaTypeChooser.java0000644001501200150120000000445611707612046030212 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import static org.codehaus.groovy.ast.ClassHelper.OBJECT_TYPE; /** * A {@link TypeChooser} which is aware of statement metadata. * * @author Jochen Theodorou * @author Cedric Champeau */ public class StatementMetaTypeChooser implements TypeChooser { public ClassNode resolveType(final Expression exp, final ClassNode current) { if (exp instanceof ClassExpression) return ClassHelper.CLASS_Type; OptimizingStatementWriter.StatementMeta meta = (OptimizingStatementWriter.StatementMeta) exp.getNodeMetaData(OptimizingStatementWriter.StatementMeta.class); ClassNode type = null; if (meta!=null) type = meta.type; if (type!=null) return type; if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.isClosureSharedVariable()) return ve.getType(); type = ve.getOriginType(); if (ve.getAccessedVariable() instanceof FieldNode) { FieldNode fn = (FieldNode) ve.getAccessedVariable(); if (!fn.getDeclaringClass().equals(current)) return OBJECT_TYPE; } } else if (exp instanceof Variable) { Variable v = (Variable) exp; type = v.getOriginType(); } else { type = exp.getType(); } return type.redirect(); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/package.html0000644001501200150120000000034211707612046024656 0ustar miguelmiguel package org.codehaus.groovy.classgen.asm.*

      Helper classes for ASMClassGenerator. All classes in this package are for internal usage only.

      groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java0000644001501200150120000004354311707612046032442 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.HashMap; import java.util.Map; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.DynamicVariable; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.runtime.BytecodeInterface8; import static org.codehaus.groovy.ast.ClassHelper.*; import static org.codehaus.groovy.syntax.Types.*; import static org.codehaus.groovy.ast.tools.WideningCategories.*; /** * This class is for internal use only! * This class will dispatch to the right type adapters according to the * kind of binary expression that is provided. * @author Jochen "blackdrag" Theodorou * @author Roshan Dawrani */ public class BinaryExpressionMultiTypeDispatcher extends BinaryExpressionHelper { private static class BinaryCharExpressionHelper extends BinaryIntExpressionHelper { public BinaryCharExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller charArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "cArrayGet"), charArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "cArraySet"); @Override protected MethodCaller getArrayGetCaller() { return charArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.char_TYPE; } @Override protected MethodCaller getArraySetCaller() { return charArraySet; } } private static class BinaryByteExpressionHelper extends BinaryIntExpressionHelper { public BinaryByteExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller byteArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "bArrayGet"), byteArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "bArraySet"); @Override protected MethodCaller getArrayGetCaller() { return byteArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.byte_TYPE; } @Override protected MethodCaller getArraySetCaller() { return byteArraySet; } } private static class BinaryShortExpressionHelper extends BinaryIntExpressionHelper { public BinaryShortExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller shortArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "sArrayGet"), shortArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "sArraySet"); @Override protected MethodCaller getArrayGetCaller() { return shortArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.short_TYPE; } @Override protected MethodCaller getArraySetCaller() { return shortArraySet; } } private BinaryExpressionWriter[] binExpWriter = { /* 0: dummy */ new BinaryObjectExpressionHelper(getController()), /* 1: int */ new BinaryIntExpressionHelper(getController()), /* 2: long */ new BinaryLongExpressionHelper(getController()), /* 3: double */ new BinaryDoubleExpressionHelper(getController()), /* 4: char */ new BinaryCharExpressionHelper(getController()), /* 5: byte */ new BinaryByteExpressionHelper(getController()), /* 6: short */ new BinaryShortExpressionHelper(getController()), /* 7: float */ new BinaryFloatExpressionHelper(getController()), /* 8: bool */ new BinaryBooleanExpressionHelper(getController()), }; public static Map typeMap = new HashMap(14); static { typeMap.put(int_TYPE, 1); typeMap.put(long_TYPE, 2); typeMap.put(double_TYPE, 3); typeMap.put(char_TYPE, 4); typeMap.put(byte_TYPE, 5); typeMap.put(short_TYPE, 6); typeMap.put(float_TYPE, 7); typeMap.put(boolean_TYPE, 8); } public final static String[] typeMapKeyNames = {"dummy", "int", "long", "double", "char", "byte", "short", "float", "boolean"}; public BinaryExpressionMultiTypeDispatcher(WriterController wc) { super(wc); } private int getOperandConversionType(ClassNode leftType, ClassNode rightType) { if (isIntCategory(leftType) && isIntCategory(rightType)) return 1; if (isLongCategory(leftType) && isLongCategory(rightType)) return 2; if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) return 0; if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) return 3; return 0; } private int getOperandType(ClassNode type) { Integer ret = typeMap.get(type); if (ret==null) return 0; return ret; } @Override protected void evaluateCompareExpression(final MethodCaller compareMethod, BinaryExpression binExp) { ClassNode current = getController().getClassNode(); int operation = binExp.getOperation().getType(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getController().getTypeChooser().resolveType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getController().getTypeChooser().resolveType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.write(operation, true)) { AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateCompareExpression(compareMethod, binExp); } } @Override protected void evaluateBinaryExpression(final String message, BinaryExpression binExp) { int operation = removeAssignment(binExp.getOperation().getType()); ClassNode current = getController().getClassNode(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftTypeOrig = getController().getTypeChooser().resolveType(leftExp, current); ClassNode leftType = leftTypeOrig; Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getController().getTypeChooser().resolveType(rightExp, current); AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); if (operation==LEFT_SQUARE_BRACKET) { leftType = leftTypeOrig.getComponentType(); int operationType = getOperandType(leftType); BinaryExpressionWriter bew = binExpWriter[operationType]; if ( leftTypeOrig.isArray() && isIntCastableType(rightExp) && bew.arrayGet(operation, true)) { leftExp.visit(acg); os.doGroovyCast(leftTypeOrig); rightExp.visit(acg); os.doGroovyCast(int_TYPE); bew.arrayGet(operation, false); if(bew instanceof BinaryObjectExpressionHelper) { os.replace(ClassHelper.OBJECT_TYPE,2); } else { os.replace(leftType,2); } } else { super.evaluateBinaryExpression(message, binExp); } } else { int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; if ( isShiftOperation(operation) && isIntCastableType(rightExp) && bew.write(operation, true)) { leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(int_TYPE); bew.write(operation, false); } else if (operation==DIVIDE && bew.writeDivision(true)) { leftExp.visit(acg); os.doGroovyCast(bew.getDevisionOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getDevisionOpResultType()); bew.writeDivision(false); } else if (bew.write(operation, true)) { leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateBinaryExpression(message, binExp); } } } private boolean isIntCastableType(Expression rightExp) { ClassNode type = getController().getTypeChooser().resolveType(rightExp, getController().getClassNode()); return isNumberCategory(type); } private boolean isShiftOperation(int operation) { return operation==LEFT_SHIFT || operation==RIGHT_SHIFT || operation==RIGHT_SHIFT_UNSIGNED; } private boolean isAssignmentToArray(BinaryExpression binExp) { Expression leftExpression = binExp.getLeftExpression(); if (!(leftExpression instanceof BinaryExpression)) return false; BinaryExpression leftBinExpr = (BinaryExpression) leftExpression; if (leftBinExpr.getOperation().getType() != LEFT_SQUARE_BRACKET) return false; return true; } private int removeAssignment(int op) { switch (op) { case PLUS_EQUAL: return PLUS; case MINUS_EQUAL: return MINUS; case MULTIPLY_EQUAL: return MULTIPLY; default: return op; } } private boolean doAssignmentToArray(BinaryExpression binExp) { if (!isAssignmentToArray(binExp)) return false; // we need to handle only assignment to arrays combined with an operation // special here. e.g x[a] += b int operation = removeAssignment(binExp.getOperation().getType()); ClassNode current = getController().getClassNode(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getController().getTypeChooser().resolveType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getController().getTypeChooser().resolveType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; boolean simulationSuccess = bew.arrayGet(LEFT_SQUARE_BRACKET, true); simulationSuccess = simulationSuccess && bew.write(operation, true); simulationSuccess = simulationSuccess && bew.arraySet(true); if (!simulationSuccess) return false; AsmClassGenerator acg = getController().getAcg(); OperandStack operandStack = getController().getOperandStack(); CompileStack compileStack = getController().getCompileStack(); // for x[a] += b we have the structure: // x = left(left(binExp))), b = right(binExp), a = right(left(binExp))) // for array set we need these values on stack: array, index, right // for array get we need these values on stack: array, index // to eval the expression we need x[a] = x[a]+b // -> arraySet(x,a, x[a]+b) // -> arraySet(x,a, arrayGet(x,a,b)) // --> x,a, x,a, b as operands // --> load x, load a, DUP2, call arrayGet, load b, call operation,call arraySet // since we cannot DUP2 here easily we will save the subscript and DUP x // --> sub=a, load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet BinaryExpression arrayWithSubscript = (BinaryExpression) leftExp; Expression subscript = arrayWithSubscript.getRightExpression(); // load array index: sub=a [load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet] subscript.visit(acg); operandStack.doGroovyCast(int_TYPE); int subscriptValueId = compileStack.defineTemporaryVariable("$sub", ClassHelper.int_TYPE, true); // load array: load x and DUP [load sub, call arrayGet, load b, call operation, load sub, call arraySet] arrayWithSubscript.getLeftExpression().visit(acg); operandStack.dup(); // array get: load sub, call arrayGet [load b, call operation, load sub, call arraySet] operandStack.load(ClassHelper.int_TYPE, subscriptValueId); bew.arrayGet(LEFT_SQUARE_BRACKET, false); operandStack.replace(leftType, 2); // complete rhs: load b, call operation [load sub, call arraySet] binExp.getRightExpression().visit(acg); bew.write(operation, false); // let us save that value for the return operandStack.dup(); int resultValueId = compileStack.defineTemporaryVariable("$result", rightType, true); // array set: load sub, call arraySet [] operandStack.load(ClassHelper.int_TYPE, subscriptValueId); operandStack.swap(); bew.arraySet(false); operandStack.remove(3); // 3 operands, the array, the index and the value! // load return value operandStack.load(rightType, resultValueId); // cleanup compileStack.removeVar(resultValueId); compileStack.removeVar(subscriptValueId); return true; } @Override protected void evaluateBinaryExpressionWithAssignment(String method, BinaryExpression binExp) { if (doAssignmentToArray(binExp)) return; if (doAssignmentToLocalVariable(method, binExp)) return; super.evaluateBinaryExpressionWithAssignment(method, binExp); } private boolean doAssignmentToLocalVariable(String method, BinaryExpression binExp) { Expression left = binExp.getLeftExpression(); if (left instanceof VariableExpression) { VariableExpression ve = (VariableExpression) left; Variable v = ve.getAccessedVariable(); if (v instanceof DynamicVariable) return false; if (v instanceof PropertyExpression) return false; /* field and declaration we don't return false */ } else { return false; } evaluateBinaryExpression(method, binExp); getController().getOperandStack().dup(); getController().getCompileStack().pushLHS(true); binExp.getLeftExpression().visit(getController().getAcg()); getController().getCompileStack().popLHS(); return true; } @Override protected void assignToArray(Expression orig, Expression receiver, Expression index, Expression rhsValueLoader) { ClassNode current = getController().getClassNode(); ClassNode arrayType = getController().getTypeChooser().resolveType(receiver, current); ClassNode arrayComponentType = arrayType.getComponentType(); int operationType = getOperandType(arrayComponentType); BinaryExpressionWriter bew = binExpWriter[operationType]; AsmClassGenerator acg = getController().getAcg(); if (bew.arraySet(true) && arrayType.isArray()) { OperandStack operandStack = getController().getOperandStack(); // load the array receiver.visit(acg); operandStack.doGroovyCast(arrayType); // load index index.visit(acg); operandStack.doGroovyCast(int_TYPE); // load rhs rhsValueLoader.visit(acg); operandStack.doGroovyCast(arrayComponentType); // store value in array bew.arraySet(false); // load return value && correct operand stack stack operandStack.remove(3); rhsValueLoader.visit(acg); } else { super.assignToArray(orig, receiver, index, rhsValueLoader); } } @Override protected void writePostOrPrefixMethod(int op, String method, Expression expression, Expression orig) { ClassNode type = getController().getTypeChooser().resolveType(orig, getController().getClassNode()); int operationType = getOperandType(type); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.writePostOrPrefixMethod(op,true)) { OperandStack operandStack = getController().getOperandStack(); // at this point the receiver will be already on the stack operandStack.doGroovyCast(type); bew.writePostOrPrefixMethod(op,false); operandStack.replace(bew.getNormalOpResultType()); } else { super.writePostOrPrefixMethod(op, method, expression, orig); } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.java0000644001501200150120000002251111707612046030361 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.codehaus.groovy.syntax.Types.*; import static org.objectweb.asm.Opcodes.*; public class BinaryIntExpressionHelper extends BinaryExpressionWriter { private static final MethodCaller intArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "intArrayGet"); private static final MethodCaller intArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "intArraySet"); private static final int[] stdCompareCodes = { IF_ICMPEQ, // COMPARE_NOT_EQUAL 120 IF_ICMPNE, // COMPARE_IDENTICAL 121 IF_ICMPEQ, // COMPARE_NOT_IDENTICAL 122 IF_ICMPNE, // COMPARE_EQUAL 123 IF_ICMPGE, // COMPARE_LESS_THAN 124 IF_ICMPGT, // COMPARE_LESS_THAN_EQUAL 125 IF_ICMPLE, // COMPARE_GREATER_THAN 126 IF_ICMPLT, // COMPARE_GREATER_THAN_EQUAL 127 }; private static final int[] stdOperations = { IADD, // PLUS 200 ISUB, // MINUS 201 IMUL, // MULTIPLY 202 0, // DIV, (203) but we don't want that one IDIV, // INTDIV 204 IREM, // MOD 203 }; private static final int[] bitOp = { IOR, // BITWISE_OR / PIPE 340 IAND, // BITWISE_AND 341 IXOR, // BIWISE_XOR 342 }; /* unhandled types from from org.codehaus.groovy.syntax.Types public static final int LOGICAL_OR = 162; // || public static final int LOGICAL_AND = 164; // && public static final int DIVIDE = 203; // / public static final int STAR_STAR = 206; // ** public static final int POWER = STAR_STAR; // public static final int PLUS_EQUAL = 210; // += public static final int MINUS_EQUAL = 211; // -= public static final int MULTIPLY_EQUAL = 212; // *= public static final int DIVIDE_EQUAL = 213; // /= public static final int INTDIV_EQUAL = 214; // \= public static final int MOD_EQUAL = 215; // %= public static final int POWER_EQUAL = 216; // **= public static final int PLUS_PLUS = 250; // ++ public static final int PREFIX_PLUS_PLUS = 251; // ++ public static final int POSTFIX_PLUS_PLUS = 252; // ++ public static final int PREFIX_PLUS = 253; // + public static final int MINUS_MINUS = 260; // -- public static final int PREFIX_MINUS_MINUS = 261; // -- public static final int POSTFIX_MINUS_MINUS = 262; // -- public static final int PREFIX_MINUS = 263; // - (negation) */ private static final int[] shiftOp = { ISHL, // LEFT_SHIFT 280 ISHR, // RIGHT_SHIFT 281 IUSHR // RIGHT_SHIFT_UNSIGNED 282 }; /* public static final int LEFT_SHIFT_EQUAL = 285; // <<= public static final int RIGHT_SHIFT_EQUAL = 286; // >>= public static final int RIGHT_SHIFT_UNSIGNED_EQUAL = 287; // >>>= public static final int BITWISE_OR_EQUAL = 350; // |= public static final int BITWISE_AND_EQUAL = 351; // &= public static final int BITWISE_XOR_EQUAL = 352; // ^= public static final int BITWISE_NEGATION = REGEX_PATTERN; // ~ */ private WriterController controller; public BinaryIntExpressionHelper(WriterController wc) { super(wc); controller = wc; } /** * writes a std compare. This involves the tokens IF_ICMPEQ, IF_ICMPNE, * IF_ICMPEQ, IF_ICMPNE, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE and IF_ICMPLT * @param type the token type * @return true if a successful std compare write */ protected boolean writeStdCompare(int type, boolean simulate) { type = type-COMPARE_NOT_EQUAL; // look if really compare if (type<0||type>7) return false; if (!simulate) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); // operands are on the stack already int bytecode = stdCompareCodes[type]; Label l1 = new Label(); mv.visitJumpInsn(bytecode,l1); mv.visitInsn(ICONST_1); Label l2 = new Label();; mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); operandStack.replace(ClassHelper.boolean_TYPE, 2); } return true; } /** * writes the spaceship operator, type should be COMPARE_TO * @param type the token type * @return true if a successful spaceship operator write */ protected boolean writeSpaceship(int type, boolean simulate) { if (type != COMPARE_TO) return false; /* we will actually do (x < y) ? -1 : ((x == y) ? 0 : 1) which is the essence of what the call with Integers would do this compiles to something along IF_ICMPGE L1 ICONST_M1 GOTO L2 L1 IF_ICMPNE L3 ICONST_0 GOTO L2 L3 ICONST_1 L2 since the operators are already on the stack and we don't want to load them again, we will instead duplicate them. This will require some pop actions in the branches! DUP2 (operands: IIII) IF_ICMPGE L1 (operands: II) ICONST_M1 (operands: III) GOTO L2 L1 ----- (operands: II) IF_ICMPNE L3 (operands: -) ICONST_0 (operands: I) GOTO L2 L3 - jump from L1 branch to here (operands: -) ICONST_1 (operands: I) L2 - if jump from GOTO L2 we have III, but need only I - if from L3 branch we get only I this means we have to pop of II before loading -1 */ if (!simulate) { MethodVisitor mv = controller.getMethodVisitor(); // duplicate int arguments mv.visitInsn(DUP2); Label l1 = new Label(); mv.visitJumpInsn(IF_ICMPGE,l1); // no jump, so -1, need to pop off surplus II mv.visitInsn(POP2); mv.visitInsn(ICONST_M1); Label l2 = new Label();; mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); Label l3 = new Label(); mv.visitJumpInsn(IF_ICMPNE,l3); mv.visitInsn(ICONST_0); mv.visitJumpInsn(GOTO,l2); mv.visitLabel(l3); mv.visitInsn(ICONST_1); controller.getOperandStack().replace(ClassHelper.int_TYPE, 2); } return true; } protected void doubleTwoOperands(MethodVisitor mv) { mv.visitInsn(DUP2); } protected MethodCaller getArrayGetCaller() { return intArrayGet; } protected MethodCaller getArraySetCaller() { return intArraySet; } protected int getBitwiseOperationBytecode(int type) { return bitOp[type]; } protected int getCompareCode() { return -1; } protected ClassNode getNormalOpResultType() { return ClassHelper.int_TYPE; } protected int getShiftOperationBytecode(int type) { return shiftOp[type]; } protected int getStandardOperationBytecode(int type) { return stdOperations[type]; } protected void removeTwoOperands(MethodVisitor mv) { mv.visitInsn(POP2); } protected void writeMinusMinus(MethodVisitor mv) { mv.visitInsn(ICONST_1); mv.visitInsn(ISUB); } protected void writePlusPlus(MethodVisitor mv) { mv.visitInsn(ICONST_1); mv.visitInsn(IADD); } protected ClassNode getDevisionOpResultType() { return ClassHelper.BigDecimal_TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/TypeChooser.java0000644001501200150120000000264111707612046025510 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.expr.Expression; /** * Interface for modules which are capable of resolving the type of an expression. * Several implementations are available, depending on whether you are in a dynamic * or static compilation mode. * * @author Cedric Champeau */ public interface TypeChooser { /** * Resolve the type of an expression. Depending on the implementations, the * returned type may be the declared type or an inferred type. * @param expression the expression for which the type must be returned. * @param classNode the classnode this expression belongs to * @return the resolved type. */ ClassNode resolveType(final Expression expression, ClassNode classNode); } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/InvocationWriter.java0000644001501200150120000004466211715031256026560 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.StaticMethodCallExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.StatementMeta; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; public class InvocationWriter { // method invocation private static final MethodCallerMultiAdapter invokeMethodOnCurrent = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "invokeMethodOnCurrent", true, false); private static final MethodCallerMultiAdapter invokeMethodOnSuper = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "invokeMethodOnSuper", true, false); private static final MethodCallerMultiAdapter invokeMethod = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "invokeMethod", true, false); private static final MethodCallerMultiAdapter invokeStaticMethod = MethodCallerMultiAdapter.newStatic(ScriptBytecodeAdapter.class, "invokeStaticMethod", true, true); private static final MethodCaller invokeClosureMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeClosure"); private WriterController controller; public InvocationWriter(WriterController wc) { this.controller = wc; } private void makeInvokeMethodCall(MethodCallExpression call, boolean useSuper, MethodCallerMultiAdapter adapter) { // receiver // we operate on GroovyObject if possible Expression objectExpression = call.getObjectExpression(); // message name Expression messageName = new CastExpression(ClassHelper.STRING_TYPE, call.getMethod()); if (useSuper) { ClassNode classNode = controller.isInClosure() ? controller.getOutermostClass() : controller.getClassNode(); // GROOVY-4035 ClassNode superClass = classNode.getSuperClass(); makeCall(call, new ClassExpression(superClass), objectExpression, messageName, call.getArguments(), adapter, call.isSafe(), call.isSpreadSafe(), false ); } else { makeCall(call, objectExpression, messageName, call.getArguments(), adapter, call.isSafe(), call.isSpreadSafe(), call.isImplicitThis() ); } } public void makeCall( Expression origin, Expression receiver, Expression message, Expression arguments, MethodCallerMultiAdapter adapter, boolean safe, boolean spreadSafe, boolean implicitThis ) { ClassNode cn = controller.getClassNode(); if (controller.isInClosure() && !implicitThis && AsmClassGenerator.isThisExpression(receiver)) cn=cn.getOuterClass(); makeCall(origin, new ClassExpression(cn), receiver, message, arguments, adapter, safe, spreadSafe, implicitThis); } private boolean writeDirectMethodCall(MethodNode target, boolean implicitThis, Expression receiver, TupleExpression args) { if (target==null) return false; String methodName = target.getName(); CompileStack compileStack = controller.getCompileStack(); OperandStack operandStack = controller.getOperandStack(); MethodVisitor mv = controller.getMethodVisitor(); int opcode = INVOKEVIRTUAL; if (target.isStatic()) { opcode = INVOKESTATIC; } else if (target.isPrivate()) { opcode = INVOKESPECIAL; } // handle receiver int argumentsToRemove = 0; if (opcode!=INVOKESTATIC) { if (receiver!=null) { // load receiver if not static invocation compileStack.pushImplicitThis(implicitThis); receiver.visit(controller.getAcg()); operandStack.doGroovyCast(target.getDeclaringClass()); compileStack.popImplicitThis(); argumentsToRemove++; } else { mv.visitIntInsn(ALOAD,0); } } loadArguments(args.getExpressions(), target.getParameters()); String owner = BytecodeHelper.getClassInternalName(target.getDeclaringClass()); String desc = BytecodeHelper.getMethodDescriptor(target.getReturnType(), target.getParameters()); mv.visitMethodInsn(opcode, owner, methodName, desc); ClassNode ret = target.getReturnType().redirect(); if (ret==ClassHelper.VOID_TYPE) { ret = ClassHelper.OBJECT_TYPE; mv.visitInsn(ACONST_NULL); } argumentsToRemove += args.getExpressions().size(); controller.getOperandStack().remove(argumentsToRemove); controller.getOperandStack().push(ret); return true; } // load arguments private void loadArguments(List argumentList, Parameter[] para) { for (int i=0; i MethodCallerMultiAdapter.MAX_ARGS || containsSpreadExpression) { ArgumentListExpression ae = makeArgumentList(arguments); if (containsSpreadExpression) { acg.despreadList(ae.getExpressions(), true); } else { ae.visit(acg); } } else if (numberOfArguments > 0) { operandsToRemove += numberOfArguments; TupleExpression te = (TupleExpression) arguments; for (int i = 0; i < numberOfArguments; i++) { Expression argument = te.getExpression(i); argument.visit(acg); operandStack.box(); if (argument instanceof CastExpression) acg.loadWrapper(argument); } } adapter.call(controller.getMethodVisitor(), numberOfArguments, safe, spreadSafe); compileStack.popLHS(); operandStack.replace(ClassHelper.OBJECT_TYPE,operandsToRemove); } private ArgumentListExpression makeArgumentList(Expression arguments) { ArgumentListExpression ae; if (arguments instanceof ArgumentListExpression) { ae = (ArgumentListExpression) arguments; } else if (arguments instanceof TupleExpression) { TupleExpression te = (TupleExpression) arguments; ae = new ArgumentListExpression(te.getExpressions()); } else { ae = new ArgumentListExpression(); ae.addExpression(arguments); } return ae; } private String getMethodName(Expression message) { String methodName = null; if (message instanceof CastExpression) { CastExpression msg = (CastExpression) message; if (msg.getType() == ClassHelper.STRING_TYPE) { final Expression methodExpr = msg.getExpression(); if (methodExpr instanceof ConstantExpression) methodName = methodExpr.getText(); } } if (methodName == null && message instanceof ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression) message; methodName = constantExpression.getText(); } return methodName; } public void writeInvokeMethod(MethodCallExpression call) { if (isClosureCall(call)) { // let's invoke the closure method invokeClosure(call.getArguments(), call.getMethodAsString()); } else { boolean isSuperMethodCall = usesSuper(call); MethodCallerMultiAdapter adapter = invokeMethod; if (AsmClassGenerator.isThisExpression(call.getObjectExpression())) adapter = invokeMethodOnCurrent; if (isSuperMethodCall) adapter = invokeMethodOnSuper; if (isStaticInvocation(call)) adapter = invokeStaticMethod; makeInvokeMethodCall(call, isSuperMethodCall, adapter); } } private boolean isClosureCall(MethodCallExpression call) { // are we a local variable? // it should not be an explicitly "this" qualified method call // and the current class should have a possible method ClassNode classNode = controller.getClassNode(); String methodName = call.getMethodAsString(); if (methodName==null) return false; if (!call.isImplicitThis()) return false; if (!AsmClassGenerator.isThisExpression(call.getObjectExpression())) return false; FieldNode field = classNode.getDeclaredField(methodName); if (field == null) return false; if (isStaticInvocation(call) && !field.isStatic()) return false; Expression arguments = call.getArguments(); return ! classNode.hasPossibleMethod(methodName, arguments); } private void invokeClosure(Expression arguments, String methodName) { AsmClassGenerator acg = controller.getAcg(); acg.visitVariableExpression(new VariableExpression(methodName)); controller.getOperandStack().box(); if (arguments instanceof TupleExpression) { arguments.visit(acg); } else { new TupleExpression(arguments).visit(acg); } invokeClosureMethod.call(controller.getMethodVisitor()); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); } private boolean isStaticInvocation(MethodCallExpression call) { if (!AsmClassGenerator.isThisExpression(call.getObjectExpression())) return false; if (controller.isStaticMethod()) return true; return controller.isStaticContext() && !call.isImplicitThis(); } private static boolean usesSuper(MethodCallExpression call) { Expression expression = call.getObjectExpression(); if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; String variable = varExp.getName(); return variable.equals("super"); } return false; } public void writeInvokeStaticMethod(StaticMethodCallExpression call) { makeCall(call, new ClassExpression(call.getOwnerType()), new ConstantExpression(call.getMethod()), call.getArguments(), InvocationWriter.invokeStaticMethod, false, false, false); } private boolean writeDirectConstructorCall(ConstructorCallExpression call) { if (!controller.isFastPath()) return false; StatementMeta meta = (StatementMeta) call.getNodeMetaData(StatementMeta.class); ConstructorNode cn = null; if (meta!=null) cn = (ConstructorNode) meta.target; if (cn==null) return false; String ownerDescriptor = prepareConstructorCall(cn); TupleExpression args = makeArgumentList(call.getArguments()); loadArguments(args.getExpressions(), cn.getParameters()); finnishConstructorCall(cn, ownerDescriptor, args.getExpressions().size()); return true; } private String prepareConstructorCall(ConstructorNode cn) { String owner = BytecodeHelper.getClassInternalName(cn.getDeclaringClass()); MethodVisitor mv = controller.getMethodVisitor(); mv.visitTypeInsn(NEW, owner); mv.visitInsn(DUP); return owner; } private void finnishConstructorCall(ConstructorNode cn, String ownerDescriptor, int argsToRemove) { String desc = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, cn.getParameters()); MethodVisitor mv = controller.getMethodVisitor(); mv.visitMethodInsn(INVOKESPECIAL, ownerDescriptor, "", desc); controller.getOperandStack().remove(argsToRemove); controller.getOperandStack().push(cn.getDeclaringClass()); } public void writeInvokeConstructor(ConstructorCallExpression call) { if (writeDirectConstructorCall(call)) return; if (writeAICCall(call)) return; Expression arguments = call.getArguments(); if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; int size = tupleExpression.getExpressions().size(); if (size == 0) { arguments = MethodCallExpression.NO_ARGUMENTS; } } Expression receiverClass = new ClassExpression(call.getType()); controller.getCallSiteWriter().makeCallSite( receiverClass, CallSiteWriter.CONSTRUCTOR, arguments, false, false, false, false); } private boolean writeAICCall(ConstructorCallExpression call) { if (!call.isUsingAnonymousInnerClass()) return false; ConstructorNode cn = call.getType().getDeclaredConstructors().get(0); OperandStack os = controller.getOperandStack(); String ownerDescriptor = prepareConstructorCall(cn); List args = makeArgumentList(call.getArguments()).getExpressions(); Parameter[] params = cn.getParameters(); for (int i=0; iJochen "blackdrag" Theodorou */ public abstract class BinaryExpressionWriter { private WriterController controller; public BinaryExpressionWriter(WriterController controller) { this.controller = controller; } protected static final int[] stdCompareCodes = { IFEQ, // COMPARE_NOT_EQUAL 120 IFNE, // COMPARE_IDENTICAL 121 IFEQ, // COMPARE_NOT_IDENTICAL 122 IFNE, // COMPARE_EQUAL 123 IFGE, // COMPARE_LESS_THAN 124 IFGT, // COMPARE_LESS_THAN_EQUAL 125 IFLE, // COMPARE_GREATER_THAN 126 IFLT, // COMPARE_GREATER_THAN_EQUAL 127 }; protected abstract int getCompareCode(); /** * writes some int standard operations. type is one of IADD, ISUB, IMUL, * IDIV or IREM * @param type the token type * @return true if a successful std operator write */ protected boolean writeStdCompare(int type, boolean simulate) { type = type-COMPARE_NOT_EQUAL; // look if really compare if (type<0||type>7) return false; if (!simulate) { MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); // operands are on the stack already int bytecode = stdCompareCodes[type]; mv.visitInsn(getCompareCode()); Label l1 = new Label(); mv.visitJumpInsn(bytecode,l1); mv.visitInsn(ICONST_1); Label l2 = new Label();; mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); operandStack.replace(ClassHelper.boolean_TYPE, 2); } return true; } protected abstract void doubleTwoOperands(MethodVisitor mv); protected abstract void removeTwoOperands(MethodVisitor mv); protected boolean writeSpaceship(int type, boolean simulate) { if (type != COMPARE_TO) return false; /* we will actually do (x < y) ? -1 : ((x == y) ? 0 : 1) which is the essence of what the call with Number would do this compiles to something along LCMP IFGE L1 ICONST_M1 GOTO L2 L1 LCMP IFNE L3 ICONST_0 GOTO L2 L3 ICONST_1 L2 since the operators are already on the stack and we don't want to load them again, we will instead duplicate them. This will require some pop actions in the branches! DUP4 (operands: L1L2L1L2) LCMP IFGE L1 (operands: L1L2) ICONST_M1 (operands: L1L2I) GOTO L2 L1 ----- (operands: L1L2) LCMP IFNE L3 (operands: -) ICONST_0 (operands: I) GOTO L2 L3 - jump from L1 branch to here (operands: -) ICONST_1 (operands: I) L2 - if jump from GOTO L2 we have LLI, but need only I - if from L3 branch we get only I this means we have to pop of LL before loading -1 since there is no DUP4 we have to do this: DUP2_X1 POP2 DUP2_X1 DUP2_X1 POP2 DUP2_X1 */ if (!simulate) { MethodVisitor mv = controller.getMethodVisitor(); // duplicate arguments doubleTwoOperands(mv); Label l1 = new Label(); mv.visitInsn(getCompareCode()); mv.visitJumpInsn(IFGE,l1); // no jump, so -1, need to pop off surplus LL removeTwoOperands(mv); mv.visitInsn(ICONST_M1); Label l2 = new Label();; mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); Label l3 = new Label(); mv.visitInsn(getCompareCode()); mv.visitJumpInsn(IFNE,l3); mv.visitInsn(ICONST_0); mv.visitJumpInsn(GOTO,l2); mv.visitLabel(l3); mv.visitInsn(ICONST_1); controller.getOperandStack().replace(ClassHelper.int_TYPE, 2); } return true; } protected abstract ClassNode getNormalOpResultType(); protected abstract int getStandardOperationBytecode(int type); protected boolean writeStdOperators(int type, boolean simulate) { type = type-PLUS; if (type<0 || type>5 || type == 3 /*DIV*/) return false; if (!simulate) { int bytecode = getStandardOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; } protected boolean writeDivision(boolean simulate) { if (!supportsDivision()) return false; if (!simulate) { int bytecode = getStandardOperationBytecode(3 /*DIV*/); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getDevisionOpResultType(), 2); } return true; } protected boolean supportsDivision() { return false; } protected abstract ClassNode getDevisionOpResultType(); protected abstract int getBitwiseOperationBytecode(int type); /** * writes some the bitwise operations. type is one of BITWISE_OR, * BITWISE_AND, BIWISE_XOR * @param type the token type * @return true if a successful bitwise operation write */ protected boolean writeBitwiseOp(int type, boolean simulate) { type = type-BITWISE_OR; if (type<0 || type>2) return false; if (!simulate) { int bytecode = getBitwiseOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; } protected abstract int getShiftOperationBytecode(int type); /** * Write shifting operations. * Type is one of LEFT_SHIFT, RIGHT_SHIFT, or RIGHT_SHIFT_UNSIGNED * * @param type the token type * @return true on a successful shift operation write */ protected boolean writeShiftOp(int type, boolean simulate) { type = type - LEFT_SHIFT; if (type < 0 || type > 2) return false; if (!simulate) { int bytecode = getShiftOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; } public boolean write(int operation, boolean simulate) { return writeStdCompare(operation, simulate) || writeSpaceship(operation, simulate) || writeStdOperators(operation, simulate) || writeBitwiseOp(operation, simulate) || writeShiftOp(operation, simulate); } protected abstract MethodCaller getArrayGetCaller(); protected ClassNode getArrayGetResultType(){ return getNormalOpResultType(); } protected abstract MethodCaller getArraySetCaller(); public boolean arrayGet(int operation, boolean simulate) { if (operation!=LEFT_SQUARE_BRACKET) return false; if (!simulate) { getArrayGetCaller().call(controller.getMethodVisitor()); } return true; } public boolean arraySet(boolean simulate) { if (!simulate) { getArraySetCaller().call(controller.getMethodVisitor()); } return true; } public boolean writePostOrPrefixMethod(int operation, boolean simulate) { if (operation!=PLUS_PLUS && operation!=MINUS_MINUS) return false; if (!simulate) { MethodVisitor mv = controller.getMethodVisitor(); if (operation==PLUS_PLUS) { writePlusPlus(mv); } else { writeMinusMinus(mv); } } return true; } protected abstract void writePlusPlus(MethodVisitor mv); protected abstract void writeMinusMinus(MethodVisitor mv); } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/OperandStack.java0000644001501200150120000006010511715031256025616 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.classgen.ClassGeneratorException; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; public class OperandStack { // type conversions private static final MethodCaller asTypeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "asType"); private static final MethodCaller castToTypeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "castToType"); private WriterController controller; private ArrayList stack = new ArrayList(); public OperandStack(WriterController wc) { this.controller = wc; } public int getStackLength() { return stack.size(); } public void popDownTo(int elements) { int last = stack.size(); MethodVisitor mv = controller.getMethodVisitor(); while (last>elements) { last--; ClassNode element = stack.remove(last); if (isTwoSlotType(element)) { mv.visitInsn(POP2); } else { mv.visitInsn(POP); } } } /** * returns true for long and double */ private boolean isTwoSlotType(ClassNode type) { return type==ClassHelper.long_TYPE || type==ClassHelper.double_TYPE; } /** * ensure last marked parameter on the stack is a primitive boolean * if mark==stack size, we assume an empty expression or statement. * was used and we will use the value given in emptyDefault as boolean * if mark==stack.size()-1 the top element will be cast to boolean using * Groovy truth. * In other cases we throw a GroovyBugError */ public void castToBool(int mark, boolean emptyDefault) { int size = stack.size(); MethodVisitor mv = controller.getMethodVisitor(); if (mark==size) { // no element, so use emptyDefault if (emptyDefault) { mv.visitIntInsn(BIPUSH, 1); } else { mv.visitIntInsn(BIPUSH, 0); } stack.add(null); } else if (mark==stack.size()-1) { ClassNode last = stack.get(size-1); // nothing to do in that case if (last == ClassHelper.boolean_TYPE) return; // not a primitive type, so call booleanUnbox if (!ClassHelper.isPrimitiveType(last)) { BytecodeHelper.unbox(mv,ClassHelper.boolean_TYPE); } else { primitive2b(mv,last); } } else { throw new GroovyBugError( "operand stack contains "+stack.size()+ " elements, but we expected only "+mark ); } stack.set(mark,ClassHelper.boolean_TYPE); } /** * convert primitive (not boolean) to boolean or byte. * type needs to be a primitive type (not checked) */ private void primitive2b(MethodVisitor mv, ClassNode type) { Label trueLabel = new Label(); Label falseLabel = new Label(); // for the various types we make first a // kind of conversion to int using a compare // operation and then handle the result common // for all cases. In case of long that is LCMP, // for int nothing is to be done if (type==ClassHelper.double_TYPE) { mv.visitInsn(DCONST_0); mv.visitInsn(DCMPL); } else if (type==ClassHelper.long_TYPE) { mv.visitInsn(LCONST_0); mv.visitInsn(LCMP); } else if (type==ClassHelper.float_TYPE) { mv.visitInsn(FCONST_0); mv.visitInsn(FCMPL); } else if (type==ClassHelper.int_TYPE) { // nothing, see comment above } mv.visitJumpInsn(IFEQ, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, trueLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(trueLabel); // other cases can be used directly } /** * remove operand stack top element using bytecode pop */ public void pop() { popDownTo(stack.size()-1); } public Label jump(int ifIns) { Label label = new Label(); jump(ifIns,label); return label; } public void jump(int ifIns, Label label) { controller.getMethodVisitor().visitJumpInsn(ifIns, label); // remove the boolean from the operand stack tracker remove(1); } /** * duplicate top element */ public void dup() { ClassNode type = getTopOperand(); stack.add(type); MethodVisitor mv = controller.getMethodVisitor(); if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) { mv.visitInsn(DUP2); } else { mv.visitInsn(DUP); } } public ClassNode box() { MethodVisitor mv = controller.getMethodVisitor(); int size = stack.size(); ClassNode type = stack.get(size-1); if (BytecodeHelper.box(mv, type)) { type = ClassHelper.getWrapper(type); BytecodeHelper.doCast(mv, type); } stack.set(size-1, type); return type; } /** * Remove amount elements from the operand stack, without using pop. * For example after a method invocation */ public void remove(int amount) { int size = stack.size(); for (int i=size-1; i>size-1-amount; i--) { try { stack.remove(i); } catch (ArrayIndexOutOfBoundsException ai) { System.err.println("index problem in "+controller.getSourceUnit().getName()); throw ai; } } } /** * push operand on stack */ public void push(ClassNode type) { stack.add(type); } /** * swap two top level operands */ public void swap() { MethodVisitor mv = controller.getMethodVisitor(); int size = stack.size(); ClassNode b = stack.get(size-1); ClassNode a = stack.get(size-2); // dup_x1: --- // dup_x2: aab -> baab // dup2_x1: abb -> bbabb // dup2_x2: aabb -> bbaabb // b = top element, a = element under b // top element at right if (isTwoSlotType(a)) { // aa if (isTwoSlotType(b)) { // aabb // aabb -> bbaa mv.visitInsn(DUP2_X2); // bbaabb mv.visitInsn(POP2); // bbaa } else { // aab -> baa mv.visitInsn(DUP_X2); // baab mv.visitInsn(POP); // baa } } else { // a if (isTwoSlotType(b)) { //abb // abb -> bba mv.visitInsn(DUP2_X1); // bbabb mv.visitInsn(POP2); // bba } else { // ab -> ba mv.visitInsn(SWAP); } } stack.set(size-1,a); stack.set(size-2,b); } /** * replace top level element with new element of given type */ public void replace(ClassNode type) { int size = stack.size(); try { if (size==0) throw new ArrayIndexOutOfBoundsException("size==0"); } catch (ArrayIndexOutOfBoundsException ai) { System.err.println("index problem in "+controller.getSourceUnit().getName()); throw ai; } stack.set(size-1, type); } /** * replace n top level elements with new element of given type */ public void replace(ClassNode type, int n) { remove(n); push(type); } /** * do Groovy cast for top level element */ public void doGroovyCast(ClassNode targetType) { doConvertAndCast(targetType,false); } public void doGroovyCast(Variable v) { ClassNode targetType = v.getOriginType(); doConvertAndCast(targetType,false); } public void doAsType(ClassNode targetType) { doConvertAndCast(targetType,true); } private void doConvertAndCast(ClassNode targetType, boolean coerce) { int size = stack.size(); try { if (size==0) throw new ArrayIndexOutOfBoundsException("size==0"); } catch (ArrayIndexOutOfBoundsException ai) { throw ai; } ClassNode top = stack.get(size-1); targetType = targetType.redirect(); if (targetType == top) return; MethodVisitor mv = controller.getMethodVisitor(); if (coerce) { if (top.isDerivedFrom(targetType)) return; box(); (new ClassExpression(targetType)).visit(controller.getAcg()); remove(1); asTypeMethod.call(mv); BytecodeHelper.doCast(mv,targetType); replace(targetType); return; } boolean primTarget = ClassHelper.isPrimitiveType(targetType); boolean primTop = ClassHelper.isPrimitiveType(top); if (primTop && primTarget) { //TODO: use jvm primitive conversions // here we box and unbox to get the goal type if (convertPrimitive(top, targetType)) { replace(targetType); return; } box(); } else if (primTop) { // top is primitive, target is not // so box and do groovy cast ClassNode boxedType = box(); castToTypeIfNecessary(boxedType, targetType); } else if (primTarget) { // top is not primitive so unbox // leave that BH#doCast later } else { castToTypeIfNecessary(top, targetType); } if (ClassHelper.isNumberType(top) && primTarget && ClassHelper.isNumberType(targetType)) { BytecodeHelper.doCastToPrimitive(mv, top, targetType); } else { BytecodeHelper.doCast(mv,targetType); } replace(targetType); } private void castToTypeIfNecessary(final ClassNode sourceType, final ClassNode targetType) { if (!sourceType.isDerivedFrom(targetType) && !sourceType.implementsInterface(targetType)) { MethodVisitor mv = controller.getMethodVisitor(); (new ClassExpression(targetType)).visit(controller.getAcg()); remove(1); castToTypeMethod.call(mv); } } private boolean convertFromInt(ClassNode target) { int convertCode = 0; if (target==ClassHelper.char_TYPE){ convertCode = I2C; } else if (target==ClassHelper.byte_TYPE){ convertCode = I2B; } else if (target==ClassHelper.short_TYPE){ convertCode = I2S; } else if (target==ClassHelper.long_TYPE){ convertCode = I2L; } else if (target==ClassHelper.float_TYPE){ convertCode = I2F; } else if (target==ClassHelper.double_TYPE){ convertCode = I2D; } else { return false; } controller.getMethodVisitor().visitInsn(convertCode); return true; } private boolean convertFromLong(ClassNode target) { MethodVisitor mv = controller.getMethodVisitor(); if (target==ClassHelper.int_TYPE){ mv.visitInsn(L2I); return true; } else if ( target==ClassHelper.char_TYPE || target==ClassHelper.byte_TYPE || target==ClassHelper.short_TYPE) { mv.visitInsn(L2I); return convertFromInt(target); } else if (target==ClassHelper.double_TYPE){ mv.visitInsn(L2D); return true; } else if (target==ClassHelper.float_TYPE){ mv.visitInsn(L2F); return true; } return false; } private boolean convertFromDouble(ClassNode target) { MethodVisitor mv = controller.getMethodVisitor(); if (target==ClassHelper.int_TYPE){ mv.visitInsn(D2I); return true; } else if ( target==ClassHelper.char_TYPE || target==ClassHelper.byte_TYPE || target==ClassHelper.short_TYPE) { mv.visitInsn(D2I); return convertFromInt(target); } else if (target==ClassHelper.long_TYPE){ mv.visitInsn(D2L); return true; } else if (target==ClassHelper.float_TYPE){ mv.visitInsn(D2F); return true; } return false; } private boolean convertFromFloat(ClassNode target) { MethodVisitor mv = controller.getMethodVisitor(); if (target==ClassHelper.int_TYPE){ mv.visitInsn(F2I); return true; } else if ( target==ClassHelper.char_TYPE || target==ClassHelper.byte_TYPE || target==ClassHelper.short_TYPE) { mv.visitInsn(F2I); return convertFromInt(target); } else if (target==ClassHelper.long_TYPE){ mv.visitInsn(F2L); return true; } else if (target==ClassHelper.double_TYPE){ mv.visitInsn(F2D); return true; } return false; } private boolean convertPrimitive(ClassNode top, ClassNode target) { if (top==target) return true; if (top==ClassHelper.int_TYPE) { return convertFromInt(target); } else if ( top==ClassHelper.char_TYPE || top==ClassHelper.byte_TYPE || top==ClassHelper.short_TYPE) { if (target==ClassHelper.int_TYPE) return true; return convertFromInt(target); } else if ( top==ClassHelper.float_TYPE) { return convertFromFloat(target); } else if ( top==ClassHelper.double_TYPE) { return convertFromDouble(target); } else if ( top==ClassHelper.long_TYPE) { return convertFromLong(target); } return false; } /** * load the constant on the operand stack. */ public void pushConstant(ConstantExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); Object value = expression.getValue(); ClassNode type = expression.getType().redirect(); boolean asPrimitive = ClassHelper.isPrimitiveType(type); if (value == null) { mv.visitInsn(ACONST_NULL); } else if (asPrimitive) { pushPrimitiveConstant(mv, value, type); } else if (value instanceof Character) { mv.visitLdcInsn(value); BytecodeHelper.box(mv, type); // does not change this.stack field contents } else if (value instanceof Number) { if (value instanceof BigDecimal) { String className = BytecodeHelper.getClassInternalName(value.getClass().getName()); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitLdcInsn(value.toString()); mv.visitMethodInsn(INVOKESPECIAL, className, "", "(Ljava/lang/String;)V"); } else if (value instanceof BigInteger) { String className = BytecodeHelper.getClassInternalName(value.getClass().getName()); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitLdcInsn(value.toString()); mv.visitMethodInsn(INVOKESPECIAL, className, "", "(Ljava/lang/String;)V"); } else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Long || value instanceof Float || value instanceof Double ) { ClassNode primType = ClassHelper.getUnwrapper(type); pushPrimitiveConstant(mv, value, primType); BytecodeHelper.box(mv, primType); // does not change this.stack field contents BytecodeHelper.doCast(mv, type); } else { mv.visitLdcInsn(value); BytecodeHelper.box(mv, ClassHelper.getUnwrapper(type)); // does not change this.stack field contents BytecodeHelper.doCast(mv, type); } } else if (value instanceof Boolean) { Boolean bool = (Boolean) value; String text = (bool.booleanValue()) ? "TRUE" : "FALSE"; mv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", text, "Ljava/lang/Boolean;"); } else if (value instanceof String) { mv.visitLdcInsn(value); } else { throw new ClassGeneratorException( "Cannot generate bytecode for constant: " + value + " of type: " + type.getName()); } push(type); } private void pushPrimitiveConstant(final MethodVisitor mv, final Object value, final ClassNode type) { boolean isInt = ClassHelper.int_TYPE.equals(type); boolean isShort = ClassHelper.short_TYPE.equals(type); boolean isByte = ClassHelper.byte_TYPE.equals(type); if (isInt || isShort || isByte) { int val = isInt?(Integer)value:isShort?(Short)value:(Byte)value; switch (val) { case 0: mv.visitInsn(ICONST_0); break; case 1: mv.visitInsn(ICONST_1); break; case 2: mv.visitInsn(ICONST_2); break; case 3: mv.visitInsn(ICONST_3); break; case 4: mv.visitInsn(ICONST_4); break; case 5: mv.visitInsn(ICONST_5); break; default: if (val>=Byte.MIN_VALUE && val<=Byte.MAX_VALUE) { mv.visitIntInsn(BIPUSH, val); } else if (val>=Short.MIN_VALUE && val<=Short.MAX_VALUE) { mv.visitIntInsn(SIPUSH, val); } else { mv.visitLdcInsn(value); } } } else if (ClassHelper.long_TYPE.equals(type)) { if ((Long)value==0L) { mv.visitInsn(LCONST_0); } else if ((Long)value==1L) { mv.visitInsn(LCONST_1); } else { mv.visitLdcInsn(value); } } else if (ClassHelper.float_TYPE.equals(type)) { if ((Float)value==0f) { mv.visitInsn(FCONST_0); } else if ((Float)value==1f) { mv.visitInsn(FCONST_1); } else if ((Float)value==2f) { mv.visitInsn(FCONST_2); } else { mv.visitLdcInsn(value); } } else if (ClassHelper.double_TYPE.equals(type)) { if ((Double)value==0d) { mv.visitInsn(DCONST_0); } else if ((Double)value==1d) { mv.visitInsn(DCONST_1); } else { mv.visitLdcInsn(value); } } else if (ClassHelper.boolean_TYPE.equals(type)) { boolean b = (Boolean) value; if (b) { mv.visitInsn(ICONST_1); } else { mv.visitInsn(ICONST_0); } } else { mv.visitLdcInsn(value); } } public void pushDynamicName(Expression name) { if (name instanceof ConstantExpression) { ConstantExpression ce = (ConstantExpression) name; Object value = ce.getValue(); if (value instanceof String) { pushConstant(ce); return; } } new CastExpression(ClassHelper.STRING_TYPE, name).visit(controller.getAcg()); } public void loadOrStoreVariable(BytecodeVariable variable, boolean useReferenceDirectly) { CompileStack compileStack = controller.getCompileStack(); if (compileStack.isLHS()) { storeVar(variable); } else { MethodVisitor mv = controller.getMethodVisitor(); int idx = variable.getIndex(); ClassNode type = variable.getType(); if (variable.isHolder()) { mv.visitVarInsn(ALOAD, idx); if (!useReferenceDirectly) { mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;"); BytecodeHelper.doCast(mv, type); push(type); } else { push(ClassHelper.REFERENCE_TYPE); } } else { load(type,idx); } } } public void storeVar(BytecodeVariable variable) { MethodVisitor mv = controller.getMethodVisitor(); int idx = variable.getIndex(); ClassNode type = variable.getType(); // value is on stack if (variable.isHolder()) { box(); mv.visitVarInsn(ALOAD, idx); mv.visitTypeInsn(CHECKCAST, "groovy/lang/Reference"); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V"); } else { doGroovyCast(type); if (type == ClassHelper.double_TYPE) { mv.visitVarInsn(DSTORE, idx); } else if (type == ClassHelper.float_TYPE) { mv.visitVarInsn(FSTORE, idx); } else if (type == ClassHelper.long_TYPE) { mv.visitVarInsn(LSTORE, idx); } else if ( type == ClassHelper.boolean_TYPE || type == ClassHelper.char_TYPE || type == ClassHelper.byte_TYPE || type == ClassHelper.int_TYPE || type == ClassHelper.short_TYPE) { mv.visitVarInsn(ISTORE, idx); } else { mv.visitVarInsn(ASTORE, idx); } } // remove RHS value from operand stack remove(1); } public void load(ClassNode type, int idx) { MethodVisitor mv = controller.getMethodVisitor(); BytecodeHelper.load(mv, type, idx); push(type); } public void pushBool(boolean inclusive) { MethodVisitor mv = controller.getMethodVisitor(); mv.visitLdcInsn(new Boolean(inclusive)); push(ClassHelper.boolean_TYPE); } public String toString() { return "OperandStack(size="+stack.size()+":"+stack.toString()+")"; } public ClassNode getTopOperand() { int size = stack.size(); try { if (size==0) throw new ArrayIndexOutOfBoundsException("size==0"); } catch (ArrayIndexOutOfBoundsException ai) { System.err.println("index problem in "+controller.getSourceUnit().getName()); throw ai; } return stack.get(size-1); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/MethodCaller.java0000644001501200150120000000514411707612046025610 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.lang.reflect.Method; import org.codehaus.groovy.classgen.ClassGeneratorException; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * A helper class to invoke methods more easily in ASM * * @author James Strachan * @version $Revision$ */ public class MethodCaller implements Opcodes { private int opcode; private String internalName; private String name; private Class theClass; private String methodDescriptor; public static MethodCaller newStatic(Class theClass, String name) { return new MethodCaller(INVOKESTATIC, theClass, name); } public static MethodCaller newInterface(Class theClass, String name) { return new MethodCaller(INVOKEINTERFACE, theClass, name); } public static MethodCaller newVirtual(Class theClass, String name) { return new MethodCaller(INVOKEVIRTUAL, theClass, name); } public MethodCaller(int opcode, Class theClass, String name) { this.opcode = opcode; this.internalName = Type.getInternalName(theClass); this.theClass = theClass; this.name = name; } public void call(MethodVisitor methodVisitor) { methodVisitor.visitMethodInsn(opcode, internalName, name, getMethodDescriptor()); } public String getMethodDescriptor() { if (methodDescriptor == null) { Method method = getMethod(); methodDescriptor = Type.getMethodDescriptor(method); } return methodDescriptor; } protected Method getMethod() { Method[] methods = theClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals(name)) { return method; } } throw new ClassGeneratorException("Could not find method: " + name + " on class: " + theClass); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/CallSiteWriter.java0000644001501200150120000004053211715031256026137 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.InterfaceHelperClassNode; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.runtime.callsite.CallSite; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; /** * This class represents non public API used by AsmClassGenerator. Don't * use this class in your code * @author Jochen Theodorou */ public class CallSiteWriter { private static final HashSet names = new HashSet(); private static final HashSet basic = new HashSet(); static { Collections.addAll(names, "plus", "minus", "multiply", "div", "compareTo", "or", "and", "xor", "intdiv", "mod", "leftShift", "rightShift", "rightShiftUnsigned"); Collections.addAll(basic, "plus", "minus", "multiply", "div"); } private static String [] sig = new String [255]; private static String getCreateArraySignature(int numberOfArguments) { if (sig[numberOfArguments] == null) { StringBuilder sb = new StringBuilder("("); for (int i = 0; i != numberOfArguments; ++i) { sb.append("Ljava/lang/Object;"); } sb.append(")[Ljava/lang/Object;"); sig[numberOfArguments] = sb.toString(); } return sig[numberOfArguments]; } private final static int MOD_PRIVSS = ACC_PRIVATE+ACC_STATIC+ACC_SYNTHETIC, MOD_PUBSS = ACC_PUBLIC+ACC_STATIC+ACC_SYNTHETIC; private final static ClassNode CALLSITE_ARRAY_NODE = ClassHelper.make(CallSite[].class); private final static String GET_CALLSITE_METHOD = "$getCallSiteArray", CALLSITE_CLASS = "org/codehaus/groovy/runtime/callsite/CallSite", CALLSITE_DESC = "[Lorg/codehaus/groovy/runtime/callsite/CallSite;", GET_CALLSITE_DESC = "()"+CALLSITE_DESC, CALLSITE_ARRAY_CLASS = "org/codehaus/groovy/runtime/callsite/CallSiteArray", GET_CALLSITEARRAY_DESC = "()Lorg/codehaus/groovy/runtime/callsite/CallSiteArray;", CALLSITE_FIELD = "$callSiteArray", REF_CLASS = "java/lang/ref/SoftReference", REF_DESC = "L"+REF_CLASS+";", METHOD_OO_DESC = "(Ljava/lang/Object;)Ljava/lang/Object;", CREATE_CSA_METHOD = "$createCallSiteArray"; public static final String CONSTRUCTOR = "<$constructor$>"; private final List callSites = new ArrayList(32); private int callSiteArrayVarIndex; private WriterController controller; public CallSiteWriter(WriterController wc) { this.controller = wc; ClassNode node = controller.getClassNode(); if(node instanceof InterfaceHelperClassNode) { InterfaceHelperClassNode ihcn = (InterfaceHelperClassNode) node; callSites.addAll(ihcn.getCallSites()); } } public void makeSiteEntry() { if (controller.isNotClinit()) { controller.getMethodVisitor().visitMethodInsn(INVOKESTATIC, controller.getInternalClassName(), GET_CALLSITE_METHOD, GET_CALLSITE_DESC); controller.getOperandStack().push(CALLSITE_ARRAY_NODE); callSiteArrayVarIndex = controller.getCompileStack().defineTemporaryVariable("$local$callSiteArray", CALLSITE_ARRAY_NODE, true); } } public void generateCallSiteArray() { if (!controller.getClassNode().isInterface()) { controller.getClassVisitor().visitField(MOD_PRIVSS, CALLSITE_FIELD, REF_DESC, null, null); generateCreateCallSiteArray(); generateGetCallSiteArray(); } } private void generateGetCallSiteArray() { int visibility = (controller.getClassNode() instanceof InterfaceHelperClassNode) ? MOD_PUBSS : MOD_PRIVSS; MethodVisitor mv = controller.getClassVisitor().visitMethod(visibility, GET_CALLSITE_METHOD, GET_CALLSITE_DESC, null, null); controller.setMethodVisitor(mv); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, controller.getInternalClassName(), "$callSiteArray", "Ljava/lang/ref/SoftReference;"); Label l0 = new Label(); mv.visitJumpInsn(IFNULL, l0); mv.visitFieldInsn(GETSTATIC, controller.getInternalClassName(), "$callSiteArray", "Ljava/lang/ref/SoftReference;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ref/SoftReference", "get", "()Ljava/lang/Object;"); mv.visitTypeInsn(CHECKCAST, "org/codehaus/groovy/runtime/callsite/CallSiteArray"); mv.visitInsn(DUP); mv.visitVarInsn(ASTORE, 0); Label l1 = new Label(); mv.visitJumpInsn(IFNONNULL, l1); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, controller.getInternalClassName(), "$createCallSiteArray", "()Lorg/codehaus/groovy/runtime/callsite/CallSiteArray;"); mv.visitVarInsn(ASTORE, 0); mv.visitTypeInsn(NEW, "java/lang/ref/SoftReference"); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/ref/SoftReference", "", "(Ljava/lang/Object;)V"); mv.visitFieldInsn(PUTSTATIC, controller.getInternalClassName(), "$callSiteArray", "Ljava/lang/ref/SoftReference;"); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "org/codehaus/groovy/runtime/callsite/CallSiteArray", "array", "[Lorg/codehaus/groovy/runtime/callsite/CallSite;"); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private void generateCreateCallSiteArray() { List callSiteInitMethods = new LinkedList(); int index = 0; int methodIndex = 0; final int size = callSites.size(); final int maxArrayInit = 5000; // create array initialization methods while (index < size) { methodIndex++; String methodName = "$createCallSiteArray_" + methodIndex; callSiteInitMethods.add(methodName); MethodVisitor mv = controller.getClassVisitor().visitMethod(MOD_PRIVSS, methodName, "([Ljava/lang/String;)V", null, null); controller.setMethodVisitor(mv); mv.visitCode(); int methodLimit = size; // check if the next block is over the max allowed if ((methodLimit - index) > maxArrayInit) { methodLimit = index + maxArrayInit; } for (; index < methodLimit; index++) { mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(index); mv.visitLdcInsn(callSites.get(index)); mv.visitInsn(AASTORE); } mv.visitInsn(RETURN); mv.visitMaxs(2,1); mv.visitEnd(); } // create base createCallSiteArray method MethodVisitor mv = controller.getClassVisitor().visitMethod(MOD_PRIVSS, CREATE_CSA_METHOD, GET_CALLSITEARRAY_DESC, null, null); controller.setMethodVisitor(mv); mv.visitCode(); mv.visitLdcInsn(size); mv.visitTypeInsn(ANEWARRAY, "java/lang/String"); mv.visitVarInsn(ASTORE, 0); for (String methodName : callSiteInitMethods) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESTATIC,controller.getInternalClassName(),methodName,"([Ljava/lang/String;)V"); } mv.visitTypeInsn(NEW, CALLSITE_ARRAY_CLASS); mv.visitInsn(DUP); controller.getAcg().visitClassExpression(new ClassExpression(controller.getClassNode())); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, CALLSITE_ARRAY_CLASS, "", "(Ljava/lang/Class;[Ljava/lang/String;)V"); mv.visitInsn(ARETURN); mv.visitMaxs(0,0); mv.visitEnd(); } private int allocateIndex(String name) { callSites.add(name); return callSites.size()-1; } private void invokeSafe(boolean safe, String unsafeMethod, String safeMethod) { String method = unsafeMethod; if (safe) method = safeMethod; controller.getMethodVisitor(). visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, method, METHOD_OO_DESC); controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE); } public void prepareCallSite(String message) { MethodVisitor mv = controller.getMethodVisitor(); if (controller.isNotClinit()) { mv.visitVarInsn(ALOAD, callSiteArrayVarIndex); } else { mv.visitMethodInsn(INVOKESTATIC, controller.getClassName(), GET_CALLSITE_METHOD, GET_CALLSITE_DESC); } final int index = allocateIndex(message); mv.visitLdcInsn(index); mv.visitInsn(AALOAD); } private void prepareSiteAndReceiver(Expression receiver, String methodName, boolean implicitThis) { prepareSiteAndReceiver(receiver, methodName, implicitThis, false); } private void prepareSiteAndReceiver(Expression receiver, String methodName, boolean implicitThis, boolean lhs) { //site prepareCallSite(methodName); // receiver CompileStack compileStack = controller.getCompileStack(); compileStack.pushImplicitThis(implicitThis); compileStack.pushLHS(lhs); receiver.visit(controller.getAcg()); controller.getOperandStack().box(); compileStack.popLHS(); compileStack.popImplicitThis(); } private void visitBoxedArgument(Expression exp) { exp.visit(controller.getAcg()); if (!(exp instanceof TupleExpression)) { // we are not in a tuple, so boxing might be missing for // this single argument call controller.getOperandStack().box(); } } public void makeInvocation(Expression receiver, String message, Expression arguments) { OperandStack operandStack = controller.getOperandStack(); int m1 = operandStack.getStackLength(); //slow Path prepareSiteAndReceiver(receiver, message, false, controller.getCompileStack().isLHS()); visitBoxedArgument(arguments); int m2 = operandStack.getStackLength(); controller.getMethodVisitor(). visitMethodInsn(INVOKEINTERFACE, "org/codehaus/groovy/runtime/callsite/CallSite", "call","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); operandStack.replace(ClassHelper.OBJECT_TYPE, m2-m1); } public void makeGroovyObjectGetPropertySite(Expression receiver, String methodName, boolean safe, boolean implicitThis) { prepareSiteAndReceiver(receiver, methodName, implicitThis); invokeSafe(safe, "callGroovyObjectGetProperty", "callGroovyObjectGetPropertySafe"); } public void makeGetPropertySite(Expression receiver, String methodName, boolean safe, boolean implicitThis) { prepareSiteAndReceiver(receiver, methodName, implicitThis); invokeSafe(safe, "callGetProperty", "callGetPropertySafe"); } public void makeCallSite(Expression receiver, String message, Expression arguments, boolean safe, boolean implicitThis, boolean callCurrent, boolean callStatic) { prepareSiteAndReceiver(receiver, message, implicitThis); CompileStack compileStack = controller.getCompileStack(); compileStack.pushImplicitThis(implicitThis); compileStack.pushLHS(false); boolean constructor = message.equals(CONSTRUCTOR); OperandStack operandStack = controller.getOperandStack(); // arguments boolean containsSpreadExpression = AsmClassGenerator.containsSpreadExpression(arguments); int numberOfArguments = containsSpreadExpression ? -1 : AsmClassGenerator.argumentSize(arguments); int operandsToReplace = 1; if (numberOfArguments > MethodCallerMultiAdapter.MAX_ARGS || containsSpreadExpression) { ArgumentListExpression ae; if (arguments instanceof ArgumentListExpression) { ae = (ArgumentListExpression) arguments; } else if (arguments instanceof TupleExpression) { TupleExpression te = (TupleExpression) arguments; ae = new ArgumentListExpression(te.getExpressions()); } else { ae = new ArgumentListExpression(); ae.addExpression(arguments); } controller.getCompileStack().pushImplicitThis(false); if (containsSpreadExpression) { numberOfArguments = -1; controller.getAcg().despreadList(ae.getExpressions(), true); } else { numberOfArguments = ae.getExpressions().size(); for (int i = 0; i < numberOfArguments; i++) { Expression argument = ae.getExpression(i); argument.visit(controller.getAcg()); operandStack.box(); if (argument instanceof CastExpression) controller.getAcg().loadWrapper(argument); } operandsToReplace += numberOfArguments; } controller.getCompileStack().popImplicitThis(); } controller.getCompileStack().popLHS(); controller.getCompileStack().popImplicitThis(); MethodVisitor mv = controller.getMethodVisitor(); if (numberOfArguments > 4) { final String createArraySignature = getCreateArraySignature(numberOfArguments); mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/ArrayUtil", "createArray", createArraySignature); //TODO: use pregenerated Object[] operandStack.replace(ClassHelper.OBJECT_TYPE.makeArray(),numberOfArguments); operandsToReplace = operandsToReplace-numberOfArguments+1; } final String desc = getDescForParamNum(numberOfArguments); if (callStatic) { mv.visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, "callStatic", "(Ljava/lang/Class;" + desc); } else if (constructor) { mv.visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, "callConstructor", "(Ljava/lang/Object;" + desc); } else if (callCurrent) { mv.visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, "callCurrent", "(Lgroovy/lang/GroovyObject;" + desc); } else if (safe) { mv.visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, "callSafe", "(Ljava/lang/Object;" + desc); } else { mv.visitMethodInsn(INVOKEINTERFACE, CALLSITE_CLASS, "call", "(Ljava/lang/Object;" + desc); } operandStack.replace(ClassHelper.OBJECT_TYPE,operandsToReplace); } private static String getDescForParamNum(int numberOfArguments) { switch (numberOfArguments) { case 0: return ")Ljava/lang/Object;"; case 1: return "Ljava/lang/Object;)Ljava/lang/Object;"; case 2: return "Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"; case 3: return "Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"; case 4: return "Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"; default: return "[Ljava/lang/Object;)Ljava/lang/Object;"; } } public List getCallSites() { return callSites; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/StatementWriter.java0000644001501200150120000005567511715031256026421 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.Iterator; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ClosureListExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.EmptyExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.classgen.asm.CompileStack.BlockRecorder; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; public class StatementWriter { // iterator private static final MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next"); private static final MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext"); private WriterController controller; public StatementWriter(WriterController controller) { this.controller = controller; } protected void writeStatementLabel(Statement statement) { String name = statement.getStatementLabel(); if (name != null) { Label label = controller.getCompileStack().createLocalLabel(name); controller.getMethodVisitor().visitLabel(label); } } public void writeBlockStatement(BlockStatement block) { CompileStack compileStack = controller.getCompileStack(); //GROOVY-4505 use no line number information for the block writeStatementLabel(block); int mark = controller.getOperandStack().getStackLength(); compileStack.pushVariableScope(block.getVariableScope()); for (Statement statement : block.getStatements()) { statement.visit(controller.getAcg()); } compileStack.pop(); controller.getOperandStack().popDownTo(mark); } public void writeForStatement(ForStatement loop) { Parameter loopVar = loop.getVariable(); if (loopVar == ForStatement.FOR_LOOP_DUMMY) { writeForLoopWithClosureList(loop); } else { writeForInLoop(loop); } } protected void writeIteratorHasNext(MethodVisitor mv) { iteratorHasNextMethod.call(mv); } protected void writeIteratorNext(MethodVisitor mv) { iteratorNextMethod.call(mv); } protected void writeForInLoop(ForStatement loop) { controller.getAcg().onLineNumber(loop,"visitForLoop"); writeStatementLabel(loop); CompileStack compileStack = controller.getCompileStack(); MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); compileStack.pushLoop(loop.getVariableScope(), loop.getStatementLabel()); // Declare the loop counter. BytecodeVariable variable = compileStack.defineVariable(loop.getVariable(), false); // Then get the iterator and generate the loop control MethodCallExpression iterator = new MethodCallExpression(loop.getCollectionExpression(), "iterator", new ArgumentListExpression()); iterator.visit(controller.getAcg()); operandStack.doGroovyCast(ClassHelper.Iterator_TYPE); final int iteratorIdx = compileStack.defineTemporaryVariable("iterator", ClassHelper.Iterator_TYPE, true); Label continueLabel = compileStack.getContinueLabel(); Label breakLabel = compileStack.getBreakLabel(); mv.visitLabel(continueLabel); mv.visitVarInsn(ALOAD, iteratorIdx); writeIteratorHasNext(mv); // note: ifeq tests for ==0, a boolean is 0 if it is false mv.visitJumpInsn(IFEQ, breakLabel); mv.visitVarInsn(ALOAD, iteratorIdx); writeIteratorNext(mv); operandStack.push(ClassHelper.OBJECT_TYPE); operandStack.storeVar(variable); // Generate the loop body loop.getLoopBlock().visit(controller.getAcg()); mv.visitJumpInsn(GOTO, continueLabel); mv.visitLabel(breakLabel); compileStack.pop(); } protected void writeForLoopWithClosureList(ForStatement loop) { controller.getAcg().onLineNumber(loop,"visitForLoop"); writeStatementLabel(loop); MethodVisitor mv = controller.getMethodVisitor(); controller.getCompileStack().pushLoop(loop.getVariableScope(), loop.getStatementLabel()); ClosureListExpression clExpr = (ClosureListExpression) loop.getCollectionExpression(); controller.getCompileStack().pushVariableScope(clExpr.getVariableScope()); List expressions = clExpr.getExpressions(); int size = expressions.size(); // middle element is condition, lower half is init, higher half is increment int condIndex = (size - 1) / 2; // visit init for (int i = 0; i < condIndex; i++) { visitExpressionOrStatement(expressions.get(i)); } Label continueLabel = controller.getCompileStack().getContinueLabel(); Label breakLabel = controller.getCompileStack().getBreakLabel(); Label cond = new Label(); mv.visitLabel(cond); // visit condition leave boolean on stack { Expression condExpr = (Expression) expressions.get(condIndex); int mark = controller.getOperandStack().getStackLength(); condExpr.visit(controller.getAcg()); controller.getOperandStack().castToBool(mark,true); } // jump if we don't want to continue // note: ifeq tests for ==0, a boolean is 0 if it is false controller.getOperandStack().jump(IFEQ, breakLabel); // Generate the loop body loop.getLoopBlock().visit(controller.getAcg()); // visit increment mv.visitLabel(continueLabel); for (int i = condIndex + 1; i < size; i++) { visitExpressionOrStatement(expressions.get(i)); } // jump to test the condition again mv.visitJumpInsn(GOTO, cond); // loop end mv.visitLabel(breakLabel); controller.getCompileStack().pop(); controller.getCompileStack().pop(); } private void visitExpressionOrStatement(Object o) { if (o == EmptyExpression.INSTANCE) return; if (o instanceof Expression) { Expression expr = (Expression) o; int mark = controller.getOperandStack().getStackLength(); expr.visit(controller.getAcg()); controller.getOperandStack().popDownTo(mark); } else { ((Statement) o).visit(controller.getAcg()); } } public void writeWhileLoop(WhileStatement loop) { controller.getAcg().onLineNumber(loop,"visitWhileLoop"); writeStatementLabel(loop); MethodVisitor mv = controller.getMethodVisitor(); controller.getCompileStack().pushLoop(loop.getStatementLabel()); Label continueLabel = controller.getCompileStack().getContinueLabel(); Label breakLabel = controller.getCompileStack().getBreakLabel(); mv.visitLabel(continueLabel); Expression bool = loop.getBooleanExpression(); boolean boolHandled = false; if (bool instanceof ConstantExpression) { ConstantExpression constant = (ConstantExpression) bool; if (constant.getValue()==Boolean.TRUE) { boolHandled = true; // do nothing } else if (constant.getValue()==Boolean.FALSE) { boolHandled = true; mv.visitJumpInsn(GOTO, breakLabel); } } if(!boolHandled) { bool.visit(controller.getAcg()); controller.getOperandStack().jump(IFEQ, breakLabel); } loop.getLoopBlock().visit(controller.getAcg()); mv.visitJumpInsn(GOTO, continueLabel); mv.visitLabel(breakLabel); controller.getCompileStack().pop(); } public void writeDoWhileLoop(DoWhileStatement loop) { controller.getAcg().onLineNumber(loop,"visitDoWhileLoop"); writeStatementLabel(loop); MethodVisitor mv = controller.getMethodVisitor(); controller.getCompileStack().pushLoop(loop.getStatementLabel()); Label breakLabel = controller.getCompileStack().getBreakLabel(); Label continueLabel = controller.getCompileStack().getContinueLabel(); mv.visitLabel(continueLabel); loop.getLoopBlock().visit(controller.getAcg()); loop.getBooleanExpression().visit(controller.getAcg()); controller.getOperandStack().jump(IFEQ, continueLabel); mv.visitLabel(breakLabel); controller.getCompileStack().pop(); } public void writeIfElse(IfStatement ifElse) { controller.getAcg().onLineNumber(ifElse,"visitIfElse"); writeStatementLabel(ifElse); MethodVisitor mv = controller.getMethodVisitor(); ifElse.getBooleanExpression().visit(controller.getAcg()); Label l0 = controller.getOperandStack().jump(IFEQ); // if-else is here handled as a special version // of a boolean expression controller.getCompileStack().pushBooleanExpression(); ifElse.getIfBlock().visit(controller.getAcg()); controller.getCompileStack().pop(); Label l1 = new Label(); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l0); controller.getCompileStack().pushBooleanExpression(); ifElse.getElseBlock().visit(controller.getAcg()); controller.getCompileStack().pop(); mv.visitLabel(l1); } public void writeTryCatchFinally(TryCatchStatement statement) { controller.getAcg().onLineNumber(statement, "visitTryCatchFinally"); writeStatementLabel(statement); MethodVisitor mv = controller.getMethodVisitor(); CompileStack compileStack = controller.getCompileStack(); OperandStack operandStack = controller.getOperandStack(); Statement tryStatement = statement.getTryStatement(); final Statement finallyStatement = statement.getFinallyStatement(); // start try block, label needed for exception table Label tryStart = new Label(); mv.visitLabel(tryStart); BlockRecorder tryBlock = makeBlockRecorder(finallyStatement); tryBlock.startRange(tryStart); tryStatement.visit(controller.getAcg()); // goto finally part Label finallyStart = new Label(); mv.visitJumpInsn(GOTO, finallyStart); Label tryEnd = new Label(); mv.visitLabel(tryEnd); tryBlock.closeRange(tryEnd); // pop for "makeBlockRecorder(finallyStatement)" controller.getCompileStack().pop(); BlockRecorder catches = makeBlockRecorder(finallyStatement); for (CatchStatement catchStatement : statement.getCatchStatements()) { ClassNode exceptionType = catchStatement.getExceptionType(); String exceptionTypeInternalName = BytecodeHelper.getClassInternalName(exceptionType); // start catch block, label needed for exception table Label catchStart = new Label(); mv.visitLabel(catchStart); catches.startRange(catchStart); // create exception variable and store the exception Parameter exceptionVariable = catchStatement.getVariable(); compileStack.pushState(); compileStack.defineVariable(exceptionVariable, true); // handle catch body catchStatement.visit(controller.getAcg()); // place holder to avoid problems with empty catch blocks mv.visitInsn(NOP); // pop for the variable controller.getCompileStack().pop(); // end of catch Label catchEnd = new Label(); mv.visitLabel(catchEnd); catches.closeRange(catchEnd); // goto finally start mv.visitJumpInsn(GOTO, finallyStart); compileStack.writeExceptionTable(tryBlock, catchStart, exceptionTypeInternalName); } // Label used to handle exceptions in catches and regularly // visited finals. Label catchAny = new Label(); // add "catch any" block to exception table for try part we do this // after the exception blocks, because else this one would supersede // any of those otherwise compileStack.writeExceptionTable(tryBlock, catchAny, null); // same for the catch parts compileStack.writeExceptionTable(catches, catchAny, null); // pop for "makeBlockRecorder(catches)" compileStack.pop(); // start finally mv.visitLabel(finallyStart); finallyStatement.visit(controller.getAcg()); mv.visitInsn(NOP); //** // goto after all-catching block Label skipCatchAll = new Label(); mv.visitJumpInsn(GOTO, skipCatchAll); // start a block catching any Exception mv.visitLabel(catchAny); //store exception //TODO: maybe define a Throwable and use it here instead of Object operandStack.push(ClassHelper.OBJECT_TYPE); int anyExceptionIndex = compileStack.defineTemporaryVariable("exception", true); finallyStatement.visit(controller.getAcg()); // load the exception and rethrow it mv.visitVarInsn(ALOAD, anyExceptionIndex); mv.visitInsn(ATHROW); mv.visitLabel(skipCatchAll); } private BlockRecorder makeBlockRecorder(final Statement finallyStatement) { final BlockRecorder block = new BlockRecorder(); Runnable tryRunner = new Runnable() { public void run() { controller.getCompileStack().pushBlockRecorderVisit(block); finallyStatement.visit(controller.getAcg()); controller.getCompileStack().popBlockRecorderVisit(block); } }; block.excludedStatement = tryRunner; controller.getCompileStack().pushBlockRecorder(block); return block; } public void writeSwitch(SwitchStatement statement) { controller.getAcg().onLineNumber(statement, "visitSwitch"); writeStatementLabel(statement); statement.getExpression().visit(controller.getAcg()); // switch does not have a continue label. use its parent's for continue Label breakLabel = controller.getCompileStack().pushSwitch(); int switchVariableIndex = controller.getCompileStack().defineTemporaryVariable("switch", true); List caseStatements = statement.getCaseStatements(); int caseCount = caseStatements.size(); Label[] labels = new Label[caseCount + 1]; for (int i = 0; i < caseCount; i++) { labels[i] = new Label(); } int i = 0; for (Iterator iter = caseStatements.iterator(); iter.hasNext(); i++) { CaseStatement caseStatement = (CaseStatement) iter.next(); writeCaseStatement(caseStatement, switchVariableIndex, labels[i], labels[i + 1]); } statement.getDefaultStatement().visit(controller.getAcg()); controller.getMethodVisitor().visitLabel(breakLabel); controller.getCompileStack().pop(); } protected void writeCaseStatement( CaseStatement statement, int switchVariableIndex, Label thisLabel, Label nextLabel) { controller.getAcg().onLineNumber(statement, "visitCaseStatement"); MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); mv.visitVarInsn(ALOAD, switchVariableIndex); statement.getExpression().visit(controller.getAcg()); operandStack.box(); controller.getBinaryExpHelper().getIsCaseMethod().call(mv); operandStack.replace(ClassHelper.boolean_TYPE); Label l0 = controller.getOperandStack().jump(IFEQ); mv.visitLabel(thisLabel); statement.getCode().visit(controller.getAcg()); // now if we don't finish with a break we need to jump past // the next comparison if (nextLabel != null) { mv.visitJumpInsn(GOTO, nextLabel); } mv.visitLabel(l0); } public void writeBreak(BreakStatement statement) { controller.getAcg().onLineNumber(statement, "visitBreakStatement"); writeStatementLabel(statement); String name = statement.getLabel(); Label breakLabel = controller.getCompileStack().getNamedBreakLabel(name); controller.getCompileStack().applyFinallyBlocks(breakLabel, true); controller.getMethodVisitor().visitJumpInsn(GOTO, breakLabel); } public void writeContinue(ContinueStatement statement) { controller.getAcg().onLineNumber(statement, "visitContinueStatement"); writeStatementLabel(statement); String name = statement.getLabel(); Label continueLabel = controller.getCompileStack().getContinueLabel(); if (name != null) continueLabel = controller.getCompileStack().getNamedContinueLabel(name); controller.getCompileStack().applyFinallyBlocks(continueLabel, false); controller.getMethodVisitor().visitJumpInsn(GOTO, continueLabel); } public void writeSynchronized(SynchronizedStatement statement) { controller.getAcg().onLineNumber(statement, "visitSynchronizedStatement"); writeStatementLabel(statement); final MethodVisitor mv = controller.getMethodVisitor(); CompileStack compileStack = controller.getCompileStack(); statement.getExpression().visit(controller.getAcg()); controller.getOperandStack().box(); final int index = compileStack.defineTemporaryVariable("synchronized", ClassHelper.OBJECT_TYPE, true); final Label synchronizedStart = new Label(); final Label synchronizedEnd = new Label(); final Label catchAll = new Label(); mv.visitVarInsn(ALOAD, index); mv.visitInsn(MONITORENTER); mv.visitLabel(synchronizedStart); // place holder for "empty" synchronized blocks, for example // if there is only a break/continue. mv.visitInsn(NOP); Runnable finallyPart = new Runnable() { public void run() { mv.visitVarInsn(ALOAD, index); mv.visitInsn(MONITOREXIT); } }; BlockRecorder fb = new BlockRecorder(finallyPart); fb.startRange(synchronizedStart); compileStack.pushBlockRecorder(fb); statement.getCode().visit(controller.getAcg()); fb.closeRange(catchAll); compileStack.writeExceptionTable(fb, catchAll, null); compileStack.pop(); //pop fb finallyPart.run(); mv.visitJumpInsn(GOTO, synchronizedEnd); mv.visitLabel(catchAll); finallyPart.run(); mv.visitInsn(ATHROW); mv.visitLabel(synchronizedEnd); } public void writeAssert(AssertStatement statement) { controller.getAcg().onLineNumber(statement, "visitAssertStatement"); writeStatementLabel(statement); controller.getAssertionWriter().writeAssertStatement(statement); } public void writeThrow(ThrowStatement statement) { controller.getAcg().onLineNumber(statement, "visitThrowStatement"); writeStatementLabel(statement); MethodVisitor mv = controller.getMethodVisitor(); statement.getExpression().visit(controller.getAcg()); // we should infer the type of the exception from the expression mv.visitTypeInsn(CHECKCAST, "java/lang/Throwable"); mv.visitInsn(ATHROW); controller.getOperandStack().remove(1); } public void writeReturn(ReturnStatement statement) { controller.getAcg().onLineNumber(statement, "visitReturnStatement"); writeStatementLabel(statement); MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); ClassNode returnType = controller.getReturnType(); if (returnType == ClassHelper.VOID_TYPE) { if (!(statement.isReturningNullOrVoid())) { //TODO: move to Verifier controller.getAcg().throwException("Cannot use return statement with an expression on a method that returns void"); } controller.getCompileStack().applyBlockRecorder(); mv.visitInsn(RETURN); return; } Expression expression = statement.getExpression(); expression.visit(controller.getAcg()); if (controller.getCompileStack().hasBlockRecorder()) { ClassNode type = operandStack.getTopOperand(); // value is always saved in boxed form, so no need to have a special load routine here int returnValueIdx = controller.getCompileStack().defineTemporaryVariable("returnValue", type, true); controller.getCompileStack().applyBlockRecorder(); operandStack.load(type, returnValueIdx); } operandStack.doGroovyCast(returnType); BytecodeHelper.doReturn(mv, returnType); operandStack.remove(1); } public void writeExpressionStatement(ExpressionStatement statement) { controller.getAcg().onLineNumber(statement, "visitExpressionStatement: " + statement.getExpression().getClass().getName()); writeStatementLabel(statement); Expression expression = statement.getExpression(); int mark = controller.getOperandStack().getStackLength(); expression.visit(controller.getAcg()); controller.getOperandStack().popDownTo(mark); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/OptimizingStatementWriter.java0000644001501200150120000010173411707612046030462 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.LinkedList; import java.util.List; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; import static org.codehaus.groovy.classgen.asm.BinaryExpressionMultiTypeDispatcher.*; import static org.codehaus.groovy.ast.ClassHelper.*; import static org.codehaus.groovy.ast.tools.WideningCategories.*; /** * A class to write out the optimized statements * @author Jochen "blackdrag" Theodorou */ public class OptimizingStatementWriter extends StatementWriter { private static class FastPathData { private Label pathStart = new Label(); private Label afterPath = new Label(); } public static class ClassNodeSkip{} public static class StatementMeta { private boolean optimize=false; protected MethodNode target; protected ClassNode type; protected boolean[] involvedTypes = new boolean[typeMapKeyNames.length]; public void chainInvolvedTypes(OptimizeFlagsCollector opt) { for (int i=0; i can do fast path if (meta==null || meta.optimize==false) return false; // fastPathBlocked -> slow path if (fastPathBlocked) return false; // controller.isFastPath() -> fastPath if (controller.isFastPath()) return false; return true; } @Override public void writeReturn(ReturnStatement statement) { if (controller.isFastPath()) { super.writeReturn(statement); } else { StatementMeta meta = (StatementMeta) statement.getNodeMetaData(StatementMeta.class); if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) { FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeReturn(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData==null) return; writeFastPathPrelude(fastPathData); super.writeReturn(statement); writeFastPathEpilogue(fastPathData); } else { super.writeReturn(statement); } } } @Override public void writeExpressionStatement(ExpressionStatement statement) { if (controller.isFastPath()) { super.writeExpressionStatement(statement); } else { StatementMeta meta = (StatementMeta) statement.getNodeMetaData(StatementMeta.class); // we have to have handle DelcarationExpressions special, since their // entry should be outside the optimization path, we have to do that of // course only if we are actually going to do two different paths, // otherwise it is not needed // // there are several cases to be considered now. // (1) no fast path possible, so just do super // (2) fast path possible, and at path split point (meaning not in // fast path and not in slow path). Here we have to extract the // Declaration and replace by an assignment // (3) fast path possible and in slow or fastPath. Nothing to do here. // // the only case we need to handle is then (2). if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) { FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeExpressionStatement(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData==null) return; writeFastPathPrelude(fastPathData); super.writeExpressionStatement(statement); writeFastPathEpilogue(fastPathData); } else { super.writeExpressionStatement(statement); } } } private boolean writeDeclarationExtraction(Statement statement) { Expression ex = null; if (statement instanceof ReturnStatement) { ReturnStatement rs = (ReturnStatement) statement; ex = rs.getExpression(); } else if (statement instanceof ExpressionStatement) { ExpressionStatement es = (ExpressionStatement) statement; ex = es.getExpression(); } else { throw new GroovyBugError("unknown statement type :"+statement.getClass()); } if (!(ex instanceof DeclarationExpression)) return true; DeclarationExpression declaration = (DeclarationExpression) ex; ex = declaration.getLeftExpression(); if (ex instanceof TupleExpression) return false; // do declaration controller.getCompileStack().defineVariable(declaration.getVariableExpression(), false); // change statement to do assignment only BinaryExpression assignment = new BinaryExpression( declaration.getLeftExpression(), declaration.getOperation(), declaration.getRightExpression()); assignment.setSourcePosition(declaration); assignment.copyNodeMetaData(declaration); // replace statement code if (statement instanceof ReturnStatement) { ReturnStatement rs = (ReturnStatement) statement; rs.setExpression(assignment); } else if (statement instanceof ExpressionStatement) { ExpressionStatement es = (ExpressionStatement) statement; es.setExpression(assignment); } else { throw new GroovyBugError("unknown statement type :"+statement.getClass()); } return true; } public static void setNodeMeta(TypeChooser chooser, ClassNode classNode) { if (classNode.getNodeMetaData(ClassNodeSkip.class)!=null) return; new OptVisitor(chooser).visitClass(classNode); } private static StatementMeta addMeta(ASTNode node) { StatementMeta metaOld = (StatementMeta) node.getNodeMetaData(StatementMeta.class); StatementMeta meta = metaOld; if (meta==null) meta = new StatementMeta(); meta.optimize = true; if (metaOld==null) node.setNodeMetaData(StatementMeta.class, meta); return meta; } private static StatementMeta addMeta(ASTNode node, OptimizeFlagsCollector opt) { StatementMeta meta = addMeta(node); meta.chainInvolvedTypes(opt); return meta; } private static class OptimizeFlagsCollector { private static class OptimizeFlagsEntry { private boolean canOptimize = false; private boolean shouldOptimize = false; private boolean[] involvedTypes = new boolean[typeMapKeyNames.length]; } private OptimizeFlagsEntry current = new OptimizeFlagsEntry(); private LinkedList olderEntries = new LinkedList(); public void push() { olderEntries.addLast(current); current = new OptimizeFlagsEntry(); } public void pop(boolean propagateFlags){ OptimizeFlagsEntry old = current; current = olderEntries.removeLast(); if (propagateFlags) { chainCanOptimize(old.canOptimize); chainShouldOptimize(old.shouldOptimize); for (int i=0; i", call.getArguments(), false); } private void setMethodTarget(Expression expression, String name, Expression callArgs, boolean isMethod) { if (name==null) return; if (!optimizeMethodCall) return; if (AsmClassGenerator.containsSpreadExpression(callArgs)) return; // find method call target Parameter[] paraTypes = null; if (callArgs instanceof ArgumentListExpression) { ArgumentListExpression args = (ArgumentListExpression) callArgs; int size = args.getExpressions().size(); paraTypes = new Parameter[size]; int i=0; for (Expression exp: args.getExpressions()) { ClassNode type = typeChooser.resolveType(exp, node); if (!validTypeForCall(type)) return; paraTypes[i] = new Parameter(type,""); i++; } } else { ClassNode type = typeChooser.resolveType(callArgs, node); if (!validTypeForCall(type)) return; paraTypes = new Parameter[]{new Parameter(type,"")}; } MethodNode target; ClassNode type; if (isMethod) { target = node.getMethod(name, paraTypes); if (target==null) return; if (!target.getDeclaringClass().equals(node)) return; if (scope.isInStaticContext() && !target.isStatic()) return; type = target.getReturnType().redirect(); } else { type = expression.getType(); target = selectConstructor(type, paraTypes); if (target==null) return; } StatementMeta meta = addMeta(expression); meta.target = target; meta.type = type; opt.chainShouldOptimize(true); } private static MethodNode selectConstructor(ClassNode node, Parameter[] paraTypes) { List cl = node.getDeclaredConstructors(); MethodNode res = null; for (ConstructorNode cn : cl) { if (parametersEqual(cn.getParameters(), paraTypes)) { res = cn; break; } } if (res !=null && res.isPublic()) return res; return null; } private static boolean parametersEqual(Parameter[] a, Parameter[] b) { if (a.length == b.length) { boolean answer = true; for (int i = 0; i < a.length; i++) { if (!a[i].getType().equals(b[i].getType())) { answer = false; break; } } return answer; } return false; } private static boolean validTypeForCall(ClassNode type) { // do call only for final classes and primitive types if (isPrimitiveType(type)) return true; if ((type.getModifiers() & ACC_FINAL)>0) return true; return false; } @Override public void visitClosureExpression(ClosureExpression expression) { return; } @Override public void visitForLoop(ForStatement statement) { opt.push(); super.visitForLoop(statement); if (opt.shouldOptimize()) addMeta(statement,opt); opt.pop(opt.shouldOptimize()); } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BytecodeHelper.java0000644001501200150120000005173211715031256026144 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * A helper class for bytecode generation with AsmClassGenerator. * * @author James Strachan * @author Bing Ran * @author Jochen Theodorou * @version $Revision$ */ public class BytecodeHelper implements Opcodes { private static String DTT_CLASSNAME = BytecodeHelper.getClassInternalName(DefaultTypeTransformation.class.getName()); public static String getClassInternalName(ClassNode t) { if (t.isPrimaryClassNode()) { if (t.isArray()) return "[L"+getClassInternalName(t.getComponentType())+";"; return getClassInternalName(t.getName()); } return getClassInternalName(t.getTypeClass()); } public static String getClassInternalName(Class t) { return org.objectweb.asm.Type.getInternalName(t); } /** * @return the ASM internal name of the type */ public static String getClassInternalName(String name) { return name.replace('.', '/'); } public static String getMethodDescriptor(ClassNode returnType, Parameter[] parameters) { StringBuffer buffer = new StringBuffer("("); for (int i = 0; i < parameters.length; i++) { buffer.append(getTypeDescription(parameters[i].getType())); } buffer.append(")"); buffer.append(getTypeDescription(returnType)); return buffer.toString(); } /** * @return the ASM method type descriptor */ public static String getMethodDescriptor(Class returnType, Class[] paramTypes) { // lets avoid class loading StringBuffer buffer = new StringBuffer("("); for (int i = 0; i < paramTypes.length; i++) { buffer.append(getTypeDescription(paramTypes[i])); } buffer.append(")"); buffer.append(getTypeDescription(returnType)); return buffer.toString(); } public static String getTypeDescription(Class c) { return org.objectweb.asm.Type.getDescriptor(c); } /** * array types are special: * eg.: String[]: classname: [Ljava.lang.String; * Object: classname: java.lang.Object * int[] : classname: [I * unlike getTypeDescription '.' is not replaced by '/'. * it seems that makes problems for * the class loading if '.' is replaced by '/' * * @return the ASM type description for class loading */ public static String getClassLoadingTypeDescription(ClassNode c) { StringBuffer buf = new StringBuffer(); boolean array = false; while (true) { if (c.isArray()) { buf.append('['); c = c.getComponentType(); array = true; } else { if (ClassHelper.isPrimitiveType(c)) { buf.append(getTypeDescription(c)); } else { if (array) buf.append('L'); buf.append(c.getName()); if (array) buf.append(';'); } return buf.toString(); } } } /** * array types are special: * eg.: String[]: classname: [Ljava/lang/String; * int[]: [I * * @return the ASM type description */ public static String getTypeDescription(ClassNode c) { return getTypeDescription(c, true); } /** * array types are special: * eg.: String[]: classname: [Ljava/lang/String; * int[]: [I * * @return the ASM type description */ private static String getTypeDescription(ClassNode c, boolean end) { StringBuffer buf = new StringBuffer(); ClassNode d = c; while (true) { if (ClassHelper.isPrimitiveType(d)) { char car; if (d == ClassHelper.int_TYPE) { car = 'I'; } else if (d == ClassHelper.VOID_TYPE) { car = 'V'; } else if (d == ClassHelper.boolean_TYPE) { car = 'Z'; } else if (d == ClassHelper.byte_TYPE) { car = 'B'; } else if (d == ClassHelper.char_TYPE) { car = 'C'; } else if (d == ClassHelper.short_TYPE) { car = 'S'; } else if (d == ClassHelper.double_TYPE) { car = 'D'; } else if (d == ClassHelper.float_TYPE) { car = 'F'; } else /* long */ { car = 'J'; } buf.append(car); return buf.toString(); } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } if (end) buf.append(';'); return buf.toString(); } } } /** * @return an array of ASM internal names of the type */ public static String[] getClassInternalNames(ClassNode[] names) { int size = names.length; String[] answer = new String[size]; for (int i = 0; i < size; i++) { answer[i] = getClassInternalName(names[i]); } return answer; } public static void pushConstant(MethodVisitor mv, int value) { switch (value) { case 0: mv.visitInsn(ICONST_0); break; case 1: mv.visitInsn(ICONST_1); break; case 2: mv.visitInsn(ICONST_2); break; case 3: mv.visitInsn(ICONST_3); break; case 4: mv.visitInsn(ICONST_4); break; case 5: mv.visitInsn(ICONST_5); break; default: if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { mv.visitIntInsn(BIPUSH, value); } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { mv.visitIntInsn(SIPUSH, value); } else { mv.visitLdcInsn(Integer.valueOf(value)); } } } /** * negate a boolean on stack. true->false, false->true */ public static void negateBoolean(MethodVisitor mv) { // code to negate the primitive boolean Label endLabel = new Label(); Label falseLabel = new Label(); mv.visitJumpInsn(IFNE, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, endLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(endLabel); } /** * load a message on the stack and remove it right away. Good for put a mark in the generated bytecode for debugging purpose. * * @param msg */ /*public void mark(String msg) { mv.visitLdcInsn(msg); mv.visitInsn(POP); }*/ /** * returns a name that Class.forName() can take. Notably for arrays: * [I, [Ljava.lang.String; etc * Regular object type: java.lang.String * * @param name */ public static String formatNameForClassLoading(String name) { if (name.equals("int") || name.equals("long") || name.equals("short") || name.equals("float") || name.equals("double") || name.equals("byte") || name.equals("char") || name.equals("boolean") || name.equals("void") ) { return name; } if (name == null) { return "java.lang.Object;"; } if (name.startsWith("[")) { return name.replace('/', '.'); } if (name.startsWith("L")) { name = name.substring(1); if (name.endsWith(";")) { name = name.substring(0, name.length() - 1); } return name.replace('/', '.'); } String prefix = ""; if (name.endsWith("[]")) { // todo need process multi prefix = "["; name = name.substring(0, name.length() - 2); if (name.equals("int")) { return prefix + "I"; } else if (name.equals("long")) { return prefix + "J"; } else if (name.equals("short")) { return prefix + "S"; } else if (name.equals("float")) { return prefix + "F"; } else if (name.equals("double")) { return prefix + "D"; } else if (name.equals("byte")) { return prefix + "B"; } else if (name.equals("char")) { return prefix + "C"; } else if (name.equals("boolean")) { return prefix + "Z"; } else { return prefix + "L" + name.replace('/', '.') + ";"; } } return name.replace('/', '.'); } /*public void dup() { mv.visitInsn(DUP); }*/ public static void doReturn(MethodVisitor mv, ClassNode returnType) { if (returnType == ClassHelper.double_TYPE) { mv.visitInsn(DRETURN); } else if (returnType == ClassHelper.float_TYPE) { mv.visitInsn(FRETURN); } else if (returnType == ClassHelper.long_TYPE) { mv.visitInsn(LRETURN); } else if ( returnType == ClassHelper.boolean_TYPE || returnType == ClassHelper.char_TYPE || returnType == ClassHelper.byte_TYPE || returnType == ClassHelper.int_TYPE || returnType == ClassHelper.short_TYPE) { //byte,short,boolean,int are all IRETURN mv.visitInsn(IRETURN); } else if (returnType == ClassHelper.VOID_TYPE) { mv.visitInsn(RETURN); } else { mv.visitInsn(ARETURN); } } private static boolean hasGenerics(Parameter[] param) { if (param.length == 0) return false; for (int i = 0; i < param.length; i++) { ClassNode type = param[i].getType(); if (hasGenerics(type)) return true; } return false; } private static boolean hasGenerics(ClassNode type) { return type.isArray() ? hasGenerics(type.getComponentType()) : type.getGenericsTypes() != null; } public static String getGenericsMethodSignature(MethodNode node) { GenericsType[] generics = node.getGenericsTypes(); Parameter[] param = node.getParameters(); ClassNode returnType = node.getReturnType(); if (generics == null && !hasGenerics(param) && !hasGenerics(returnType)) return null; StringBuffer ret = new StringBuffer(100); getGenericsTypeSpec(ret, generics); GenericsType[] paramTypes = new GenericsType[param.length]; for (int i = 0; i < param.length; i++) { ClassNode pType = param[i].getType(); if (pType.getGenericsTypes() == null || !pType.isGenericsPlaceHolder()) { paramTypes[i] = new GenericsType(pType); } else { paramTypes[i] = pType.getGenericsTypes()[0]; } } addSubTypes(ret, paramTypes, "(", ")"); addSubTypes(ret, new GenericsType[]{new GenericsType(returnType)}, "", ""); return ret.toString(); } private static boolean usesGenericsInClassSignature(ClassNode node) { if (!node.isUsingGenerics()) return false; if (hasGenerics(node)) return true; ClassNode sclass = node.getUnresolvedSuperClass(false); if (sclass.isUsingGenerics()) return true; ClassNode[] interfaces = node.getInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].isUsingGenerics()) return true; } } return false; } public static String getGenericsSignature(ClassNode node) { if (!usesGenericsInClassSignature(node)) return null; GenericsType[] genericsTypes = node.getGenericsTypes(); StringBuffer ret = new StringBuffer(100); getGenericsTypeSpec(ret, genericsTypes); GenericsType extendsPart = new GenericsType(node.getUnresolvedSuperClass(false)); writeGenericsBounds(ret, extendsPart, true); ClassNode[] interfaces = node.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { GenericsType interfacePart = new GenericsType(interfaces[i]); writeGenericsBounds(ret, interfacePart, false); } return ret.toString(); } private static void getGenericsTypeSpec(StringBuffer ret, GenericsType[] genericsTypes) { if (genericsTypes == null) return; ret.append('<'); for (int i = 0; i < genericsTypes.length; i++) { String name = genericsTypes[i].getName(); ret.append(name); ret.append(':'); writeGenericsBounds(ret, genericsTypes[i], true); } ret.append('>'); } public static String getGenericsBounds(ClassNode type) { GenericsType[] genericsTypes = type.getGenericsTypes(); if (genericsTypes == null) return null; StringBuffer ret = new StringBuffer(100); if (type.isGenericsPlaceHolder()) { addSubTypes(ret, type.getGenericsTypes(), "", ""); } else { GenericsType gt = new GenericsType(type); writeGenericsBounds(ret, gt, false); } return ret.toString(); } private static void writeGenericsBoundType(StringBuffer ret, ClassNode printType, boolean writeInterfaceMarker) { if (writeInterfaceMarker && printType.isInterface()) ret.append(":"); if (printType.equals(ClassHelper.OBJECT_TYPE) && printType.getGenericsTypes() != null) { ret.append("T"); ret.append(printType.getGenericsTypes()[0].getName()); ret.append(";"); } else { ret.append(getTypeDescription(printType, false)); addSubTypes(ret, printType.getGenericsTypes(), "<", ">"); if (!ClassHelper.isPrimitiveType(printType)) ret.append(";"); } } private static void writeGenericsBounds(StringBuffer ret, GenericsType type, boolean writeInterfaceMarker) { if (type.getUpperBounds() != null) { ClassNode[] bounds = type.getUpperBounds(); for (int i = 0; i < bounds.length; i++) { writeGenericsBoundType(ret, bounds[i], writeInterfaceMarker); } } else if (type.getLowerBound() != null) { writeGenericsBoundType(ret, type.getLowerBound(), writeInterfaceMarker); } else { writeGenericsBoundType(ret, type.getType(), writeInterfaceMarker); } } private static void addSubTypes(StringBuffer ret, GenericsType[] types, String start, String end) { if (types == null) return; ret.append(start); for (int i = 0; i < types.length; i++) { if (types[i].getType().isArray()) { ret.append("["); addSubTypes(ret, new GenericsType[]{new GenericsType(types[i].getType().getComponentType())}, "", ""); } else { if (types[i].isPlaceholder()) { ret.append('T'); String name = types[i].getName(); ret.append(name); ret.append(';'); } else if (types[i].isWildcard()) { if (types[i].getUpperBounds() != null) { ret.append('+'); writeGenericsBounds(ret, types[i], false); } else if (types[i].getLowerBound() != null) { ret.append('-'); writeGenericsBounds(ret, types[i], false); } else { ret.append('*'); } } else { writeGenericsBounds(ret, types[i], false); } } } ret.append(end); } public static void load(MethodVisitor mv, ClassNode type, int idx) { if (type == ClassHelper.double_TYPE) { mv.visitVarInsn(DLOAD, idx); } else if (type == ClassHelper.float_TYPE) { mv.visitVarInsn(FLOAD, idx); } else if (type == ClassHelper.long_TYPE) { mv.visitVarInsn(LLOAD, idx); } else if ( type == ClassHelper.boolean_TYPE || type == ClassHelper.char_TYPE || type == ClassHelper.byte_TYPE || type == ClassHelper.int_TYPE || type == ClassHelper.short_TYPE) { mv.visitVarInsn(ILOAD, idx); } else { mv.visitVarInsn(ALOAD, idx); } } public static void doCast(MethodVisitor mv, ClassNode type) { if (type == ClassHelper.OBJECT_TYPE) return; if (ClassHelper.isPrimitiveType(type) && type != ClassHelper.VOID_TYPE) { unbox(mv, type); } else { mv.visitTypeInsn( CHECKCAST, type.isArray() ? BytecodeHelper.getTypeDescription(type) : BytecodeHelper.getClassInternalName(type.getName())); } } /** * Given a wrapped number type (Byte, Integer, Short, ...), generates bytecode * to convert it to a primitive number (int, long, double) using calls to * wrapped.[targetType]Value() * @param mv method visitor * @param sourceType the wrapped number type * @param targetType the primitive target type */ public static void doCastToPrimitive(MethodVisitor mv, ClassNode sourceType, ClassNode targetType) { mv.visitMethodInsn( INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(sourceType), targetType.getName()+"Value", "()"+BytecodeHelper.getTypeDescription(targetType) ); } public static void doCast(MethodVisitor mv, Class type) { if (type == Object.class) return; if (type.isPrimitive() && type != Void.TYPE) { unbox(mv, type); } else { mv.visitTypeInsn( CHECKCAST, type.isArray() ? BytecodeHelper.getTypeDescription(type) : BytecodeHelper.getClassInternalName(type.getName())); } } /** * Generates the bytecode to unbox the current value on the stack */ public static void unbox(MethodVisitor mv, Class type) { if (type.isPrimitive() && type != Void.TYPE) { String returnString = "(Ljava/lang/Object;)" + BytecodeHelper.getTypeDescription(type); mv.visitMethodInsn( INVOKESTATIC, DTT_CLASSNAME, type.getName() + "Unbox", returnString); } } public static void unbox(MethodVisitor mv, ClassNode type) { if (type.isPrimaryClassNode()) return; unbox(mv, type.getTypeClass()); } /** * box top level operand */ public static boolean box(MethodVisitor mv, ClassNode type) { if (type.isPrimaryClassNode()) return false; return box(mv, type.getTypeClass()); } /** * Generates the bytecode to autobox the current value on the stack */ public static boolean box(MethodVisitor mv, Class type) { if (ReflectionCache.getCachedClass(type).isPrimitive && type != void.class) { String returnString = "(" + BytecodeHelper.getTypeDescription(type) + ")Ljava/lang/Object;"; mv.visitMethodInsn(INVOKESTATIC, DTT_CLASSNAME, "box", returnString); return true; } return false; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryObjectExpressionHelper.java0000644001501200150120000000546211707612046031043 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; /** * @author Jochen "blackdrag" Theodorou */ public class BinaryObjectExpressionHelper extends BinaryExpressionWriter { private static final MethodCaller arrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "objectArrayGet"); private static final MethodCaller arraySet = MethodCaller.newStatic(BytecodeInterface8.class, "objectArraySet"); // private WriterController controller; public BinaryObjectExpressionHelper(WriterController controller) { super(controller); // this.controller = controller; } protected MethodCaller getArrayGetCaller() { return arrayGet; } protected MethodCaller getArraySetCaller() { return arraySet; } // dummy methods public boolean writePostOrPrefixMethod(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } public boolean write(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } protected boolean writeDivision(boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } protected int getBitwiseOperationBytecode(int type) { return -1; } protected int getCompareCode() { return -1; } protected ClassNode getNormalOpResultType() { return null; } protected ClassNode getDevisionOpResultType() { return null; } protected int getShiftOperationBytecode(int type) { return -1; } protected int getStandardOperationBytecode(int type) { return -1; } protected void removeTwoOperands(MethodVisitor mv) {} protected void writePlusPlus(MethodVisitor mv) {} protected void writeMinusMinus(MethodVisitor mv) {} protected void doubleTwoOperands(MethodVisitor mv) {} } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/MopWriter.java0000644001501200150120000001613111707612046025173 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.objectweb.asm.MethodVisitor; import static org.objectweb.asm.Opcodes.*; public class MopWriter { private static class MopKey { int hash = 0; String name; Parameter[] params; MopKey(String name, Parameter[] params) { this.name = name; this.params = params; hash = name.hashCode() << 2 + params.length; } public int hashCode() { return hash; } public boolean equals(Object obj) { MopKey other = (MopKey) obj; return other.name.equals(name) && equalParameterTypes(other.params,params); } } private WriterController controller; public MopWriter(WriterController wc) { controller = wc; } public void createMopMethods() { ClassNode classNode = controller.getClassNode(); if (classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) { return; } visitMopMethodList(classNode.getMethods(), true); visitMopMethodList(classNode.getSuperClass().getAllDeclaredMethods(), false); } /** * filters a list of method for MOP methods. For all methods that are no * MOP methods a MOP method is created if the method is not public and the * call would be a call on "this" (isThis == true). If the call is not on * "this", then the call is a call on "super" and all methods are used, * unless they are already a MOP method * * @param methods unfiltered list of methods for MOP * @param isThis if true, then we are creating a MOP method on "this", "super" else * @see #generateMopCalls(LinkedList, boolean) */ private void visitMopMethodList(List methods, boolean isThis) { HashMap mops = new HashMap(); LinkedList mopCalls = new LinkedList(); for (Object method : methods) { MethodNode mn = (MethodNode) method; if ((mn.getModifiers() & ACC_ABSTRACT) != 0) continue; if (mn.isStatic()) continue; // no this$ methods for non-private isThis=true // super$ method for non-private isThis=false // --> results in XOR boolean isPrivate = Modifier.isPrivate(mn.getModifiers()); if (isThis ^ isPrivate) continue; String methodName = mn.getName(); if (isMopMethod(methodName)) { mops.put(new MopKey(methodName, mn.getParameters()), mn); continue; } if (methodName.startsWith("<")) continue; String name = getMopMethodName(mn, isThis); MopKey key = new MopKey(name, mn.getParameters()); if (mops.containsKey(key)) continue; mops.put(key, mn); mopCalls.add(mn); } generateMopCalls(mopCalls, isThis); mopCalls.clear(); mops.clear(); } /** * creates a MOP method name from a method * * @param method the method to be called by the mop method * @param useThis if true, then it is a call on "this", "super" else * @return the mop method name */ public static String getMopMethodName(MethodNode method, boolean useThis) { ClassNode declaringNode = method.getDeclaringClass(); int distance = 0; for (; declaringNode != null; declaringNode = declaringNode.getSuperClass()) { distance++; } return (useThis ? "this" : "super") + "$" + distance + "$" + method.getName(); } /** * method to determine if a method is a MOP method. This is done by the * method name. If the name starts with "this$" or "super$" but does not * contain "$dist$", then it is an MOP method * * @param methodName name of the method to test * @return true if the method is a MOP method */ public static boolean isMopMethod(String methodName) { return (methodName.startsWith("this$") || methodName.startsWith("super$")) && !methodName.contains("$dist$"); } /** * generates a Meta Object Protocol method, that is used to call a non public * method, or to make a call to super. * * @param mopCalls list of methods a mop call method should be generated for * @param useThis true if "this" should be used for the naming */ private void generateMopCalls(LinkedList mopCalls, boolean useThis) { for (MethodNode method : mopCalls) { String name = getMopMethodName(method, useThis); Parameter[] parameters = method.getParameters(); String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters()); MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null); controller.setMethodVisitor(mv); mv.visitVarInsn(ALOAD, 0); int newRegister = 1; OperandStack operandStack = controller.getOperandStack(); for (Parameter parameter : parameters) { ClassNode type = parameter.getType(); operandStack.load(parameter.getType(), newRegister); // increment to next register, double/long are using two places newRegister++; if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++; } operandStack.remove(parameters.length); mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(method.getDeclaringClass()), method.getName(), methodDescriptor); BytecodeHelper.doReturn(mv, method.getReturnType()); mv.visitMaxs(0, 0); mv.visitEnd(); controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null); } } private static boolean equalParameterTypes(Parameter[] p1, Parameter[] p2) { if (p1.length!=p2.length) return false; for (int i=0; i closureClassMap; private WriterController controller; public ClosureWriter(WriterController wc) { this.controller = wc; closureClassMap = new HashMap(); } public void writeClosure(ClosureExpression expression) { CompileStack compileStack = controller.getCompileStack(); MethodVisitor mv = controller.getMethodVisitor(); ClassNode classNode = controller.getClassNode(); AsmClassGenerator acg = controller.getAcg(); ClassNode closureClass = getOrAddClosureClass(expression, 0); String closureClassinternalName = BytecodeHelper.getClassInternalName(closureClass); List constructors = closureClass.getDeclaredConstructors(); ConstructorNode node = (ConstructorNode) constructors.get(0); Parameter[] localVariableParams = node.getParameters(); mv.visitTypeInsn(NEW, closureClassinternalName); mv.visitInsn(DUP); if (controller.isStaticMethod() || compileStack.isInSpecialConstructorCall()) { (new ClassExpression(classNode)).visit(acg); (new ClassExpression(controller.getOutermostClass())).visit(acg); } else { mv.visitVarInsn(ALOAD, 0); controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); loadThis(); } // now let's load the various parameters we're passing // we start at index 2 because the first variable we pass // is the owner instance and at this point it is already // on the stack for (int i = 2; i < localVariableParams.length; i++) { Parameter param = localVariableParams[i]; String name = param.getName(); loadReference(name, controller); if (param.getNodeMetaData(ClosureWriter.UseExistingReference.class)==null) { param.setNodeMetaData(ClosureWriter.UseExistingReference.class,Boolean.TRUE); } } // we may need to pass in some other constructors //cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "", prototype + ")V"); mv.visitMethodInsn( INVOKESPECIAL, closureClassinternalName, "", BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, localVariableParams)); controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE, localVariableParams.length); } public static void loadReference(String name, WriterController controller) { CompileStack compileStack = controller.getCompileStack(); MethodVisitor mv = controller.getMethodVisitor(); ClassNode classNode = controller.getClassNode(); AsmClassGenerator acg = controller.getAcg(); // compileStack.containsVariable(name) means to ask if the variable is already declared // compileStack.getScope().isReferencedClassVariable(name) means to ask if the variable is a field // If it is no field and is not yet declared, then it is either a closure shared variable or // an already declared variable. if (!compileStack.containsVariable(name) && compileStack.getScope().isReferencedClassVariable(name)) { acg.visitFieldExpression(new FieldExpression(classNode.getDeclaredField(name))); } else { BytecodeVariable v = compileStack.getVariable(name, !classNodeUsesReferences(controller.getClassNode())); if (v == null) { // variable is not on stack because we are // inside a nested Closure and this variable // was not used before // then load it from the Closure field FieldNode field = classNode.getDeclaredField(name); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, controller.getInternalClassName(), name, BytecodeHelper.getTypeDescription(field.getType())); } else { mv.visitVarInsn(ALOAD, v.getIndex()); } controller.getOperandStack().push(ClassHelper.REFERENCE_TYPE); } } public ClassNode getOrAddClosureClass(ClosureExpression expression, int mods) { ClassNode closureClass = closureClassMap.get(expression); if (closureClass == null) { closureClass = createClosureClass(expression, mods); closureClassMap.put(expression, closureClass); controller.getAcg().addInnerClass(closureClass); closureClass.addInterface(ClassHelper.GENERATED_CLOSURE_Type); } return closureClass; } private static boolean classNodeUsesReferences(ClassNode classNode) { boolean ret = classNode.getSuperClass() == ClassHelper.CLOSURE_TYPE; if (ret) return ret; if (classNode instanceof InnerClassNode) { InnerClassNode inner = (InnerClassNode) classNode; return inner.isAnonymous(); } return false; } private ClassNode createClosureClass(ClosureExpression expression, int mods) { ClassNode classNode = controller.getClassNode(); ClassNode outerClass = controller.getOutermostClass(); MethodNode methodNode = controller.getMethodNode(); String name = outerClass.getName() + "$" + controller.getContext().getNextClosureInnerName(outerClass, classNode, methodNode); // add a more informative name boolean staticMethodOrInStaticClass = controller.isStaticMethod() || classNode.isStaticClass(); Parameter[] parameters = expression.getParameters(); if (parameters == null) { parameters = Parameter.EMPTY_ARRAY; } else if (parameters.length == 0) { // let's create a default 'it' parameter Parameter it = new Parameter(ClassHelper.OBJECT_TYPE, "it", ConstantExpression.NULL); parameters = new Parameter[]{it}; Variable ref = expression.getVariableScope().getDeclaredVariable("it"); if (ref!=null) it.setClosureSharedVariable(ref.isClosureSharedVariable()); } Parameter[] localVariableParams = getClosureSharedVariables(expression); removeInitialValues(localVariableParams); InnerClassNode answer = new InnerClassNode(classNode, name, mods, ClassHelper.CLOSURE_TYPE.getPlainNodeReference()); answer.setEnclosingMethod(controller.getMethodNode()); answer.setSynthetic(true); answer.setUsingGenerics(outerClass.isUsingGenerics()); answer.setSourcePosition(expression); if (staticMethodOrInStaticClass) { answer.setStaticClass(true); } if (controller.isInScriptBody()) { answer.setScriptBody(true); } MethodNode method = answer.addMethod("doCall", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, expression.getCode()); method.setSourcePosition(expression); VariableScope varScope = expression.getVariableScope(); if (varScope == null) { throw new RuntimeException( "Must have a VariableScope by now! for expression: " + expression + " class: " + name); } else { method.setVariableScope(varScope.copy()); } if (parameters.length > 1 || (parameters.length == 1 && parameters[0].getType() != null && parameters[0].getType() != ClassHelper.OBJECT_TYPE)) { // let's add a typesafe call method MethodNode call = answer.addMethod( "call", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, new ReturnStatement( new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "doCall", new ArgumentListExpression(parameters)))); call.setSourcePosition(expression); } // let's make the constructor BlockStatement block = new BlockStatement(); // this block does not get a source position, because we don't // want this synthetic constructor to show up in corbertura reports VariableExpression outer = new VariableExpression("_outerInstance"); outer.setSourcePosition(expression); block.getVariableScope().putReferencedLocalVariable(outer); VariableExpression thisObject = new VariableExpression("_thisObject"); thisObject.setSourcePosition(expression); block.getVariableScope().putReferencedLocalVariable(thisObject); TupleExpression conArgs = new TupleExpression(outer, thisObject); block.addStatement( new ExpressionStatement( new ConstructorCallExpression( ClassNode.SUPER, conArgs))); // let's assign all the parameter fields from the outer context for (Parameter param : localVariableParams) { String paramName = param.getName(); ClassNode type = param.getType(); if (true) { VariableExpression initialValue = new VariableExpression(paramName); initialValue.setAccessedVariable(param); initialValue.setUseReferenceDirectly(true); ClassNode realType = type; type = ClassHelper.makeReference(); param.setType(ClassHelper.makeReference()); FieldNode paramField = answer.addField(paramName, ACC_PRIVATE | ACC_SYNTHETIC, type, initialValue); paramField.setOriginType(ClassHelper.getWrapper(param.getOriginType())); paramField.setHolder(true); String methodName = Verifier.capitalize(paramName); // let's add a getter & setter Expression fieldExp = new FieldExpression(paramField); answer.addMethod( "get" + methodName, ACC_PUBLIC, realType.getPlainNodeReference(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement(fieldExp)); } } Parameter[] params = new Parameter[2 + localVariableParams.length]; params[0] = new Parameter(ClassHelper.OBJECT_TYPE, "_outerInstance"); params[1] = new Parameter(ClassHelper.OBJECT_TYPE, "_thisObject"); System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length); ASTNode sn = answer.addConstructor(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, block); sn.setSourcePosition(expression); correctAccessedVariable(answer,expression); return answer; } private void correctAccessedVariable(final InnerClassNode closureClass, ClosureExpression ce) { CodeVisitorSupport visitor = new CodeVisitorSupport() { @Override public void visitVariableExpression(VariableExpression expression) { Variable v = expression.getAccessedVariable(); if (v==null) return; if (!(v instanceof FieldNode)) return; String name = expression.getName(); FieldNode fn = closureClass.getDeclaredField(name); if (fn != null) { // only overwrite if we find something more specific expression.setAccessedVariable(fn); } } }; visitor.visitClosureExpression(ce); } /* * this method is called for local variables shared between scopes. * These variables must not have init values because these would * then in later steps be used to create multiple versions of the * same method, in this case the constructor. A closure should not * have more than one constructor! */ private void removeInitialValues(Parameter[] params) { for (int i = 0; i < params.length; i++) { if (params[i].hasInitialExpression()) { Parameter p = new Parameter(params[i].getType(), params[i].getName()); p.setOriginType(p.getOriginType()); params[i] = p; } } } public boolean addGeneratedClosureConstructorCall(ConstructorCallExpression call) { ClassNode classNode = controller.getClassNode(); if (!classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) return false; AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); MethodVisitor mv = controller.getMethodVisitor(); mv.visitVarInsn(ALOAD, 0); ClassNode callNode = classNode.getSuperClass(); TupleExpression arguments = (TupleExpression) call.getArguments(); if (arguments.getExpressions().size()!=2) throw new GroovyBugError("expected 2 arguments for closure constructor super call, but got"+arguments.getExpressions().size()); arguments.getExpression(0).visit(acg); operandStack.box(); arguments.getExpression(1).visit(acg); operandStack.box(); //TODO: replace with normal String, p not needed Parameter p = new Parameter(ClassHelper.OBJECT_TYPE,"_p"); String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, new Parameter[]{p,p}); mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "", descriptor); operandStack.remove(2); return true; } protected Parameter[] getClosureSharedVariables(ClosureExpression ce) { VariableScope scope = ce.getVariableScope(); Parameter[] ret = new Parameter[scope.getReferencedLocalVariablesCount()]; int index = 0; for (Iterator iter = scope.getReferencedLocalVariablesIterator(); iter.hasNext();) { Variable element = (org.codehaus.groovy.ast.Variable) iter.next(); Parameter p = new Parameter(element.getType(), element.getName()); p.setOriginType(element.getOriginType()); p.setClosureSharedVariable(element.isClosureSharedVariable()); ret[index] = p; index++; } return ret; } private void loadThis() { MethodVisitor mv = controller.getMethodVisitor(); mv.visitVarInsn(ALOAD, 0); if (controller.isInClosure()) { mv.visitMethodInsn( INVOKEVIRTUAL, "groovy/lang/Closure", "getThisObject", "()Ljava/lang/Object;" ); controller.getOperandStack().push(ClassHelper.OBJECT_TYPE); } else { controller.getOperandStack().push(controller.getClassNode()); } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/BinaryDoubleExpressionHelper.java0000644001501200150120000000611211707612046031040 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import static org.objectweb.asm.Opcodes.*; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; /** * @author Jochen "blackdrag" Theodorou */ public class BinaryDoubleExpressionHelper extends BinaryLongExpressionHelper { public BinaryDoubleExpressionHelper(WriterController controller) { super(controller); } private static final MethodCaller doubleArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "dArrayGet"), doubleArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "dArraySet"); protected MethodCaller getArrayGetCaller() { return doubleArrayGet; } protected MethodCaller getArraySetCaller() { return doubleArraySet; } protected boolean writeBitwiseOp(int op, boolean simulate) { if (!simulate) throw new GroovyBugError("should not reach here"); return false; } protected int getBitwiseOperationBytecode(int op) { return -1; } protected int getCompareCode() { return DCMPG; } protected ClassNode getNormalOpResultType() { return ClassHelper.double_TYPE; } protected boolean writeShiftOp(int type, boolean simulate) { if (!simulate) throw new GroovyBugError("should not reach here"); return false; } protected int getShiftOperationBytecode(int type) { return -1; } private static final int[] stdOperations = { DADD, // PLUS 200 DSUB, // MINUS 201 DMUL, // MULTIPLY 202 DDIV, // DIV 203 DDIV, // INTDIV 204 DREM, // MOD 203 }; protected int getStandardOperationBytecode(int type) { return stdOperations[type]; } protected void writeMinusMinus(MethodVisitor mv) { mv.visitInsn(DCONST_1); mv.visitInsn(DSUB); } protected void writePlusPlus(MethodVisitor mv) { mv.visitInsn(DCONST_1); mv.visitInsn(DADD); } protected ClassNode getDevisionOpResultType() { return ClassHelper.double_TYPE; } @Override protected boolean supportsDivision() { return true; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/asm/VariableSlotLoader.java0000644001501200150120000000261611707612046026764 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.BytecodeExpression; import org.objectweb.asm.MethodVisitor; public class VariableSlotLoader extends BytecodeExpression { private int idx; private OperandStack operandStack; public VariableSlotLoader(ClassNode type, int index, OperandStack os) { super(type); this.idx = index; this.operandStack = os; } public VariableSlotLoader(int index, OperandStack os) { this.idx = index; this.operandStack = os; } @Override public void visit(MethodVisitor mv) { operandStack.load(this.getType(), idx); operandStack.remove(1); } public int getIndex(){ return idx; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/genArrayAccess.groovy0000644001501200150120000001416011627206700025756 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen println """ package org.codehaus.groovy.runtime.dgmimpl; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; public class ArrayOperations { ${genInners()} } """ def genInners () { def res = "" final Map primitives = [ "boolean": "Boolean", "byte": "Byte", "char": "Character", "short": "Short", "int": "Integer", "long": "Long", "float": "Float", "double": "Double" ] primitives.each {primName, clsName -> res += """ public static class ${clsName}ArrayGetAtMetaMethod extends ArrayGetAtMetaMethod { private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(${primName}[].class); public Class getReturnType() { return ${clsName}.class; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final ${primName}[] objects = (${primName}[]) object; return objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)]; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args [0] instanceof Integer)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new PojoMetaMethodSite(site, metaClass, metaMethod, params) { public Object invoke(Object receiver, Object[] args) { final ${primName}[] objects = (${primName}[]) receiver; return objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)]; } public Object callBinop(Object receiver, Object arg) { if ((receiver instanceof ${primName}[] && arg instanceof Integer) && checkMetaClass()) { final ${primName}[] objects = (${primName}[]) receiver; return objects[normaliseIndex(((Integer) arg).intValue(), objects.length)]; } else return super.callBinop(receiver,arg); } public Object invokeBinop(Object receiver, Object arg) { final ${primName}[] objects = (${primName}[]) receiver; return objects[normaliseIndex(((Integer) arg).intValue(), objects.length)]; } }; } } public static class ${clsName}ArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(${primName}[].class); private static final CachedClass [] PARAM_CLASS_ARR = new CachedClass[] {INTEGER_CLASS, OBJECT_CLASS}; public ${clsName}ArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final ${primName}[] objects = (${primName}[]) object; final int index = normaliseIndex(((Integer) args[0]).intValue(), objects.length); Object newValue = args[1]; if (!(newValue instanceof ${clsName})) { Number n = (Number) newValue; objects[index] = ((Number)newValue).${primName}Value(); } else objects[index] = ((${clsName})args[1]).${primName}Value(); return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args [0] instanceof Integer) || !(args [1] instanceof ${clsName})) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new PojoMetaMethodSite(site, metaClass, metaMethod, params) { public Object call(Object receiver, Object[] args) { if ((receiver instanceof ${primName}[] && args[0] instanceof Integer && args[1] instanceof ${clsName} ) && checkMetaClass()) { final ${primName}[] objects = (${primName}[]) receiver; objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)] = ((${clsName})args[1]).${primName}Value(); return null; } else return super.call(receiver,args); } }; } } """ } res } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.java0000644001501200150120000001006311627206700026404 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.syntax.RuntimeParserException; import org.objectweb.asm.Opcodes; /** * Performs various checks on code inside methods and constructors * including checking for valid field, variables names etc. that * would otherwise lead to invalid code. * * @author James Strachan * @version $Revision$ */ public class VerifierCodeVisitor extends CodeVisitorSupport implements Opcodes { private Verifier verifier; VerifierCodeVisitor(Verifier verifier) { this.verifier = verifier; } public void visitForLoop(ForStatement expression) { assertValidIdentifier(expression.getVariable().getName(), "for loop variable name", expression); super.visitForLoop(expression); } public void visitFieldExpression(FieldExpression expression) { if (!expression.getField().isSynthetic()) { assertValidIdentifier(expression.getFieldName(), "field name", expression); } super.visitFieldExpression(expression); } public void visitVariableExpression(VariableExpression expression) { assertValidIdentifier(expression.getName(), "variable name", expression); super.visitVariableExpression(expression); } public void visitListExpression(ListExpression expression) { for (Expression element : expression.getExpressions()) { if (element instanceof MapEntryExpression) { throw new RuntimeParserException("No map entry allowed at this place", element); } } super.visitListExpression(expression); } public void visitConstructorCallExpression(ConstructorCallExpression call) { ClassNode callType = call.getType(); if (callType.isEnum() && !callType.equals(verifier.getClassNode())) { throw new RuntimeParserException("Enum constructor calls are only allowed inside the enum class", call); } } public static void assertValidIdentifier(String name, String message, ASTNode node) { int size = name.length(); if (size <= 0) { throw new RuntimeParserException("Invalid " + message + ". Identifier must not be empty", node); } char firstCh = name.charAt(0); if (size == 1 && firstCh == '$') { throw new RuntimeParserException("Invalid " + message + ". Must include a letter but only found: " + name, node); } if (!Character.isJavaIdentifierStart(firstCh)) { throw new RuntimeParserException("Invalid " + message + ". Must start with a letter but was: " + name, node); } for (int i = 1; i < size; i++) { char ch = name.charAt(i); if (!Character.isJavaIdentifierPart(ch)) { throw new RuntimeParserException("Invalid " + message + ". Invalid character at position: " + (i + 1) + " of value: " + ch + " in name: " + name, node); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/EnumVisitor.java0000644001501200150120000004254111707612044024751 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.List; public class EnumVisitor extends ClassCodeVisitorSupport { // some constants for modifiers private static final int FS = Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; private static final int PS = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; private static final int PUBLIC_FS = Opcodes.ACC_PUBLIC | FS; private static final int PRIVATE_FS = Opcodes.ACC_PRIVATE | FS; private final SourceUnit sourceUnit; public EnumVisitor(CompilationUnit cu, SourceUnit su) { sourceUnit = su; } public void visitClass(ClassNode node) { if (!node.isEnum()) return; completeEnum(node); } protected SourceUnit getSourceUnit() { return sourceUnit; } private void completeEnum(ClassNode enumClass) { boolean isAic = isAnonymousInnerClass(enumClass); // create MIN_VALUE and MAX_VALUE fields FieldNode minValue = null, maxValue = null, values = null; if (!isAic) { ClassNode enumRef = enumClass.getPlainNodeReference(); // create values field values = new FieldNode("$VALUES", PRIVATE_FS | Opcodes.ACC_SYNTHETIC, enumRef.makeArray(), enumClass, null); values.setSynthetic(true); addMethods(enumClass, values); // create MIN_VALUE and MAX_VALUE fields minValue = new FieldNode("MIN_VALUE", PUBLIC_FS, enumRef, enumClass, null); maxValue = new FieldNode("MAX_VALUE", PUBLIC_FS, enumRef, enumClass, null); } addInit(enumClass, minValue, maxValue, values, isAic); } private void addMethods(ClassNode enumClass, FieldNode values) { List methods = enumClass.getMethods(); boolean hasNext = false; boolean hasPrevious = false; for (MethodNode m : methods) { if (m.getName().equals("next") && m.getParameters().length == 0) hasNext = true; if (m.getName().equals("previous") && m.getParameters().length == 0) hasPrevious = true; if (hasNext && hasPrevious) break; } ClassNode enumRef = enumClass.getPlainNodeReference(); { // create values() method MethodNode valuesMethod = new MethodNode("values", PUBLIC_FS, enumRef.makeArray(), new Parameter[0], ClassNode.EMPTY_ARRAY, null); valuesMethod.setSynthetic(true); BlockStatement code = new BlockStatement(); MethodCallExpression cloneCall = new MethodCallExpression(new FieldExpression(values), "clone", MethodCallExpression.NO_ARGUMENTS); cloneCall.setMethodTarget(values.getType().getMethod("clone", Parameter.EMPTY_ARRAY)); code.addStatement(new ReturnStatement(cloneCall)); valuesMethod.setCode(code); enumClass.addMethod(valuesMethod); } if (!hasNext) { // create next() method, code: // Day next() { // int ordinal = ordinal().next() // if (ordinal >= values().size()) ordinal = 0 // return values()[ordinal] // } Token assign = Token.newSymbol(Types.ASSIGN, -1, -1); Token ge = Token.newSymbol(Types.COMPARE_GREATER_THAN_EQUAL, -1, -1); MethodNode nextMethod = new MethodNode("next", Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, enumRef, new Parameter[0], ClassNode.EMPTY_ARRAY, null); nextMethod.setSynthetic(true); BlockStatement code = new BlockStatement(); BlockStatement ifStatement = new BlockStatement(); ifStatement.addStatement( new ExpressionStatement( new BinaryExpression(new VariableExpression("ordinal"), assign, new ConstantExpression(0)) ) ); code.addStatement( new ExpressionStatement( new DeclarationExpression( new VariableExpression("ordinal"), assign, new MethodCallExpression( new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "ordinal", MethodCallExpression.NO_ARGUMENTS), "next", MethodCallExpression.NO_ARGUMENTS ) ) ) ); code.addStatement( new IfStatement( new BooleanExpression(new BinaryExpression( new VariableExpression("ordinal"), ge, new MethodCallExpression( new FieldExpression(values), "size", MethodCallExpression.NO_ARGUMENTS ) )), ifStatement, EmptyStatement.INSTANCE ) ); code.addStatement( new ReturnStatement( new MethodCallExpression(new FieldExpression(values), "getAt", new VariableExpression("ordinal")) ) ); nextMethod.setCode(code); enumClass.addMethod(nextMethod); } if (!hasPrevious) { // create previous() method, code: // Day previous() { // int ordinal = ordinal().previous() // if (ordinal < 0) ordinal = values().size() - 1 // return values()[ordinal] // } Token assign = Token.newSymbol(Types.ASSIGN, -1, -1); Token lt = Token.newSymbol(Types.COMPARE_LESS_THAN, -1, -1); MethodNode nextMethod = new MethodNode("previous", Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, enumRef, new Parameter[0], ClassNode.EMPTY_ARRAY, null); nextMethod.setSynthetic(true); BlockStatement code = new BlockStatement(); BlockStatement ifStatement = new BlockStatement(); ifStatement.addStatement( new ExpressionStatement( new BinaryExpression(new VariableExpression("ordinal"), assign, new MethodCallExpression( new MethodCallExpression( new FieldExpression(values), "size", MethodCallExpression.NO_ARGUMENTS ), "minus", new ConstantExpression(1) ) ) ) ); code.addStatement( new ExpressionStatement( new DeclarationExpression( new VariableExpression("ordinal"), assign, new MethodCallExpression( new MethodCallExpression( VariableExpression.THIS_EXPRESSION, "ordinal", MethodCallExpression.NO_ARGUMENTS), "previous", MethodCallExpression.NO_ARGUMENTS ) ) ) ); code.addStatement( new IfStatement( new BooleanExpression(new BinaryExpression( new VariableExpression("ordinal"), lt, new ConstantExpression(0) )), ifStatement, EmptyStatement.INSTANCE ) ); code.addStatement( new ReturnStatement( new MethodCallExpression(new FieldExpression(values), "getAt", new VariableExpression("ordinal")) ) ); nextMethod.setCode(code); enumClass.addMethod(nextMethod); } { // create valueOf Parameter stringParameter = new Parameter(ClassHelper.STRING_TYPE, "name"); MethodNode valueOfMethod = new MethodNode("valueOf", PS, enumRef, new Parameter[]{stringParameter}, ClassNode.EMPTY_ARRAY, null); ArgumentListExpression callArguments = new ArgumentListExpression(); callArguments.addExpression(new ClassExpression(enumClass)); callArguments.addExpression(new VariableExpression("name")); BlockStatement code = new BlockStatement(); code.addStatement( new ReturnStatement( new MethodCallExpression(new ClassExpression(ClassHelper.Enum_Type), "valueOf", callArguments) ) ); valueOfMethod.setCode(code); valueOfMethod.setSynthetic(true); enumClass.addMethod(valueOfMethod); } } private void addInit(ClassNode enumClass, FieldNode minValue, FieldNode maxValue, FieldNode values, boolean isAic) { // constructor helper // This method is used instead of calling the constructor as // calling the constructor may require a table with MetaClass // selecting the constructor for each enum value. So instead we // use this method to have a central point for constructor selection // and only one table. The whole construction is needed because // Reflection forbids access to the enum constructor. // code: // def $INIT(Object[] para) { // return this(*para) // } ClassNode enumRef = enumClass.getPlainNodeReference(); Parameter[] parameter = new Parameter[]{new Parameter(ClassHelper.OBJECT_TYPE.makeArray(), "para")}; MethodNode initMethod = new MethodNode("$INIT", PUBLIC_FS | Opcodes.ACC_SYNTHETIC, enumRef, parameter, ClassNode.EMPTY_ARRAY, null); initMethod.setSynthetic(true); ConstructorCallExpression cce = new ConstructorCallExpression( ClassNode.THIS, new ArgumentListExpression( new SpreadExpression(new VariableExpression("para")) ) ); BlockStatement code = new BlockStatement(); code.addStatement(new ReturnStatement(cce)); initMethod.setCode(code); enumClass.addMethod(initMethod); // static init List fields = enumClass.getFields(); List arrayInit = new ArrayList(); int value = -1; Token assign = Token.newSymbol(Types.ASSIGN, -1, -1); List block = new ArrayList(); FieldNode tempMin = null; FieldNode tempMax = null; for (FieldNode field : fields) { if ((field.getModifiers() & Opcodes.ACC_ENUM) == 0) continue; value++; if (tempMin == null) tempMin = field; tempMax = field; ClassNode enumBase = enumClass; ArgumentListExpression args = new ArgumentListExpression(); args.addExpression(new ConstantExpression(field.getName())); args.addExpression(new ConstantExpression(value)); if (field.getInitialExpression() != null) { ListExpression oldArgs = (ListExpression) field.getInitialExpression(); for (Expression exp : oldArgs.getExpressions()) { if (exp instanceof MapEntryExpression) { String msg = "The usage of a map entry expression to initialize an Enum is currently not supported, please use an explicit map instead."; sourceUnit.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage( new SyntaxException(msg + '\n', exp.getLineNumber(), exp.getColumnNumber()), sourceUnit) ); continue; } InnerClassNode inner = null; if (exp instanceof ClassExpression) { ClassExpression clazzExp = (ClassExpression) exp; ClassNode ref = clazzExp.getType(); if (ref instanceof EnumConstantClassNode) { inner = (InnerClassNode) ref; } } if (inner != null) { if (inner.getVariableScope() == null) { enumBase = inner; /* * GROOVY-3985: Remove the final modifier from $INIT method in this case * so that subclasses of enum generated for enum constants (aic) can provide * their own $INIT method */ initMethod.setModifiers(initMethod.getModifiers() & ~Opcodes.ACC_FINAL); continue; } } args.addExpression(exp); } } field.setInitialValueExpression(null); block.add( new ExpressionStatement( new BinaryExpression( new FieldExpression(field), assign, new StaticMethodCallExpression(enumBase, "$INIT", args) ) ) ); arrayInit.add(new FieldExpression(field)); } if (!isAic) { if (tempMin != null) { block.add( new ExpressionStatement( new BinaryExpression( new FieldExpression(minValue), assign, new FieldExpression(tempMin) ) ) ); block.add( new ExpressionStatement( new BinaryExpression( new FieldExpression(maxValue), assign, new FieldExpression(tempMax) ) ) ); enumClass.addField(minValue); enumClass.addField(maxValue); } block.add( new ExpressionStatement( new BinaryExpression(new FieldExpression(values), assign, new ArrayExpression(enumClass, arrayInit)) ) ); enumClass.addField(values); } enumClass.addStaticInitializerStatements(block, true); } private boolean isAnonymousInnerClass(ClassNode enumClass) { if (!(enumClass instanceof EnumConstantClassNode)) return false; InnerClassNode ic = (InnerClassNode) enumClass; return ic.getVariableScope() == null; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/genMathModification.groovy0000644001501200150120000000712511627206700027000 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen def ops = [ "plus", "minus", "multiply", "div", "or", "and", "xor", "intdiv", "mod", "leftShift", "rightShift", "rightShiftUnsigned" ] def numbers = ["Byte":"byte", "Short":"short", "Integer":"int", "Long":"long", "Float":"float", "Double":"double"] ops.each { op -> numbers.each { wrappedType, type -> println "public boolean ${type}_${op};"; } } ops.each { op -> println "if (\"${op}\".equals(name)) {" numbers.each { wrappedType, type -> println """if (klazz==${wrappedType}.class) { ${type}_${op} = true; }""" } println "if (klazz==Object.class) {" numbers.each { wrappedType, type -> println "${type}_${op} = true;" } println "}" println "}" } ops.each { op -> numbers.each { wrappedType1, type1 -> numbers.each { wrappedType2, type2 -> def math = getMath(wrappedType1, wrappedType2) if (math [op]) { println """public static ${math.resType} ${op}(${type1} op1, ${type2} op2) { if (instance.${type1}_${op}) { return ${op}Slow(op1, op2); } else { return ${math.resType != type1 ? "((" + math.resType+ ")op1)" : "op1"} ${math[op]} ${math.resType != type2 ? "((" + math.resType+ ")op2)" : "op2"}; } }""" println """private static ${math.resType} ${op}Slow(${type1} op1,${type2} op2) { return ((Number)InvokerHelper.invokeMethod(op1, "${op}", op2)).${math.resType}Value(); }""" } } } } def isFloatingPoint(number) { return number == "Double" || number == "Float"; } def isLong(number) { return number == "Long"; } def getMath (left, right) { if (isFloatingPoint(left) || isFloatingPoint(right)) { return [ resType : "double", plus : "+", minus : "-", multiply : "*", div : "/", ]; } if (isLong(left) || isLong(right)){ return [ resType : "long", plus : "+", minus : "-", multiply : "*", div : "/", or : "|", and : "&", xor : "^", intdiv : "/", mod : "%", leftShift : "<<", rightShift : ">>", rightShiftUnsigned : ">>>" ] } return [ resType : "int", plus : "+", minus : "-", multiply : "*", div : "/", or : "|", and : "&", xor : "^", intdiv : "/", mod : "%", leftShift : "<<", rightShift : ">>", rightShiftUnsigned : ">>>" ] } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/ClassGeneratorException.java0000644001501200150120000000205611627206700027254 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; /** * An exception thrown by the class generator * * @author James Strachan * @version $Revision$ */ public class ClassGeneratorException extends RuntimeException { public ClassGeneratorException(String message) { super(message); } public ClassGeneratorException(String message, Throwable cause) { super(message, cause); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/InnerClassVisitorHelper.java0000644001501200150120000001221111645141222027231 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.VariableScope; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.util.ArrayList; import java.util.List; public abstract class InnerClassVisitorHelper extends ClassCodeVisitorSupport { protected static void setPropertyGetterDispatcher(BlockStatement block, Expression thiz, Parameter[] parameters) { List gStringStrings = new ArrayList(); gStringStrings.add(new ConstantExpression("")); gStringStrings.add(new ConstantExpression("")); List gStringValues = new ArrayList(); gStringValues.add(new VariableExpression(parameters[0])); block.addStatement( new ReturnStatement( new AttributeExpression( thiz, new GStringExpression("$name", gStringStrings, gStringValues ) ) ) ); } protected static void setPropertySetterDispatcher(BlockStatement block, Expression thiz, Parameter[] parameters) { List gStringStrings = new ArrayList(); gStringStrings.add(new ConstantExpression("")); gStringStrings.add(new ConstantExpression("")); List gStringValues = new ArrayList(); gStringValues.add(new VariableExpression(parameters[0])); block.addStatement( new ExpressionStatement( new BinaryExpression( new AttributeExpression( thiz, new GStringExpression("$name", gStringStrings, gStringValues ) ), Token.newSymbol(Types.ASSIGN, -1, -1), new VariableExpression(parameters[1]) ) ) ); } protected static void setMethodDispatcherCode(BlockStatement block, Expression thiz, Parameter[] parameters) { List gStringStrings = new ArrayList(); gStringStrings.add(new ConstantExpression("")); gStringStrings.add(new ConstantExpression("")); List gStringValues = new ArrayList(); gStringValues.add(new VariableExpression(parameters[0])); block.addStatement( new ReturnStatement( new MethodCallExpression( thiz, new GStringExpression("$name", gStringStrings, gStringValues ), new ArgumentListExpression( new SpreadExpression(new VariableExpression(parameters[1])) ) ) ) ); } protected static boolean isStatic(InnerClassNode node) { VariableScope scope = node.getVariableScope(); if (scope != null) return scope.isInStaticContext(); return (node.getModifiers() & Opcodes.ACC_STATIC) != 0; } protected static ClassNode getClassNode(ClassNode node, boolean isStatic) { if (isStatic) node = ClassHelper.CLASS_Type; return node; } protected static int getObjectDistance(ClassNode node) { int count = 0; while (node != null && node != ClassHelper.OBJECT_TYPE) { count++; node = node.getSuperClass(); } return count; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/AnnotationVisitor.java0000644001501200150120000003516211707612044026160 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import java.util.*; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.control.ErrorCollector; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.vmplugin.VMPluginFactory; /** * An Annotation visitor responsible with: * - reading annotation metadata (@Retention, @Target, attribute types) * - verify that an AnnotationNode conforms to annotation meta * - enhancing an AnnotationNode AST to reflect real annotation meta * * @author Alex Popescu */ public class AnnotationVisitor { private SourceUnit source; private ErrorCollector errorCollector; private AnnotationNode annotation; private ClassNode reportClass; public AnnotationVisitor(SourceUnit source, ErrorCollector errorCollector) { this.source = source; this.errorCollector = errorCollector; } public void setReportClass(ClassNode cn) { reportClass = cn; } public AnnotationNode visit(AnnotationNode node) { this.annotation = node; this.reportClass = node.getClassNode(); if (!isValidAnnotationClass(node.getClassNode())) { addError("class " + node.getClassNode().getName() + " is not an annotation"); return node; } // check if values have been passed for all annotation attributes that don't have defaults if (!checkIfMandatoryAnnotationValuesPassed(node)) { return node; } // if enum constants have been used, check if they are all valid if (!checkIfValidEnumConstsAreUsed(node)) { return node; } Map attributes = node.getMembers(); for (Map.Entry entry : attributes.entrySet()) { String attrName = entry.getKey(); Expression attrExpr = transformInlineConstants(entry.getValue()); entry.setValue(attrExpr); ClassNode attrType = getAttributeType(node, attrName); visitExpression(attrName, attrExpr, attrType); } VMPluginFactory.getPlugin().configureAnnotation(node); return this.annotation; } private boolean checkIfValidEnumConstsAreUsed(AnnotationNode node) { boolean ok = true; Map attributes = node.getMembers(); for (Map.Entry entry : attributes.entrySet()) { ok &= validateEnumConstant(entry.getValue()); } return ok; } private boolean validateEnumConstant(Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; String name = pe.getPropertyAsString(); if (pe.getObjectExpression() instanceof ClassExpression && name != null) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum()) { boolean ok = false; try { FieldNode enumField = type.getDeclaredField(name); ok = enumField != null && enumField.getType().equals(type); } catch(Exception ex) { // ignore } if(!ok) { addError("No enum const " + type.getName() + "." + name, pe); return false; } } } } return true; } private Expression transformInlineConstants(Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum() || !type.isResolved()) return exp; try { Field field = type.getTypeClass().getField(pe.getPropertyAsString()); if (field != null && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) { return new ConstantExpression(field.get(null)); } } catch(Exception e) { // ignore, leave property expression in place and we'll report later } } } else if (exp instanceof ListExpression) { ListExpression le = (ListExpression) exp; ListExpression result = new ListExpression(); for (Expression e : le.getExpressions()) { result.addExpression(transformInlineConstants(e)); } return result; } return exp; } private boolean checkIfMandatoryAnnotationValuesPassed(AnnotationNode node) { boolean ok = true; Map attributes = node.getMembers(); ClassNode classNode = node.getClassNode(); for (MethodNode mn : classNode.getMethods()) { String methodName = mn.getName(); // if the annotation attribute has a default, getCode() returns a ReturnStatement with the default value if (mn.getCode() == null && !attributes.containsKey(methodName)) { addError("No explicit/default value found for annotation attribute '" + methodName + "' in annotation " + classNode, node); ok = false; } } return ok; } private ClassNode getAttributeType(AnnotationNode node, String attrName) { ClassNode classNode = node.getClassNode(); List methods = classNode.getMethods(attrName); // if size is >1, then the method was overwritten or something, we ignore that // if it is an error, we have to test it at another place. But size==0 is // an error, because it means that no such attribute exists. if (methods.size() == 0) { addError("'" + attrName + "'is not part of the annotation " + classNode, node); return ClassHelper.OBJECT_TYPE; } MethodNode method = (MethodNode) methods.get(0); return method.getReturnType(); } private boolean isValidAnnotationClass(ClassNode node) { return node.implementsInterface(ClassHelper.Annotation_TYPE); } protected void visitExpression(String attrName, Expression attrExp, ClassNode attrType) { if (attrType.isArray()) { // check needed as @Test(attr = {"elem"}) passes through the parser if (attrExp instanceof ListExpression) { ListExpression le = (ListExpression) attrExp; visitListExpression(attrName, le, attrType.getComponentType()); } else if (attrExp instanceof ClosureExpression) { addError("Annotation list attributes must use Groovy notation [el1, el2]", attrExp); } else { // treat like a singleton list as per Java ListExpression listExp = new ListExpression(); listExp.addExpression(attrExp); if (annotation != null) { annotation.setMember(attrName, listExp); } visitExpression(attrName, listExp, attrType); } } else if (ClassHelper.isPrimitiveType(attrType)) { visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.getWrapper(attrType)); } else if (ClassHelper.STRING_TYPE.equals(attrType)) { visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.STRING_TYPE); } else if (ClassHelper.CLASS_Type.equals(attrType)) { if (!(attrExp instanceof ClassExpression || attrExp instanceof ClosureExpression)) { addError("Only classes and closures can be used for attribute '" + attrName + "'", attrExp); } } else if (attrType.isDerivedFrom(ClassHelper.Enum_Type)) { if (attrExp instanceof PropertyExpression) { visitEnumExpression(attrName, (PropertyExpression) attrExp, attrType); } else { addError("Expected enum value for attribute " + attrName, attrExp); } } else if (isValidAnnotationClass(attrType)) { if (attrExp instanceof AnnotationConstantExpression) { visitAnnotationExpression(attrName, (AnnotationConstantExpression) attrExp, attrType); } else { addError("Expected annotation of type '" + attrType.getName() + "' for attribute " + attrName, attrExp); } } else { addError("Unexpected type " + attrType.getName(), attrExp); } } public void checkReturnType(ClassNode attrType, ASTNode node) { if (attrType.isArray()) { checkReturnType(attrType.getComponentType(), node); } else if (ClassHelper.isPrimitiveType(attrType)) { return; } else if (ClassHelper.STRING_TYPE.equals(attrType)) { return; } else if (ClassHelper.CLASS_Type.equals(attrType)) { return; } else if (attrType.isDerivedFrom(ClassHelper.Enum_Type)) { return; } else if (isValidAnnotationClass(attrType)) { return; } else { addError("Unexpected return type " + attrType.getName(), node); } } private ConstantExpression getConstantExpression(Expression exp, ClassNode attrType) { if (exp instanceof ConstantExpression) { return (ConstantExpression) exp; } else { String base = "expected '" + exp.getText() + "' to be an inline constant of type " + attrType.getName(); if (exp instanceof PropertyExpression) { addError(base + " not a property expression", exp); } else if (exp instanceof VariableExpression && ((VariableExpression)exp).getAccessedVariable() instanceof FieldNode) { addError(base + " not a field expression", exp); } else { addError(base, exp); } return ConstantExpression.EMPTY_EXPRESSION; } } /** * @param attrName the name * @param expression the expression * @param attrType the type */ protected void visitAnnotationExpression(String attrName, AnnotationConstantExpression expression, ClassNode attrType) { AnnotationNode annotationNode = (AnnotationNode) expression.getValue(); AnnotationVisitor visitor = new AnnotationVisitor(this.source, this.errorCollector); // TODO track Deprecated usage and give a warning? visitor.visit(annotationNode); } protected void visitListExpression(String attrName, ListExpression listExpr, ClassNode elementType) { for (Expression expression : listExpr.getExpressions()) { visitExpression(attrName, expression, elementType); } } protected void visitConstantExpression(String attrName, ConstantExpression constExpr, ClassNode attrType) { ClassNode type = ClassHelper.getWrapper(constExpr.getType()); if (!type.isDerivedFrom(attrType)) { addError("Attribute '" + attrName + "' should have type '" + attrType.getName() + "'; " + "but found type '" + constExpr.getType().getName() + "'", constExpr); } } protected void visitEnumExpression(String attrName, PropertyExpression propExpr, ClassNode attrType) { if (!propExpr.getObjectExpression().getType().isDerivedFrom(attrType)) { addError("Attribute '" + attrName + "' should have type '" + attrType.getName() + "' (Enum), but found " + propExpr.getObjectExpression().getType().getName(), propExpr); } } protected void addError(String msg) { addError(msg, this.annotation); } protected void addError(String msg, ASTNode expr) { this.errorCollector.addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException( msg + " in @" + this.reportClass.getName() + '\n', expr.getLineNumber(), expr.getColumnNumber()), this.source) ); } public void checkCircularReference(ClassNode searchClass, ClassNode attrType, Expression startExp) { if (!isValidAnnotationClass(attrType)) return; if (!(startExp instanceof AnnotationConstantExpression)) { addError("Found '" + startExp.getText() + "' when expecting an Annotation Constant", startExp); return; } AnnotationConstantExpression ace = (AnnotationConstantExpression) startExp; AnnotationNode annotationNode = (AnnotationNode) ace.getValue(); if (annotationNode.getClassNode().equals(searchClass)) { addError("Circular reference discovered in " + searchClass.getName(), startExp); return; } ClassNode cn = annotationNode.getClassNode(); for (MethodNode method : cn.getMethods()) { if (method.getReturnType().equals(searchClass)) { addError("Circular reference discovered in " + cn.getName(), startExp); } ReturnStatement code = (ReturnStatement) method.getCode(); if (code == null) continue; checkCircularReference(searchClass, method.getReturnType(), code.getExpression()); } } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/genArrays.groovy0000644001501200150120000000236311627206700025021 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen print """ public class ArrayUtil { ${genMethods()} } """ def genMethods () { def res = "" for (i in 1..250) res += "\n\n" + genMethod (i) res } def genMethod (int paramNum) { def res = "public static Object [] createArray (" for (k in 0.. expressions = args.getExpressions(); VariableExpression ve = new VariableExpression(thisPara.getName()); ve.setAccessedVariable(thisPara); expressions.add(0, ve); } if (cce.isSuperCall()) { // we have a call to super here, so we need to add // our code after that block.getStatements().add(1, newCode); } node.setCode(block); } private boolean shouldImplicitlyPassThisPara(ConstructorCallExpression cce) { boolean pass = false; ClassNode superCN = classNode.getSuperClass(); if (cce.isThisCall()) { pass = true; } else if (cce.isSuperCall()) { // if the super class is another non-static inner class in the same outer class hierarchy, implicit this // needs to be passed if (!superCN.isEnum() && !superCN.isInterface() && superCN instanceof InnerClassNode) { InnerClassNode superInnerCN = (InnerClassNode) superCN; if (!isStatic(superInnerCN) && classNode.getOuterClass().isDerivedFrom(superCN.getOuterClass())) { pass = true; } } } return pass; } private String getUniqueName(Parameter[] params, ConstructorNode node) { String namePrefix = "$p"; outer: for (int i = 0; i < 100; i++) { namePrefix = namePrefix + "$"; for (Parameter p : params) { if (p.getName().equals(namePrefix)) continue outer; } return namePrefix; } addError("unable to find a unique prefix name for synthetic this reference", node); return namePrefix; } private ConstructorCallExpression getFirstIfSpecialConstructorCall(BlockStatement code) { if (code == null) return null; final List statementList = code.getStatements(); if (statementList.isEmpty()) return null; final Statement statement = statementList.get(0); if (!(statement instanceof ExpressionStatement)) return null; Expression expression = ((ExpressionStatement) statement).getExpression(); if (!(expression instanceof ConstructorCallExpression)) return null; ConstructorCallExpression cce = (ConstructorCallExpression) expression; if (cce.isSpecialCall()) return cce; return null; } @Override protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { this.currentMethod = node; super.visitConstructorOrMethod(node, isConstructor); this.currentMethod = null; } @Override public void visitField(FieldNode node) { this.currentField = node; super.visitField(node); this.currentField = null; } @Override public void visitProperty(PropertyNode node) { final FieldNode field = node.getField(); final Expression init = field.getInitialExpression(); field.setInitialValueExpression(null); super.visitProperty(node); field.setInitialValueExpression(init); } @Override public void visitConstructorCallExpression(ConstructorCallExpression call) { super.visitConstructorCallExpression(call); if (!call.isUsingAnonymousInnerClass()) { passThisReference(call); return; } InnerClassNode innerClass = (InnerClassNode) call.getType(); if (!innerClass.getDeclaredConstructors().isEmpty()) return; if ((innerClass.getModifiers() & ACC_STATIC) != 0) return; VariableScope scope = innerClass.getVariableScope(); if (scope == null) return; boolean isStatic = scope.isInStaticContext(); // expressions = constructor call arguments List expressions = ((TupleExpression) call.getArguments()).getExpressions(); // block = init code for the constructor we produce BlockStatement block = new BlockStatement(); // parameters = parameters of the constructor final int additionalParamCount = 1 + scope.getReferencedLocalVariablesCount(); List parameters = new ArrayList(expressions.size() + additionalParamCount); // superCallArguments = arguments for the super call == the constructor call arguments List superCallArguments = new ArrayList(expressions.size()); // first we add a super() call for all expressions given in the // constructor call expression int pCount = additionalParamCount; for (Expression expr : expressions) { pCount++; // add one parameter for each expression in the // constructor call Parameter param = new Parameter(ClassHelper.OBJECT_TYPE, "p" + pCount); parameters.add(param); // add to super call superCallArguments.add(new VariableExpression(param)); } // add the super call ConstructorCallExpression cce = new ConstructorCallExpression( ClassNode.SUPER, new TupleExpression(superCallArguments) ); block.addStatement(new ExpressionStatement(cce)); // we need to add "this" to access unknown methods/properties // this is saved in a field named this$0 pCount = 0; expressions.add(pCount, VariableExpression.THIS_EXPRESSION); ClassNode outerClassType = getClassNode(innerClass.getOuterClass(), isStatic).getPlainNodeReference(); Parameter thisParameter = new Parameter(outerClassType, "p" + pCount); parameters.add(pCount, thisParameter); thisField = innerClass.addField("this$0", PUBLIC_SYNTHETIC, outerClassType, null); addFieldInit(thisParameter, thisField, block); // for each shared variable we add a reference and save it as field for (Iterator it = scope.getReferencedLocalVariablesIterator(); it.hasNext();) { pCount++; org.codehaus.groovy.ast.Variable var = (org.codehaus.groovy.ast.Variable) it.next(); VariableExpression ve = new VariableExpression(var); ve.setClosureSharedVariable(true); ve.setUseReferenceDirectly(true); expressions.add(pCount, ve); ClassNode rawReferenceType = ClassHelper.REFERENCE_TYPE.getPlainNodeReference(); Parameter p = new Parameter(rawReferenceType, "p" + pCount); parameters.add(pCount, p); p.setOriginType(var.getOriginType()); final VariableExpression initial = new VariableExpression(p); initial.setUseReferenceDirectly(true); final FieldNode pField = innerClass.addFieldFirst(ve.getName(), PUBLIC_SYNTHETIC,rawReferenceType, initial); pField.setHolder(true); pField.setOriginType(ClassHelper.getWrapper(var.getOriginType())); } innerClass.addConstructor(ACC_SYNTHETIC, parameters.toArray(new Parameter[0]), ClassNode.EMPTY_ARRAY, block); } // this is the counterpart of addThisReference(). To non-static inner classes, outer this should be // passed as the first argument implicitly. private void passThisReference(ConstructorCallExpression call) { ClassNode cn = call.getType().redirect(); if (!shouldHandleImplicitThisForInnerClass(cn)) return; boolean isInStaticContext = true; if (currentMethod != null) isInStaticContext = currentMethod.getVariableScope().isInStaticContext(); else if (currentField != null) isInStaticContext = currentField.isStatic(); else if (processingObjInitStatements) isInStaticContext = false; // if constructor call is not in static context, return if (isInStaticContext) { // constructor call is in static context and the inner class is non-static - 1st arg is supposed to be // passed as enclosing "this" instance // Expression args = call.getArguments(); if (args instanceof TupleExpression && ((TupleExpression) args).getExpressions().isEmpty()) { addError("No enclosing instance passed in constructor call of a non-static inner class", call); } return; } // calculate outer class which we need for this$0 ClassNode parent = classNode; int level = 0; for (; parent != null && parent != cn.getOuterClass(); parent = parent.getOuterClass()) { level++; } // if constructor call is not in outer class, don't pass 'this' implicitly. Return. if (parent == null) return; //add this parameter to node Expression argsExp = call.getArguments(); if (argsExp instanceof TupleExpression) { TupleExpression argsListExp = (TupleExpression) argsExp; Expression this0 = VariableExpression.THIS_EXPRESSION; for (int i = 0; i != level; ++i) this0 = new PropertyExpression(this0, "this$0"); argsListExp.getExpressions().add(0, this0); } } private static void addFieldInit(Parameter p, FieldNode fn, BlockStatement block) { VariableExpression ve = new VariableExpression(p); FieldExpression fe = new FieldExpression(fn); block.addStatement(new ExpressionStatement( new BinaryExpression( fe, Token.newSymbol(Types.ASSIGN, -1, -1), ve ) )); } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/BytecodeInstruction.java0000644001501200150120000000176311627206700026465 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.objectweb.asm.MethodVisitor; /** * Helper class used by the class generator. Usually * an inner class is produced, that contains bytecode * creation code in the visit method. * * @author Jochen Theodorou */ public abstract class BytecodeInstruction { public abstract void visit(MethodVisitor mv); } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/BytecodeExpression.java0000644001501200150120000000325511707612044026302 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ExpressionTransformer; import org.objectweb.asm.MethodVisitor; /** * Represents some custom bytecode generation by the compiler * * @author James Strachan * @version $Revision$ */ public abstract class BytecodeExpression extends Expression { public static final BytecodeExpression NOP = new BytecodeExpression() { public void visit(MethodVisitor visitor) { //do nothing } }; public BytecodeExpression() { } public BytecodeExpression(ClassNode type) { super.setType(type); } public void visit(GroovyCodeVisitor visitor) { visitor.visitBytecodeExpression(this); } public abstract void visit(MethodVisitor mv); public Expression transformExpression(ExpressionTransformer transformer) { return this; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/ClassCompletionVerifier.java0000644001501200150120000006045511715031256027263 0ustar miguelmiguel/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. The initial API is made available under the terms of * the Common Public License v1.0 which is available at: * http://www.eclipse.org/legal/cpl-v10.html * Subsequent modifications are made available under the Apache 2.0 license. * * Contributors: * IBM - Initial API and implementation * Groovy community - subsequent modifications ******************************************************************************/ package org.codehaus.groovy.classgen; import java.util.List; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.GStringExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.control.SourceUnit; import org.objectweb.asm.Opcodes; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.Types; import static java.lang.reflect.Modifier.*; /** * ClassCompletionVerifier */ public class ClassCompletionVerifier extends ClassCodeVisitorSupport implements Opcodes { private ClassNode currentClass; private SourceUnit source; private boolean inConstructor = false; private boolean inStaticConstructor = false; public ClassCompletionVerifier(SourceUnit source) { this.source = source; } public ClassNode getClassNode() { return currentClass; } public void visitClass(ClassNode node) { ClassNode oldClass = currentClass; currentClass = node; checkImplementsAndExtends(node); if (source != null && !source.getErrorCollector().hasErrors()) { checkClassForIncorrectModifiers(node); checkInterfaceMethodVisibility(node); checkClassForOverwritingFinal(node); checkMethodsForIncorrectModifiers(node); checkMethodsForWeakerAccess(node); checkMethodsForOverridingFinal(node); checkNoAbstractMethodsNonabstractClass(node); checkGenericsUsage(node, node.getUnresolvedInterfaces()); checkGenericsUsage(node, node.getUnresolvedSuperClass()); } super.visitClass(node); currentClass = oldClass; } private void checkInterfaceMethodVisibility(ClassNode node) { if (!node.isInterface()) return; for (MethodNode method : node.getMethods()) { if (method.isPrivate()) { addError("Method '" + method.getName() + "' is private but should be public in " + getDescription(currentClass) + ".", method); } else if (method.isProtected()) { addError("Method '" + method.getName() + "' is protected but should be public in " + getDescription(currentClass) + ".", method); } } } private void checkNoAbstractMethodsNonabstractClass(ClassNode node) { if (isAbstract(node.getModifiers())) return; List abstractMethods = node.getAbstractMethods(); if (abstractMethods == null) return; for (MethodNode method : abstractMethods) { addError("Can't have an abstract method in a non-abstract class." + " The " + getDescription(node) + " must be declared abstract or" + " the " + getDescription(method) + " must be implemented.", node); } } private void checkClassForIncorrectModifiers(ClassNode node) { checkClassForAbstractAndFinal(node); checkClassForOtherModifiers(node); } private void checkClassForAbstractAndFinal(ClassNode node) { if (!isAbstract(node.getModifiers())) return; if (!isFinal(node.getModifiers())) return; if (node.isInterface()) { addError("The " + getDescription(node) + " must not be final. It is by definition abstract.", node); } else { addError("The " + getDescription(node) + " must not be both final and abstract.", node); } } private void checkClassForOtherModifiers(ClassNode node) { checkClassForModifier(node, isTransient(node.getModifiers()), "transient"); checkClassForModifier(node, isVolatile(node.getModifiers()), "volatile"); checkClassForModifier(node, isNative(node.getModifiers()), "native"); if (!(node instanceof InnerClassNode)) { checkClassForModifier(node, isStatic(node.getModifiers()), "static"); } // don't check synchronized here as it overlaps with ACC_SUPER } private void checkMethodForModifier(MethodNode node, boolean condition, String modifierName) { if (!condition) return; addError("The " + getDescription(node) + " has an incorrect modifier " + modifierName + ".", node); } private void checkClassForModifier(ClassNode node, boolean condition, String modifierName) { if (!condition) return; addError("The " + getDescription(node) + " has an incorrect modifier " + modifierName + ".", node); } private String getDescription(ClassNode node) { return (node.isInterface() ? "interface" : "class") + " '" + node.getName() + "'"; } private String getDescription(MethodNode node) { return "method '" + node.getTypeDescriptor() + "'"; } private String getDescription(FieldNode node) { return "field '" + node.getName() + "'"; } private void checkAbstractDeclaration(MethodNode methodNode) { if (!methodNode.isAbstract()) return; if (isAbstract(currentClass.getModifiers())) return; addError("Can't have an abstract method in a non-abstract class." + " The " + getDescription(currentClass) + " must be declared abstract or the method '" + methodNode.getTypeDescriptor() + "' must not be abstract.", methodNode); } private void checkClassForOverwritingFinal(ClassNode cn) { ClassNode superCN = cn.getSuperClass(); if (superCN == null) return; if (!isFinal(superCN.getModifiers())) return; StringBuilder msg = new StringBuilder(); msg.append("You are not allowed to overwrite the final "); msg.append(getDescription(superCN)); msg.append("."); addError(msg.toString(), cn); } private void checkImplementsAndExtends(ClassNode node) { ClassNode cn = node.getSuperClass(); if (cn.isInterface() && !node.isInterface()) { addError("You are not allowed to extend the " + getDescription(cn) + ", use implements instead.", node); } for (ClassNode anInterface : node.getInterfaces()) { cn = anInterface; if (!cn.isInterface()) { addError("You are not allowed to implement the " + getDescription(cn) + ", use extends instead.", node); } } } private void checkMethodsForIncorrectModifiers(ClassNode cn) { if (!cn.isInterface()) return; for (MethodNode method : cn.getMethods()) { if (isFinal(method.getModifiers())) { addError("The " + getDescription(method) + " from " + getDescription(cn) + " must not be final. It is by definition abstract.", method); } if (method.isStatic() && !isConstructor(method)) { addError("The " + getDescription(method) + " from " + getDescription(cn) + " must not be static. Only fields may be static in an interface.", method); } } } private void checkMethodsForWeakerAccess(ClassNode cn) { for (MethodNode method : cn.getMethods()) { checkMethodForWeakerAccessPrivileges(method, cn); } } private boolean isConstructor(MethodNode method) { return method.getName().equals(""); } private void checkMethodsForOverridingFinal(ClassNode cn) { for (MethodNode method : cn.getMethods()) { Parameter[] params = method.getParameters(); for (MethodNode superMethod : cn.getSuperClass().getMethods(method.getName())) { Parameter[] superParams = superMethod.getParameters(); if (!hasEqualParameterTypes(params, superParams)) continue; if (!isFinal(superMethod.getModifiers())) break; addInvalidUseOfFinalError(method, params, superMethod.getDeclaringClass()); return; } } } private void addInvalidUseOfFinalError(MethodNode method, Parameter[] parameters, ClassNode superCN) { StringBuilder msg = new StringBuilder(); msg.append("You are not allowed to override the final method ").append(method.getName()); msg.append("("); boolean needsComma = false; for (Parameter parameter : parameters) { if (needsComma) { msg.append(","); } else { needsComma = true; } msg.append(parameter.getType()); } msg.append(") from ").append(getDescription(superCN)); msg.append("."); addError(msg.toString(), method); } private void addWeakerAccessError(ClassNode cn, MethodNode method, Parameter[] parameters, MethodNode superMethod) { StringBuilder msg = new StringBuilder(); msg.append(method.getName()); msg.append("("); boolean needsComma = false; for (Parameter parameter : parameters) { if (needsComma) { msg.append(","); } else { needsComma = true; } msg.append(parameter.getType()); } msg.append(") in "); msg.append(cn.getName()); msg.append(" cannot override "); msg.append(superMethod.getName()); msg.append(" in "); msg.append(superMethod.getDeclaringClass().getName()); msg.append("; attempting to assign weaker access privileges; was "); msg.append(superMethod.isPublic() ? "public" : "protected"); addError(msg.toString(), method); } private boolean hasEqualParameterTypes(Parameter[] first, Parameter[] second) { if (first.length != second.length) return false; for (int i = 0; i < first.length; i++) { String ft = first[i].getType().getName(); String st = second[i].getType().getName(); if (ft.equals(st)) continue; return false; } return true; } protected SourceUnit getSourceUnit() { return source; } public void visitMethod(MethodNode node) { inConstructor = false; inStaticConstructor = node.isStaticConstructor(); checkAbstractDeclaration(node); checkRepetitiveMethod(node); checkOverloadingPrivateAndPublic(node); checkMethodModifiers(node); checkGenericsUsage(node, node.getParameters()); checkGenericsUsage(node, node.getReturnType()); super.visitMethod(node); } private void checkMethodModifiers(MethodNode node) { // don't check volatile here as it overlaps with ACC_BRIDGE // additional modifiers not allowed for interfaces if ((this.currentClass.getModifiers() & ACC_INTERFACE) != 0) { checkMethodForModifier(node, isStrict(node.getModifiers()), "strictfp"); checkMethodForModifier(node, isSynchronized(node.getModifiers()), "synchronized"); checkMethodForModifier(node, isNative(node.getModifiers()), "native"); } } private void checkMethodForWeakerAccessPrivileges(MethodNode mn, ClassNode cn) { Parameter[] params = mn.getParameters(); for (MethodNode superMethod : cn.getSuperClass().getMethods(mn.getName())) { Parameter[] superParams = superMethod.getParameters(); if (!hasEqualParameterTypes(params, superParams)) continue; if ((mn.isPrivate() && !superMethod.isPrivate()) || (mn.isProtected() && superMethod.isPublic())) { addWeakerAccessError(cn, mn, params, superMethod); return; } } } private void checkOverloadingPrivateAndPublic(MethodNode node) { if (isConstructor(node)) return; boolean hasPrivate = false; boolean hasPublic = false; for (MethodNode method : currentClass.getMethods(node.getName())) { if (method == node) continue; if (!method.getDeclaringClass().equals(node.getDeclaringClass())) continue; if (method.isPublic() || method.isProtected()) { hasPublic = true; } else { hasPrivate = true; } } if (hasPrivate && hasPublic) { addError("Mixing private and public/protected methods of the same name causes multimethods to be disabled and is forbidden to avoid surprising behaviour. Renaming the private methods will solve the problem.", node); } } private void checkRepetitiveMethod(MethodNode node) { if (isConstructor(node)) return; for (MethodNode method : currentClass.getMethods(node.getName())) { if (method == node) continue; if (!method.getDeclaringClass().equals(node.getDeclaringClass())) continue; Parameter[] p1 = node.getParameters(); Parameter[] p2 = method.getParameters(); if (p1.length != p2.length) continue; addErrorIfParamsAndReturnTypeEqual(p2, p1, node, method); } } private void addErrorIfParamsAndReturnTypeEqual(Parameter[] p2, Parameter[] p1, MethodNode node, MethodNode element) { boolean isEqual = true; for (int i = 0; i < p2.length; i++) { isEqual &= p1[i].getType().equals(p2[i].getType()); } isEqual &= node.getReturnType().equals(element.getReturnType()); if (isEqual) { addError("Repetitive method name/signature for " + getDescription(node) + " in " + getDescription(currentClass) + ".", node); } } public void visitField(FieldNode node) { if (currentClass.getDeclaredField(node.getName()) != node) { addError("The " + getDescription(node) + " is declared multiple times.", node); } checkInterfaceFieldModifiers(node); checkGenericsUsage(node, node.getType()); super.visitField(node); } public void visitProperty(PropertyNode node) { checkDuplicateProperties(node); checkGenericsUsage(node, node.getType()); super.visitProperty(node); } private void checkDuplicateProperties(PropertyNode node) { ClassNode cn = node.getDeclaringClass(); String name = node.getName(); String getterName = "get" + MetaClassHelper.capitalize(name); if (Character.isUpperCase(name.charAt(0))) { for (PropertyNode propNode : cn.getProperties()) { String otherName = propNode.getField().getName(); String otherGetterName = "get" + MetaClassHelper.capitalize(otherName); if (node != propNode && getterName.equals(otherGetterName)) { String msg = "The field " + name + " and " + otherName + " on the class " + cn.getName() + " will result in duplicate JavaBean properties, which is not allowed"; addError(msg, node); } } } } private void checkInterfaceFieldModifiers(FieldNode node) { if (!currentClass.isInterface()) return; if ((node.getModifiers() & (ACC_PUBLIC | ACC_STATIC | ACC_FINAL)) == 0 || (node.getModifiers() & (ACC_PRIVATE | ACC_PROTECTED)) != 0) { addError("The " + getDescription(node) + " is not 'public static final' but is defined in " + getDescription(currentClass) + ".", node); } } public void visitBinaryExpression(BinaryExpression expression) { if (expression.getOperation().getType() == Types.LEFT_SQUARE_BRACKET && expression.getRightExpression() instanceof MapEntryExpression) { addError("You tried to use a map entry for an index operation, this is not allowed. " + "Maybe something should be set in parentheses or a comma is missing?", expression.getRightExpression()); } super.visitBinaryExpression(expression); switch (expression.getOperation().getType()) { case Types.EQUAL: // = assignment case Types.BITWISE_AND_EQUAL: case Types.BITWISE_OR_EQUAL: case Types.BITWISE_XOR_EQUAL: case Types.PLUS_EQUAL: case Types.MINUS_EQUAL: case Types.MULTIPLY_EQUAL: case Types.DIVIDE_EQUAL: case Types.INTDIV_EQUAL: case Types.MOD_EQUAL: case Types.POWER_EQUAL: case Types.LEFT_SHIFT_EQUAL: case Types.RIGHT_SHIFT_EQUAL: case Types.RIGHT_SHIFT_UNSIGNED_EQUAL: checkFinalFieldAccess(expression.getLeftExpression()); break; default: break; } } private void checkFinalFieldAccess(Expression expression) { if (!(expression instanceof VariableExpression) && !(expression instanceof PropertyExpression)) return; Variable v = null; if (expression instanceof VariableExpression) { VariableExpression ve = (VariableExpression) expression; v = ve.getAccessedVariable(); } else { PropertyExpression propExp = ((PropertyExpression) expression); Expression objectExpression = propExp.getObjectExpression(); if (objectExpression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) objectExpression; if (varExp.isThisExpression()) { v = currentClass.getDeclaredField(propExp.getPropertyAsString()); } } } if (v instanceof FieldNode) { FieldNode fn = (FieldNode) v; /* * if it is static final but not accessed inside a static constructor, or, * if it is an instance final but not accessed inside a instance constructor, it is an error */ boolean isFinal = fn.isFinal(); boolean isStatic = fn.isStatic(); boolean error = isFinal && ((isStatic && !inStaticConstructor) || (!isStatic && !inConstructor)); if (error) addError("cannot modify" + (isStatic ? " static" : "") + " final field '" + fn.getName() + "' outside of " + (isStatic ? "static initialization block." : "constructor."), expression); } } public void visitConstructor(ConstructorNode node) { inConstructor = true; inStaticConstructor = node.isStaticConstructor(); checkGenericsUsage(node, node.getParameters()); super.visitConstructor(node); } public void visitCatchStatement(CatchStatement cs) { if (!(cs.getExceptionType().isDerivedFrom(ClassHelper.make(Throwable.class)))) { addError("Catch statement parameter type is not a subclass of Throwable.", cs); } super.visitCatchStatement(cs); } public void visitMethodCallExpression(MethodCallExpression mce) { super.visitMethodCallExpression(mce); Expression aexp = mce.getArguments(); if (aexp instanceof TupleExpression) { TupleExpression arguments = (TupleExpression) aexp; for (Expression e : arguments.getExpressions()) { checkForInvalidDeclaration(e); } } else { checkForInvalidDeclaration(aexp); } } @Override public void visitDeclarationExpression(DeclarationExpression expression) { super.visitDeclarationExpression(expression); if (expression.isMultipleAssignmentDeclaration()) return; checkInvalidDeclarationModifier(expression, ACC_ABSTRACT, "abstract"); checkInvalidDeclarationModifier(expression, ACC_NATIVE, "native"); checkInvalidDeclarationModifier(expression, ACC_PRIVATE, "private"); checkInvalidDeclarationModifier(expression, ACC_PROTECTED, "protected"); checkInvalidDeclarationModifier(expression, ACC_PUBLIC, "public"); checkInvalidDeclarationModifier(expression, ACC_STATIC, "static"); checkInvalidDeclarationModifier(expression, ACC_STRICT, "strictfp"); checkInvalidDeclarationModifier(expression, ACC_SYNCHRONIZED, "synchronized"); checkInvalidDeclarationModifier(expression, ACC_TRANSIENT, "transient"); checkInvalidDeclarationModifier(expression, ACC_VOLATILE, "volatile"); } private void checkInvalidDeclarationModifier(DeclarationExpression expression, int modifier, String modName) { if ((expression.getVariableExpression().getModifiers() & modifier) != 0) { addError("Modifier '" + modName + "' not allowed here.", expression); } } private void checkForInvalidDeclaration(Expression exp) { if (!(exp instanceof DeclarationExpression)) return; addError("Invalid use of declaration inside method call.", exp); } public void visitConstantExpression(ConstantExpression expression) { super.visitConstantExpression(expression); checkStringExceedingMaximumLength(expression); } public void visitGStringExpression(GStringExpression expression) { super.visitGStringExpression(expression); for (ConstantExpression ce : expression.getStrings()) { checkStringExceedingMaximumLength(ce); } } private void checkStringExceedingMaximumLength(ConstantExpression expression) { Object value = expression.getValue(); if (value instanceof String) { String s = (String) value; if (s.length() > 65535) { addError("String too long. The given string is " + s.length() + " Unicode code units long, but only a maximum of 65535 is allowed.", expression); } } } private void checkGenericsUsage(ASTNode ref, ClassNode[] nodes) { for (ClassNode node : nodes) { checkGenericsUsage(ref, node); } } private void checkGenericsUsage(ASTNode ref, Parameter[] params) { for (Parameter p : params) { checkGenericsUsage(ref, p.getType()); } } private void checkGenericsUsage(ASTNode ref, ClassNode node) { if (node.isArray()) { checkGenericsUsage(ref, node.getComponentType()); } else if (!node.isRedirectNode() && node.isUsingGenerics()) { addError( "A transform used a generics containing ClassNode "+ node + " " + "for "+getRefDescriptor(ref) + "directly. You are not suppposed to do this. " + "Please create a new ClassNode refering to the old ClassNode " + "and use the new ClassNode instead of the old one. Otherwise " + "the compiler will create wrong descriptors and a potential " + "NullPointerException in TypeResolver in the OpenJDK. If this is " + "not your own doing, please report this bug to the writer of the " + "transform.", ref); } } private String getRefDescriptor(ASTNode ref) { if (ref instanceof FieldNode) { FieldNode f = (FieldNode) ref; return "the field "+f.getName()+" "; } else if (ref instanceof PropertyNode) { PropertyNode p = (PropertyNode) ref; return "the property "+p.getName()+" "; } else if (ref instanceof ConstructorNode) { return "the constructor "+ref.getText()+" "; } else if (ref instanceof MethodNode) { return "the method "+ref.getText()+" "; } else if (ref instanceof ClassNode) { return "the super class "+ref+" "; } return " "; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/Verifier.java0000644001501200150120000020263111715031256024235 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import groovy.lang.MetaClass; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.classgen.asm.MopWriter; import org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.ClassNodeSkip; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.syntax.RuntimeParserException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.reflection.ClassInfo; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; /** * Verifies the AST node and adds any defaulted AST code before * bytecode generation occurs. * * @author James Strachan * @version $Revision$ */ public class Verifier implements GroovyClassVisitor, Opcodes { public static final String STATIC_METACLASS_BOOL = "__$stMC"; public static final String SWAP_INIT = "__$swapInit"; public static final String __TIMESTAMP = "__timeStamp"; public static final String __TIMESTAMP__ = "__timeStamp__239_neverHappen"; private static final Parameter[] INVOKE_METHOD_PARAMS = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "method"), new Parameter(ClassHelper.OBJECT_TYPE, "arguments") }; private static final Parameter[] SET_PROPERTY_PARAMS = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "property"), new Parameter(ClassHelper.OBJECT_TYPE, "value") }; private static final Parameter[] GET_PROPERTY_PARAMS = new Parameter[]{ new Parameter(ClassHelper.STRING_TYPE, "property") }; private static final Parameter[] SET_METACLASS_PARAMS = new Parameter[]{ new Parameter(ClassHelper.METACLASS_TYPE, "mc") }; private ClassNode classNode; private MethodNode methodNode; public ClassNode getClassNode() { return classNode; } public MethodNode getMethodNode() { return methodNode; } private FieldNode setMetaClassFieldIfNotExists(ClassNode node, FieldNode metaClassField) { if (metaClassField != null) return metaClassField; final String classInternalName = BytecodeHelper.getClassInternalName(node); metaClassField = node.addField("metaClass", ACC_PRIVATE | ACC_TRANSIENT | ACC_SYNTHETIC, ClassHelper.METACLASS_TYPE, new BytecodeExpression(ClassHelper.METACLASS_TYPE) { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "$getStaticMetaClass", "()Lgroovy/lang/MetaClass;"); }}); metaClassField.setSynthetic(true); return metaClassField; } private FieldNode getMetaClassField(ClassNode node) { FieldNode ret = node.getDeclaredField("metaClass"); if (ret != null) { ClassNode mcFieldType = ret.getType(); if (!mcFieldType.equals(ClassHelper.METACLASS_TYPE)) { throw new RuntimeParserException("The class " + node.getName() + " cannot declare field 'metaClass' of type " + mcFieldType.getName() + " as it needs to be of " + "the type " + ClassHelper.METACLASS_TYPE.getName() + " for internal groovy purposes", ret); } return ret; } ClassNode current = node; while (current != ClassHelper.OBJECT_TYPE) { current = current.getSuperClass(); if (current == null) break; ret = current.getDeclaredField("metaClass"); if (ret == null) continue; if (Modifier.isPrivate(ret.getModifiers())) continue; return ret; } return null; } /** * add code to implement GroovyObject * * @param node */ public void visitClass(final ClassNode node) { this.classNode = node; if ((classNode.getModifiers() & Opcodes.ACC_INTERFACE) > 0) { //interfaces have no constructors, but this code expects one, //so create a dummy and don't add it to the class node ConstructorNode dummy = new ConstructorNode(0, null); addInitialization(node, dummy); node.visitContents(this); if (classNode.getNodeMetaData(ClassNodeSkip.class)==null) { classNode.setNodeMetaData(ClassNodeSkip.class,true); } return; } ClassNode[] classNodes = classNode.getInterfaces(); List interfaces = new ArrayList(); for (ClassNode classNode : classNodes) { interfaces.add(classNode.getName()); } Set interfaceSet = new HashSet(interfaces); if (interfaceSet.size() != interfaces.size()) { throw new RuntimeParserException("Duplicate interfaces in implements list: " + interfaces, classNode); } addDefaultParameterMethods(node); addDefaultParameterConstructors(node); final String classInternalName = BytecodeHelper.getClassInternalName(node); addStaticMetaClassField(node, classInternalName); boolean knownSpecialCase = node.isDerivedFrom(ClassHelper.GSTRING_TYPE) || node.isDerivedFrom(ClassHelper.GROOVY_OBJECT_SUPPORT_TYPE); addFastPathHelperFieldsAndHelperMethod(node, classInternalName, knownSpecialCase); if (!knownSpecialCase) addGroovyObjectInterfaceAndMethods(node, classInternalName); addDefaultConstructor(node); // add a static timestamp field to the class if (!(node instanceof InnerClassNode)) addTimeStamp(node); addInitialization(node); checkReturnInObjectInitializer(node.getObjectInitializerStatements()); node.getObjectInitializerStatements().clear(); addCovariantMethods(node); node.visitContents(this); } private FieldNode checkFieldDoesNotExist(ClassNode node, String fieldName) { FieldNode ret = node.getDeclaredField(fieldName); if (ret != null) { if ( Modifier.isPublic(ret.getModifiers()) && ret.getType().redirect()==ClassHelper.boolean_TYPE) { return ret; } throw new RuntimeParserException("The class " + node.getName() + " cannot declare field '"+fieldName+"' as this" + " field is needed for internal groovy purposes", ret); } return null; } private void addFastPathHelperFieldsAndHelperMethod(ClassNode node, final String classInternalName, boolean knownSpecialCase) { if (node.getNodeMetaData(ClassNodeSkip.class)!=null) return; FieldNode stMCB = checkFieldDoesNotExist(node,STATIC_METACLASS_BOOL); if (stMCB==null) { stMCB = node.addField( STATIC_METACLASS_BOOL, ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC | ACC_TRANSIENT, ClassHelper.boolean_TYPE, null); stMCB.setSynthetic(true); } } protected void addDefaultConstructor(ClassNode node) { if (!node.getDeclaredConstructors().isEmpty()) return; BlockStatement empty = new BlockStatement(); empty.setSourcePosition(node); ConstructorNode constructor = new ConstructorNode(ACC_PUBLIC, empty); constructor.setSourcePosition(node); constructor.setHasNoRealSourcePosition(true); node.addConstructor(constructor); } private void addStaticMetaClassField(ClassNode node, final String classInternalName) { String _staticClassInfoFieldName = "$staticClassInfo"; while (node.getDeclaredField(_staticClassInfoFieldName) != null) _staticClassInfoFieldName = _staticClassInfoFieldName + "$"; final String staticMetaClassFieldName = _staticClassInfoFieldName; FieldNode staticMetaClassField = node.addField(staticMetaClassFieldName, ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC, ClassHelper.make(ClassInfo.class, false), null); staticMetaClassField.setSynthetic(true); node.addSyntheticMethod( "$getStaticMetaClass", ACC_PROTECTED, ClassHelper.make(MetaClass.class), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); mv.visitMethodInsn(INVOKESTATIC, classInternalName, "$get$$class$" + classInternalName.replaceAll("\\/", "\\$"), "()Ljava/lang/Class;"); Label l1 = new Label(); mv.visitJumpInsn(IF_ACMPEQ, l1); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/ScriptBytecodeAdapter", "initMetaClass", "(Ljava/lang/Object;)Lgroovy/lang/MetaClass;"); mv.visitInsn(ARETURN); mv.visitLabel(l1); mv.visitFieldInsn(GETSTATIC, classInternalName, staticMetaClassFieldName, "Lorg/codehaus/groovy/reflection/ClassInfo;"); mv.visitVarInsn(ASTORE, 1); mv.visitVarInsn(ALOAD, 1); Label l0 = new Label(); mv.visitJumpInsn(IFNONNULL, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/reflection/ClassInfo", "getClassInfo", "(Ljava/lang/Class;)Lorg/codehaus/groovy/reflection/ClassInfo;"); mv.visitInsn(DUP); mv.visitVarInsn(ASTORE, 1); mv.visitFieldInsn(PUTSTATIC, classInternalName, staticMetaClassFieldName, "Lorg/codehaus/groovy/reflection/ClassInfo;"); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/ClassInfo", "getMetaClass", "()Lgroovy/lang/MetaClass;"); mv.visitInsn(ARETURN); } }) ); } protected void addGroovyObjectInterfaceAndMethods(ClassNode node, final String classInternalName) { if (!node.isDerivedFromGroovyObject()) node.addInterface(ClassHelper.make(GroovyObject.class)); FieldNode metaClassField = getMetaClassField(node); if (!node.hasMethod("getMetaClass", Parameter.EMPTY_ARRAY)) { metaClassField = setMetaClassFieldIfNotExists(node, metaClassField); addMethod(node, !Modifier.isAbstract(node.getModifiers()), "getMetaClass", ACC_PUBLIC, ClassHelper.METACLASS_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { Label nullLabel = new Label(); /** * the code is: * if (this.metaClass==null) { * this.metaClass = this.$getStaticMetaClass * return this.metaClass * } else { * return this.metaClass * } * with the optimization that the result of the * first this.metaClass is duped on the operand * stack and reused for the return in the else part */ mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classInternalName, "metaClass", "Lgroovy/lang/MetaClass;"); mv.visitInsn(DUP); mv.visitJumpInsn(IFNULL, nullLabel); mv.visitInsn(ARETURN); mv.visitLabel(nullLabel); mv.visitInsn(POP); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "$getStaticMetaClass", "()Lgroovy/lang/MetaClass;"); mv.visitFieldInsn(PUTFIELD, classInternalName, "metaClass", "Lgroovy/lang/MetaClass;"); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classInternalName, "metaClass", "Lgroovy/lang/MetaClass;"); mv.visitInsn(ARETURN); } }) ); } Parameter[] parameters = new Parameter[]{new Parameter(ClassHelper.METACLASS_TYPE, "mc")}; if (!node.hasMethod("setMetaClass", parameters)) { metaClassField = setMetaClassFieldIfNotExists(node, metaClassField); Statement setMetaClassCode; if (Modifier.isFinal(metaClassField.getModifiers())) { ConstantExpression text = new ConstantExpression("cannot set read-only meta class"); ConstructorCallExpression cce = new ConstructorCallExpression(ClassHelper.make(IllegalArgumentException.class), text); setMetaClassCode = new ExpressionStatement(cce); } else { List list = new ArrayList(); list.add(new BytecodeInstruction() { public void visit(MethodVisitor mv) { /** * the code is (meta class is stored in 1): * this.metaClass = <1> */ mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitFieldInsn(PUTFIELD, classInternalName, "metaClass", "Lgroovy/lang/MetaClass;"); mv.visitInsn(RETURN); } }); setMetaClassCode = new BytecodeSequence(list); } addMethod(node, !Modifier.isAbstract(node.getModifiers()), "setMetaClass", ACC_PUBLIC, ClassHelper.VOID_TYPE, SET_METACLASS_PARAMS, ClassNode.EMPTY_ARRAY, setMetaClassCode ); } if (!node.hasMethod("invokeMethod", INVOKE_METHOD_PARAMS)) { VariableExpression vMethods = new VariableExpression("method"); VariableExpression vArguments = new VariableExpression("arguments"); VariableScope blockScope = new VariableScope(); blockScope.putReferencedLocalVariable(vMethods); blockScope.putReferencedLocalVariable(vArguments); addMethod(node, !Modifier.isAbstract(node.getModifiers()), "invokeMethod", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, INVOKE_METHOD_PARAMS, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "getMetaClass", "()Lgroovy/lang/MetaClass;"); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEINTERFACE, "groovy/lang/MetaClass", "invokeMethod", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(ARETURN); } }) ); } if (!node.hasMethod("getProperty", GET_PROPERTY_PARAMS)) { addMethod(node, !Modifier.isAbstract(node.getModifiers()), "getProperty", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, GET_PROPERTY_PARAMS, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "getMetaClass", "()Lgroovy/lang/MetaClass;"); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEINTERFACE, "groovy/lang/MetaClass", "getProperty", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;"); mv.visitInsn(ARETURN); } }) ); } if (!node.hasMethod("setProperty", SET_PROPERTY_PARAMS)) { addMethod(node, !Modifier.isAbstract(node.getModifiers()), "setProperty", ACC_PUBLIC, ClassHelper.VOID_TYPE, SET_PROPERTY_PARAMS, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "getMetaClass", "()Lgroovy/lang/MetaClass;"); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEINTERFACE, "groovy/lang/MetaClass", "setProperty", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V"); mv.visitInsn(RETURN); } }) ); } } /** * Helper method to add a new method to a ClassNode. Depending on the shouldBeSynthetic flag the * call will either be made to ClassNode.addSyntheticMethod() or ClassNode.addMethod(). If a non-synthetic method * is to be added the ACC_SYNTHETIC modifier is removed if it has been accidentally supplied. */ protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { if (shouldBeSynthetic) { node.addSyntheticMethod(name, modifiers, returnType, parameters, exceptions, code); } else { node.addMethod(name, modifiers & ~ACC_SYNTHETIC, returnType, parameters, exceptions, code); } } protected void addTimeStamp(ClassNode node) { if (node.getDeclaredField(Verifier.__TIMESTAMP) == null) { // in case if verifier visited the call already FieldNode timeTagField = new FieldNode( Verifier.__TIMESTAMP, ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC, ClassHelper.long_TYPE, //"", node, new ConstantExpression(System.currentTimeMillis())); // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final long __timeStamp = " + System.currentTimeMillis() + "L"); timeTagField.setSynthetic(true); node.addField(timeTagField); timeTagField = new FieldNode( Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()), ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC, ClassHelper.long_TYPE, //"", node, new ConstantExpression((long) 0)); // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final long __timeStamp = " + System.currentTimeMillis() + "L"); timeTagField.setSynthetic(true); node.addField(timeTagField); } } private void checkReturnInObjectInitializer(List init) { CodeVisitorSupport cvs = new CodeVisitorSupport() { @Override public void visitClosureExpression(ClosureExpression expression) { // return is OK in closures in object initializers } public void visitReturnStatement(ReturnStatement statement) { throw new RuntimeParserException("'return' is not allowed in object initializer", statement); } }; for (Iterator iterator = init.iterator(); iterator.hasNext();) { Statement stm = (Statement) iterator.next(); stm.visit(cvs); } } public void visitConstructor(ConstructorNode node) { CodeVisitorSupport checkSuper = new CodeVisitorSupport() { boolean firstMethodCall = true; String type = null; public void visitMethodCallExpression(MethodCallExpression call) { if (!firstMethodCall) return; firstMethodCall = false; String name = call.getMethodAsString(); // the name might be null if the method name is a GString for example if (name == null) return; if (!name.equals("super") && !name.equals("this")) return; type = name; call.getArguments().visit(this); type = null; } public void visitConstructorCallExpression(ConstructorCallExpression call) { if (!call.isSpecialCall()) return; type = call.getText(); call.getArguments().visit(this); type = null; } public void visitVariableExpression(VariableExpression expression) { if (type == null) return; String name = expression.getName(); if (!name.equals("this") && !name.equals("super")) return; throw new RuntimeParserException("cannot reference " + name + " inside of " + type + "(....) before supertype constructor has been called", expression); } }; Statement s = node.getCode(); if (s == null) { return; } else { s.visit(new VerifierCodeVisitor(this)); } s.visit(checkSuper); } public void visitMethod(MethodNode node) { //GROOVY-3712 - if it's an MOP method, it's an error as they aren't supposed to exist before ACG is invoked if(MopWriter.isMopMethod(node.getName())) { throw new RuntimeParserException("Found unexpected MOP methods in the class node for " + classNode.getName() + "(" + node.getName() + ")", classNode); } this.methodNode = node; adjustTypesIfStaticMainMethod(node); addReturnIfNeeded(node); Statement statement; statement = node.getCode(); if (statement != null) statement.visit(new VerifierCodeVisitor(this)); } private void adjustTypesIfStaticMainMethod(MethodNode node) { if (node.getName().equals("main") && node.isStatic()) { Parameter[] params = node.getParameters(); if (params.length == 1) { Parameter param = params[0]; if (param.getType() == null || param.getType() == ClassHelper.OBJECT_TYPE) { param.setType(ClassHelper.STRING_TYPE.makeArray()); ClassNode returnType = node.getReturnType(); if (returnType == ClassHelper.OBJECT_TYPE) { node.setReturnType(ClassHelper.VOID_TYPE); } } } } } protected void addReturnIfNeeded(MethodNode node) { ReturnAdder.addReturnIfNeeded(node); } public void visitField(FieldNode node) { } private boolean methodNeedsReplacement(MethodNode m) { // no method found, we need to replace if (m == null) return true; // method is in current class, nothing to be done if (m.getDeclaringClass() == this.getClassNode()) return false; // do not overwrite final if ((m.getModifiers() & ACC_FINAL) != 0) return false; return true; } public void visitProperty(PropertyNode node) { String name = node.getName(); FieldNode field = node.getField(); int propNodeModifiers = node.getModifiers(); String getterName = "get" + capitalize(name); String setterName = "set" + capitalize(name); // GROOVY-3726: clear volatile, transient modifiers so that they don't get applied to methods if ((propNodeModifiers & Modifier.VOLATILE) != 0) { propNodeModifiers = propNodeModifiers - Modifier.VOLATILE; } if ((propNodeModifiers & Modifier.TRANSIENT) != 0) { propNodeModifiers = propNodeModifiers - Modifier.TRANSIENT; } Statement getterBlock = node.getGetterBlock(); if (getterBlock == null) { MethodNode getter = classNode.getGetterMethod(getterName); if (getter == null && ClassHelper.boolean_TYPE == node.getType()) { String secondGetterName = "is" + capitalize(name); getter = classNode.getGetterMethod(secondGetterName); } if (!node.isPrivate() && methodNeedsReplacement(getter)) { getterBlock = createGetterBlock(node, field); } } Statement setterBlock = node.getSetterBlock(); if (setterBlock == null) { // 2nd arg false below: though not usual, allow setter with non-void return type MethodNode setter = classNode.getSetterMethod(setterName, false); if (!node.isPrivate() && (propNodeModifiers & ACC_FINAL) == 0 && methodNeedsReplacement(setter)) { setterBlock = createSetterBlock(node, field); } } if (getterBlock != null) { MethodNode getter = new MethodNode(getterName, propNodeModifiers, node.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock); getter.setSynthetic(true); addPropertyMethod(getter); visitMethod(getter); if (ClassHelper.boolean_TYPE == node.getType() || ClassHelper.Boolean_TYPE == node.getType()) { String secondGetterName = "is" + capitalize(name); MethodNode secondGetter = new MethodNode(secondGetterName, propNodeModifiers, node.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock); secondGetter.setSynthetic(true); addPropertyMethod(secondGetter); visitMethod(secondGetter); } } if (setterBlock != null) { Parameter[] setterParameterTypes = {new Parameter(node.getType(), "value")}; MethodNode setter = new MethodNode(setterName, propNodeModifiers, ClassHelper.VOID_TYPE, setterParameterTypes, ClassNode.EMPTY_ARRAY, setterBlock); setter.setSynthetic(true); addPropertyMethod(setter); visitMethod(setter); } } protected void addPropertyMethod(MethodNode method) { classNode.addMethod(method); // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one List abstractMethods = classNode.getAbstractMethods(); if (abstractMethods==null) return; String methodName = method.getName(); Parameter[] parameters = method.getParameters(); ClassNode methodReturnType = method.getReturnType(); for (MethodNode node : abstractMethods) { if (node.getName().equals(methodName) && node.getParameters().length==parameters.length) { if (parameters.length==1) { // setter ClassNode abstractMethodParameterType = node.getParameters()[0].getType(); ClassNode methodParameterType = parameters[0].getType(); if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) { continue; } } ClassNode nodeReturnType = node.getReturnType(); if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) { continue; } // matching method, remove abstract status and use the same body node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT); node.setCode(method.getCode()); } } } // Implementation methods //------------------------------------------------------------------------- public interface DefaultArgsAction { void call(ArgumentListExpression arguments, Parameter[] newParams, MethodNode method); } /** * Creates a new helper method for each combination of default parameter expressions */ protected void addDefaultParameterMethods(final ClassNode node) { List methods = new ArrayList(node.getMethods()); addDefaultParameters(methods, new DefaultArgsAction() { public void call(ArgumentListExpression arguments, Parameter[] newParams, MethodNode method) { MethodCallExpression expression = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, method.getName(), arguments); expression.setImplicitThis(true); Statement code = null; if (method.isVoidMethod()) { code = new ExpressionStatement(expression); } else { code = new ReturnStatement(expression); } MethodNode newMethod = new MethodNode(method.getName(), method.getModifiers(), method.getReturnType(), newParams, method.getExceptions(), code); List annotations = method.getAnnotations(); if(annotations != null) { newMethod.addAnnotations(annotations); } MethodNode oldMethod = node.getDeclaredMethod(method.getName(), newParams); if (oldMethod != null) { throw new RuntimeParserException( "The method with default parameters \"" + method.getTypeDescriptor() + "\" defines a method \"" + newMethod.getTypeDescriptor() + "\" that is already defined.", method); } addPropertyMethod(newMethod); newMethod.setGenericsTypes(method.getGenericsTypes()); } }); } protected void addDefaultParameterConstructors(final ClassNode node) { List methods = new ArrayList(node.getDeclaredConstructors()); addDefaultParameters(methods, new DefaultArgsAction() { public void call(ArgumentListExpression arguments, Parameter[] newParams, MethodNode method) { ConstructorNode ctor = (ConstructorNode) method; ConstructorCallExpression expression = new ConstructorCallExpression(ClassNode.THIS, arguments); Statement code = new ExpressionStatement(expression); addConstructor(newParams, ctor, code, node); } }); } protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) { node.addConstructor(ctor.getModifiers(), newParams, ctor.getExceptions(), code); } /** * Creates a new helper method for each combination of default parameter expressions */ protected void addDefaultParameters(List methods, DefaultArgsAction action) { for (Iterator iter = methods.iterator(); iter.hasNext();) { MethodNode method = (MethodNode) iter.next(); if (method.hasDefaultValue()) { addDefaultParameters(action, method); } } } protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) { Parameter[] parameters = method.getParameters(); int counter = 0; List paramValues = new ArrayList(); int size = parameters.length; for (int i = size - 1; i >= 0; i--) { Parameter parameter = parameters[i]; if (parameter != null && parameter.hasInitialExpression()) { paramValues.add(Integer.valueOf(i)); paramValues.add( new CastExpression( parameter.getType(), parameter.getInitialExpression() ) ); counter++; } } for (int j = 1; j <= counter; j++) { Parameter[] newParams = new Parameter[parameters.length - j]; ArgumentListExpression arguments = new ArgumentListExpression(); int index = 0; int k = 1; for (int i = 0; i < parameters.length; i++) { if (k > counter - j && parameters[i] != null && parameters[i].hasInitialExpression()) { arguments.addExpression( new CastExpression( parameters[i].getType(), parameters[i].getInitialExpression() ) ); k++; } else if (parameters[i] != null && parameters[i].hasInitialExpression()) { newParams[index++] = parameters[i]; arguments.addExpression( new CastExpression( parameters[i].getType(), new VariableExpression(parameters[i].getName()) ) ); k++; } else { newParams[index++] = parameters[i]; arguments.addExpression( new CastExpression( parameters[i].getType(), new VariableExpression(parameters[i].getName()) ) ); } } action.call(arguments, newParams, method); } for (Parameter parameter : parameters) { // remove default expression parameter.setInitialExpression(null); } } protected void addClosureCode(InnerClassNode node) { // add a new invoke } protected void addInitialization(final ClassNode node) { boolean addSwapInit = moveOptimizedConstantsInitialization(node); for (ConstructorNode cn : node.getDeclaredConstructors()) { addInitialization(node, cn); } if (addSwapInit) { BytecodeSequence seq = new BytecodeSequence( new BytecodeInstruction() { @Override public void visit(MethodVisitor mv) { mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(node), SWAP_INIT, "()V"); } }); List swapCall= new ArrayList(1); swapCall.add(seq); node.addStaticInitializerStatements(swapCall, true); } } protected void addInitialization(ClassNode node, ConstructorNode constructorNode) { Statement firstStatement = constructorNode.getFirstStatement(); // if some transformation decided to generate constructor then it probably knows who it does if (firstStatement instanceof BytecodeSequence) return; ConstructorCallExpression first = getFirstIfSpecialConstructorCall(firstStatement); // in case of this(...) let the other constructor do the init if (first != null && (first.isThisCall())) return; List statements = new ArrayList(); List staticStatements = new ArrayList(); final boolean isEnum = node.isEnum(); List initStmtsAfterEnumValuesInit = new ArrayList(); Set explicitStaticPropsInEnum = new HashSet(); if (isEnum) { for (PropertyNode propNode : node.getProperties()) { if (!propNode.isSynthetic() && propNode.getField().isStatic()) { explicitStaticPropsInEnum.add(propNode.getField().getName()); } } for (FieldNode fieldNode : node.getFields()) { if (!fieldNode.isSynthetic() && fieldNode.isStatic() && fieldNode.getType() != node) { explicitStaticPropsInEnum.add(fieldNode.getName()); } } } for (FieldNode fn : node.getFields()) { addFieldInitialization(statements, staticStatements, fn, isEnum, initStmtsAfterEnumValuesInit, explicitStaticPropsInEnum); } statements.addAll(node.getObjectInitializerStatements()); Statement code = constructorNode.getCode(); BlockStatement block = new BlockStatement(); List otherStatements = block.getStatements(); if (code instanceof BlockStatement) { block = (BlockStatement) code; otherStatements = block.getStatements(); } else if (code != null) { otherStatements.add(code); } if (!otherStatements.isEmpty()) { if (first != null) { // it is super(..) since this(..) is already covered otherStatements.remove(0); statements.add(0, firstStatement); } Statement stmtThis$0 = getImplicitThis$0StmtIfInnerClass(otherStatements); if (stmtThis$0 != null) { // since there can be field init statements that depend on method/property dispatching // that uses this$0, it needs to bubble up before the super call itself (GROOVY-4471) statements.add(0, stmtThis$0); } statements.addAll(otherStatements); } BlockStatement newBlock = new BlockStatement(statements, block.getVariableScope()); newBlock.setSourcePosition(block); constructorNode.setCode(newBlock); if (!staticStatements.isEmpty()) { if (isEnum) { /* * GROOVY-3161: initialize statements for explicitly declared static fields * inside an enum should come after enum values are initialized */ staticStatements.removeAll(initStmtsAfterEnumValuesInit); node.addStaticInitializerStatements(staticStatements, true); if (!initStmtsAfterEnumValuesInit.isEmpty()) { node.positionStmtsAfterEnumInitStmts(initStmtsAfterEnumValuesInit); } } else { node.addStaticInitializerStatements(staticStatements, true); } } } /* * when InnerClassVisitor adds this.this$0 = $p$n, it adds it as a BlockStatement having that * ExpressionStatement */ private Statement getImplicitThis$0StmtIfInnerClass(List otherStatements) { if (!(classNode instanceof InnerClassNode)) return null; for (Statement stmt : otherStatements) { if (stmt instanceof BlockStatement) { List stmts = ((BlockStatement) stmt).getStatements(); for (Statement bstmt : stmts) { if (bstmt instanceof ExpressionStatement) { if (extractImplicitThis$0StmtIfInnerClassFromExpression(stmts, bstmt)) return bstmt; } } } else if (stmt instanceof ExpressionStatement) { if (extractImplicitThis$0StmtIfInnerClassFromExpression(otherStatements, stmt)) return stmt; } } return null; } private boolean extractImplicitThis$0StmtIfInnerClassFromExpression(final List stmts, final Statement bstmt) { Expression expr = ((ExpressionStatement) bstmt).getExpression(); if (expr instanceof BinaryExpression) { Expression lExpr = ((BinaryExpression) expr).getLeftExpression(); if (lExpr instanceof FieldExpression) { if ("this$0".equals(((FieldExpression) lExpr).getFieldName())) { stmts.remove(bstmt); // remove from here and let the caller reposition it return true; } } } return false; } private ConstructorCallExpression getFirstIfSpecialConstructorCall(Statement code) { if (code == null || !(code instanceof ExpressionStatement)) return null; Expression expression = ((ExpressionStatement) code).getExpression(); if (!(expression instanceof ConstructorCallExpression)) return null; ConstructorCallExpression cce = (ConstructorCallExpression) expression; if (cce.isSpecialCall()) return cce; return null; } protected void addFieldInitialization(List list, List staticList, FieldNode fieldNode, boolean isEnumClassNode, List initStmtsAfterEnumValuesInit, Set explicitStaticPropsInEnum) { Expression expression = fieldNode.getInitialExpression(); if (expression != null) { final FieldExpression fe = new FieldExpression(fieldNode); if (fieldNode.getType().equals(ClassHelper.REFERENCE_TYPE) && ((fieldNode.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0)) { fe.setUseReferenceDirectly(true); } ExpressionStatement statement = new ExpressionStatement( new BinaryExpression( fe, Token.newSymbol(Types.EQUAL, fieldNode.getLineNumber(), fieldNode.getColumnNumber()), expression)); if (fieldNode.isStatic()) { // GROOVY-3311: pre-defined constants added by groovy compiler for numbers/characters should be // initialized first so that code dependent on it does not see their values as empty Expression initialValueExpression = fieldNode.getInitialValueExpression(); if (initialValueExpression instanceof ConstantExpression) { ConstantExpression cexp = (ConstantExpression) initialValueExpression; cexp = transformToPrimitiveConstantIfPossible(cexp); if (fieldNode.isFinal() && ClassHelper.isStaticConstantInitializerType(cexp.getType()) && cexp.getType().equals(fieldNode.getType())) { return; // GROOVY-5150: primitive type constants will be initialized directly } staticList.add(0, statement); } else { staticList.add(statement); } fieldNode.setInitialValueExpression(null); // to avoid double initialization in case of several constructors /* * If it is a statement for an explicitly declared static field inside an enum, store its * reference. For enums, they need to be handled differently as such init statements should * come after the enum values have been initialized inside block. GROOVY-3161. */ if (isEnumClassNode && explicitStaticPropsInEnum.contains(fieldNode.getName())) { initStmtsAfterEnumValuesInit.add(statement); } } else { list.add(statement); } } } /** * Capitalizes the start of the given bean property name */ public static String capitalize(String name) { return MetaClassHelper.capitalize(name); } protected Statement createGetterBlock(PropertyNode propertyNode, final FieldNode field) { return new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { if (field.isStatic()) { mv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(classNode), field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } else { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, BytecodeHelper.getClassInternalName(classNode), field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } BytecodeHelper.doReturn(mv, field.getType()); } }); } protected Statement createSetterBlock(PropertyNode propertyNode, final FieldNode field) { return new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { if (field.isStatic()) { BytecodeHelper.load(mv, field.getType(), 0); mv.visitFieldInsn(PUTSTATIC, BytecodeHelper.getClassInternalName(classNode), field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } else { mv.visitVarInsn(ALOAD, 0); BytecodeHelper.load(mv, field.getType(), 1); mv.visitFieldInsn(PUTFIELD, BytecodeHelper.getClassInternalName(classNode), field.getName(), BytecodeHelper.getTypeDescription(field.getType())); } mv.visitInsn(RETURN); } }); } public void visitGenericType(GenericsType genericsType) { } public static long getTimestamp(Class clazz) { if (clazz.getClassLoader() instanceof GroovyClassLoader.InnerLoader) { GroovyClassLoader.InnerLoader innerLoader = (GroovyClassLoader.InnerLoader) clazz.getClassLoader(); return innerLoader.getTimeStamp(); } final Field[] fields = clazz.getFields(); for (int i = 0; i != fields.length; ++i) { if (Modifier.isStatic(fields[i].getModifiers())) { final String name = fields[i].getName(); if (name.startsWith(__TIMESTAMP__)) { try { return Long.decode(name.substring(__TIMESTAMP__.length())).longValue(); } catch (NumberFormatException e) { return Long.MAX_VALUE; } } } } return Long.MAX_VALUE; } protected void addCovariantMethods(ClassNode classNode) { Map methodsToAdd = new HashMap(); Map genericsSpec = new HashMap(); // unimplemented abstract methods from interfaces Map abstractMethods = new HashMap(); Map allInterfaceMethods = new HashMap(); ClassNode[] interfaces = classNode.getInterfaces(); for (ClassNode iface : interfaces) { Map ifaceMethodsMap = iface.getDeclaredMethodsMap(); abstractMethods.putAll(ifaceMethodsMap); allInterfaceMethods.putAll(ifaceMethodsMap); } collectSuperInterfaceMethods(classNode, allInterfaceMethods); List declaredMethods = new ArrayList(classNode.getMethods()); // remove all static, private and package private methods for (Iterator methodsIterator = declaredMethods.iterator(); methodsIterator.hasNext();) { MethodNode m = (MethodNode) methodsIterator.next(); abstractMethods.remove(m.getTypeDescriptor()); if (m.isStatic() || !(m.isPublic() || m.isProtected())) { methodsIterator.remove(); } MethodNode intfMethod = allInterfaceMethods.get(m.getTypeDescriptor()); if (intfMethod != null && ((m.getModifiers() & ACC_SYNTHETIC) == 0) && !m.isPublic() && !m.isStaticConstructor()) { throw new RuntimeParserException("The method " + m.getName() + " should be public as it implements the corresponding method from interface " + intfMethod.getDeclaringClass(), m); } } addCovariantMethods(classNode, declaredMethods, abstractMethods, methodsToAdd, genericsSpec); Map declaredMethodsMap = new HashMap(); if (methodsToAdd.size() > 0) { for (MethodNode mn : declaredMethods) { declaredMethodsMap.put(mn.getTypeDescriptor(), mn); } } for (Object o : methodsToAdd.entrySet()) { Map.Entry entry = (Map.Entry) o; MethodNode method = (MethodNode) entry.getValue(); // we skip bridge methods implemented in current class already MethodNode mn = declaredMethodsMap.get(entry.getKey()); if (mn != null && mn.getDeclaringClass().equals(classNode)) continue; addPropertyMethod(method); } } private void collectSuperInterfaceMethods(ClassNode cn, Map allInterfaceMethods) { List cnInterfaces = Arrays.asList(cn.getInterfaces()); ClassNode sn = cn.getSuperClass(); while (sn != null && !sn.equals(ClassHelper.OBJECT_TYPE)) { ClassNode[] interfaces = sn.getInterfaces(); for (ClassNode iface : interfaces) { if (!cnInterfaces.contains(iface)) { Map ifaceMethodsMap = iface.getDeclaredMethodsMap(); allInterfaceMethods.putAll(ifaceMethodsMap); } } sn = sn.getSuperClass(); } } private void addCovariantMethods(ClassNode classNode, List declaredMethods, Map abstractMethods, Map methodsToAdd, Map oldGenericsSpec) { ClassNode sn = classNode.getUnresolvedSuperClass(false); if (sn != null) { Map genericsSpec = createGenericsSpec(sn, oldGenericsSpec); List classMethods = sn.getMethods(); // original class causing bridge methods for methods in super class for (Object declaredMethod : declaredMethods) { MethodNode method = (MethodNode) declaredMethod; if (method.isStatic()) continue; storeMissingCovariantMethods(classMethods, method, methodsToAdd, genericsSpec); } // super class causing bridge methods for abstract methods in original class if (!abstractMethods.isEmpty()) { for (Object classMethod : classMethods) { MethodNode method = (MethodNode) classMethod; if (method.isStatic()) continue; storeMissingCovariantMethods(abstractMethods.values(), method, methodsToAdd, Collections.EMPTY_MAP); } } addCovariantMethods(sn.redirect(), declaredMethods, abstractMethods, methodsToAdd, genericsSpec); } ClassNode[] interfaces = classNode.getInterfaces(); for (ClassNode anInterface : interfaces) { List interfacesMethods = anInterface.getMethods(); Map genericsSpec = createGenericsSpec(anInterface, oldGenericsSpec); for (Object declaredMethod : declaredMethods) { MethodNode method = (MethodNode) declaredMethod; if (method.isStatic()) continue; storeMissingCovariantMethods(interfacesMethods, method, methodsToAdd, genericsSpec); } addCovariantMethods(anInterface, declaredMethods, abstractMethods, methodsToAdd, genericsSpec); } } private MethodNode getCovariantImplementation(final MethodNode oldMethod, final MethodNode overridingMethod, Map genericsSpec) { // method name if (!oldMethod.getName().equals(overridingMethod.getName())) return null; if ((overridingMethod.getModifiers() & ACC_BRIDGE) != 0) return null; // parameters boolean normalEqualParameters = equalParametersNormal(overridingMethod, oldMethod); boolean genericEqualParameters = equalParametersWithGenerics(overridingMethod, oldMethod, genericsSpec); if (!normalEqualParameters && !genericEqualParameters) return null; // return type ClassNode mr = overridingMethod.getReturnType(); ClassNode omr = oldMethod.getReturnType(); boolean equalReturnType = mr.equals(omr); if (equalReturnType && normalEqualParameters) return null; // if we reach this point we have at least one parameter or return type, that // is different in its specified form. That means we have to create a bridge method! ClassNode testmr = correctToGenericsSpec(genericsSpec, omr); if (!isAssignable(mr, testmr)) { throw new RuntimeParserException( "The return type of " + overridingMethod.getTypeDescriptor() + " in " + overridingMethod.getDeclaringClass().getName() + " is incompatible with " + oldMethod.getTypeDescriptor() + " in " + oldMethod.getDeclaringClass().getName(), overridingMethod); } if ((oldMethod.getModifiers() & ACC_FINAL) != 0) { throw new RuntimeParserException( "Cannot override final method " + oldMethod.getTypeDescriptor() + " in " + oldMethod.getDeclaringClass().getName(), overridingMethod); } if (oldMethod.isStatic() != overridingMethod.isStatic()) { throw new RuntimeParserException( "Cannot override method " + oldMethod.getTypeDescriptor() + " in " + oldMethod.getDeclaringClass().getName() + " with disparate static modifier", overridingMethod); } if (!equalReturnType) { boolean oldM = ClassHelper.isPrimitiveType(oldMethod.getReturnType()); boolean newM = ClassHelper.isPrimitiveType(overridingMethod.getReturnType()); if (oldM || newM) { String message=""; if (oldM && newM) { message = " with old and new method having different primitive return types"; } else if (newM) { message = " with new method having a primitive return type and old method not"; } else if (oldM) { message = " with old method having a primitive return type and new method not"; } throw new RuntimeParserException( "Cannot override method " + oldMethod.getTypeDescriptor() + " in " + oldMethod.getDeclaringClass().getName() + message, overridingMethod); } } MethodNode newMethod = new MethodNode( oldMethod.getName(), overridingMethod.getModifiers() | ACC_SYNTHETIC | ACC_BRIDGE, oldMethod.getReturnType().getPlainNodeReference(), cleanParameters(oldMethod.getParameters()), oldMethod.getExceptions(), null ); List instructions = new ArrayList(1); instructions.add( new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(ALOAD,0); Parameter[] para = oldMethod.getParameters(); Parameter[] goal = overridingMethod.getParameters(); int doubleSlotOffset = 0; for (int i = 0; i < para.length; i++) { ClassNode type = para[i].getType(); BytecodeHelper.load(mv, type, i+1+doubleSlotOffset); if (type.redirect()==ClassHelper.double_TYPE || type.redirect()==ClassHelper.long_TYPE) { doubleSlotOffset++; } if (!type.equals(goal[i].getType())) { BytecodeHelper.doCast(mv,goal[i].getType()); } } mv.visitMethodInsn( INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(classNode), overridingMethod.getName(), BytecodeHelper.getMethodDescriptor(overridingMethod.getReturnType(), overridingMethod.getParameters())); BytecodeHelper.doReturn(mv, oldMethod.getReturnType()); } } ); newMethod.setCode(new BytecodeSequence(instructions)); return newMethod; } private boolean isAssignable(ClassNode node, ClassNode testNode) { if (testNode.isInterface()) { if (node.isInterface()) { if (node.isDerivedFrom(testNode)) return true; } else { if (node.implementsInterface(testNode)) return true; } } else { if (node.isDerivedFrom(testNode)) return true; } return false; } private Parameter[] cleanParameters(Parameter[] parameters) { Parameter[] params = new Parameter[parameters.length]; for (int i = 0; i < params.length; i++) { params[i] = new Parameter(parameters[i].getType().getPlainNodeReference(), parameters[i].getName()); } return params; } private void storeMissingCovariantMethods(Collection methods, MethodNode method, Map methodsToAdd, Map genericsSpec) { for (Object method1 : methods) { MethodNode toOverride = (MethodNode) method1; MethodNode bridgeMethod = getCovariantImplementation(toOverride, method, genericsSpec); if (bridgeMethod == null) continue; methodsToAdd.put(bridgeMethod.getTypeDescriptor(), bridgeMethod); return; } } private ClassNode correctToGenericsSpec(Map genericsSpec, GenericsType type) { ClassNode ret = null; if (type.isPlaceholder()) { String name = type.getName(); ret = (ClassNode) genericsSpec.get(name); } if (ret == null) ret = type.getType(); return ret; } private ClassNode correctToGenericsSpec(Map genericsSpec, ClassNode type) { if (type.isGenericsPlaceHolder()) { String name = type.getGenericsTypes()[0].getName(); type = (ClassNode) genericsSpec.get(name); } if (type == null) type = ClassHelper.OBJECT_TYPE; return type; } private boolean equalParametersNormal(MethodNode m1, MethodNode m2) { Parameter[] p1 = m1.getParameters(); Parameter[] p2 = m2.getParameters(); if (p1.length != p2.length) return false; for (int i = 0; i < p2.length; i++) { ClassNode type = p2[i].getType(); ClassNode parameterType = p1[i].getType(); if (!parameterType.equals(type)) return false; } return true; } private boolean equalParametersWithGenerics(MethodNode m1, MethodNode m2, Map genericsSpec) { Parameter[] p1 = m1.getParameters(); Parameter[] p2 = m2.getParameters(); if (p1.length != p2.length) return false; for (int i = 0; i < p2.length; i++) { ClassNode type = p2[i].getType(); ClassNode genericsType = correctToGenericsSpec(genericsSpec, type); ClassNode parameterType = p1[i].getType(); if (!parameterType.equals(genericsType)) return false; } return true; } private Map createGenericsSpec(ClassNode current, Map oldSpec) { Map ret = new HashMap(oldSpec); // ret contains the type specs, what we now need is the type spec for the // current class. To get that we first apply the type parameters to the // current class and then use the type names of the current class to reset // the map. Example: // class A{} // class B extends A {} // first we have: T->Number // we apply it to A -> A // resulting in: V->Number,W->Long,X->String GenericsType[] sgts = current.getGenericsTypes(); if (sgts != null) { ClassNode[] spec = new ClassNode[sgts.length]; for (int i = 0; i < spec.length; i++) { spec[i] = correctToGenericsSpec(ret, sgts[i]); } GenericsType[] newGts = current.redirect().getGenericsTypes(); if (newGts == null) return ret; ret.clear(); for (int i = 0; i < spec.length; i++) { ret.put(newGts[i].getName(), spec[i]); } } return ret; } private boolean moveOptimizedConstantsInitialization(final ClassNode node) { if (node.isInterface()) return false; final int mods = Opcodes.ACC_STATIC|Opcodes.ACC_SYNTHETIC| Opcodes.ACC_PUBLIC; String name = SWAP_INIT; BlockStatement methodCode = new BlockStatement(); node.addSyntheticMethod( name, mods, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, methodCode); methodCode.addStatement(new BytecodeSequence(new BytecodeInstruction() { @Override public void visit(MethodVisitor mv) { final String classInternalName = BytecodeHelper.getClassInternalName(node); mv.visitInsn(ACONST_NULL); mv.visitFieldInsn(PUTSTATIC, classInternalName, "$callSiteArray", "Ljava/lang/ref/SoftReference;"); } })); for (FieldNode fn : node.getFields()) { if (!fn.isStatic() || !fn.isSynthetic() || !fn.getName().startsWith("$const$")) continue; if (fn.getInitialExpression()==null) continue; final FieldExpression fe = new FieldExpression(fn); if (fn.getType().equals(ClassHelper.REFERENCE_TYPE)) fe.setUseReferenceDirectly(true); ConstantExpression init = (ConstantExpression) fn.getInitialExpression(); ExpressionStatement statement = new ExpressionStatement( new BinaryExpression( fe, Token.newSymbol(Types.EQUAL, fn.getLineNumber(), fn.getColumnNumber()), init)); fn.setInitialValueExpression(null); init.setConstantName(null); methodCode.addStatement(statement); } return true; } /** * When constant expressions are created, the value is always wrapped to a non primitive type. * Some constant expressions are optimized to return primitive types, but not all primitives are * handled. This method guarantees to return a similar constant expression but with a primitive type * instead of a boxed type. * * Additionaly, single char strings are converted to 'char' types. * * @param constantExpression a constant expression * @return the same instance of constant expression if the type is already primitive, or a primitive * constant if possible. */ public static ConstantExpression transformToPrimitiveConstantIfPossible(ConstantExpression constantExpression) { Object value = constantExpression.getValue(); if (value ==null) return constantExpression; ConstantExpression result; ClassNode type = constantExpression.getType(); if (ClassHelper.isPrimitiveType(type)) return constantExpression; if (value instanceof String && ((String)value).length()==1) { result = new ConstantExpression(((String)value).charAt(0)); result.setType(ClassHelper.char_TYPE); } else { type = ClassHelper.getUnwrapper(type); result = new ConstantExpression(value, true); result.setType(type); } return result; } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/ExtendedVerifier.java0000644001501200150120000001664311707612044025725 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen; import java.lang.annotation.Target; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.ErrorCollector; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.objectweb.asm.Opcodes; /** * A specialized Groovy AST visitor meant to perform additional verifications upon the * current AST. Currently it does checks on annotated nodes and annotations itself. *

      * Current limitations: * - annotations on local variables are not supported * * @author Alex Popescu */ public class ExtendedVerifier implements GroovyClassVisitor { public static final String JVM_ERROR_MESSAGE = "Please make sure you are running on a JVM >= 1.5"; private SourceUnit source; private ClassNode currentClass; public ExtendedVerifier(SourceUnit sourceUnit) { this.source = sourceUnit; } public void visitClass(ClassNode node) { this.currentClass = node; if (node.isAnnotationDefinition()) { visitAnnotations(node, AnnotationNode.ANNOTATION_TARGET); } else { visitAnnotations(node, AnnotationNode.TYPE_TARGET); } PackageNode packageNode = node.getPackage(); if (packageNode != null) { visitAnnotations(packageNode, AnnotationNode.PACKAGE_TARGET); } node.visitContents(this); } public void visitField(FieldNode node) { visitAnnotations(node, AnnotationNode.FIELD_TARGET); } public void visitConstructor(ConstructorNode node) { visitConstructorOrMethod(node, AnnotationNode.CONSTRUCTOR_TARGET); } public void visitMethod(MethodNode node) { visitConstructorOrMethod(node, AnnotationNode.METHOD_TARGET); } private void visitConstructorOrMethod(MethodNode node, int methodTarget) { visitAnnotations(node, methodTarget); for (int i = 0; i < node.getParameters().length; i++) { Parameter parameter = node.getParameters()[i]; visitAnnotations(parameter, AnnotationNode.PARAMETER_TARGET); } if (this.currentClass.isAnnotationDefinition() && !node.isStaticConstructor()) { ErrorCollector errorCollector = new ErrorCollector(this.source.getConfiguration()); AnnotationVisitor visitor = new AnnotationVisitor(this.source, errorCollector); visitor.setReportClass(currentClass); visitor.checkReturnType(node.getReturnType(), node); if (node.getParameters().length > 0) { addError("Annotation members may not have parameters.", node.getParameters()[0]); } if (node.getExceptions().length > 0) { addError("Annotation members may not have a throws clause.", node.getExceptions()[0]); } ReturnStatement code = (ReturnStatement) node.getCode(); if (code != null) { visitor.visitExpression(node.getName(), code.getExpression(), node.getReturnType()); visitor.checkCircularReference(currentClass, node.getReturnType(), code.getExpression()); } this.source.getErrorCollector().addCollectorContents(errorCollector); } } public void visitProperty(PropertyNode node) { } protected void visitAnnotations(AnnotatedNode node, int target) { if (node.getAnnotations().isEmpty()) { return; } this.currentClass.setAnnotated(true); if (!isAnnotationCompatible()) { addError("Annotations are not supported in the current runtime. " + JVM_ERROR_MESSAGE, node); return; } for (AnnotationNode unvisited : node.getAnnotations()) { AnnotationNode visited = visitAnnotation(unvisited); boolean isTargetAnnotation = visited.getClassNode().isResolved() && visited.getClassNode().getName().equals("java.lang.annotation.Target"); // Check if the annotation target is correct, unless it's the target annotating an annotation definition // defining on which target elements the annotation applies if (!isTargetAnnotation && !visited.isTargetAllowed(target)) { addError("Annotation @" + visited.getClassNode().getName() + " is not allowed on element " + AnnotationNode.targetToName(target), visited); } visitDeprecation(node, visited); } } private void visitDeprecation(AnnotatedNode node, AnnotationNode visited) { if (visited.getClassNode().isResolved() && visited.getClassNode().getName().equals("java.lang.Deprecated")) { if (node instanceof MethodNode) { MethodNode mn = (MethodNode) node; mn.setModifiers(mn.getModifiers() | Opcodes.ACC_DEPRECATED); } else if (node instanceof FieldNode) { FieldNode fn = (FieldNode) node; fn.setModifiers(fn.getModifiers() | Opcodes.ACC_DEPRECATED); } else if (node instanceof ClassNode) { ClassNode cn = (ClassNode) node; cn.setModifiers(cn.getModifiers() | Opcodes.ACC_DEPRECATED); } } } /** * Resolve metadata and details of the annotation. * * @param unvisited the node to visit * @return the visited node */ private AnnotationNode visitAnnotation(AnnotationNode unvisited) { ErrorCollector errorCollector = new ErrorCollector(this.source.getConfiguration()); AnnotationVisitor visitor = new AnnotationVisitor(this.source, errorCollector); AnnotationNode visited = visitor.visit(unvisited); this.source.getErrorCollector().addCollectorContents(errorCollector); return visited; } /** * Check if the current runtime allows Annotation usage. * * @return true if running on a 1.5+ runtime */ protected boolean isAnnotationCompatible() { return CompilerConfiguration.POST_JDK5.equals(this.source.getConfiguration().getTargetBytecode()); } protected void addError(String msg, ASTNode expr) { this.source.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage( new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber()), this.source) ); } // TODO use it or lose it public void visitGenericType(GenericsType genericsType) { } } groovy-1.8.6/src/main/org/codehaus/groovy/classgen/genDgmMath.groovy0000644001501200150120000000502411627206700025076 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen def types = ["Integer", "Long", "Float", "Double"] def getMath (a,b) { if (a == "Double" || b == "Double" || a == "Float" || b == "Float") return "FloatingPointMath" if (a == "Long" || b == "Long") return "LongMath" "IntegerMath" } println """ public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { NumberMath m = NumberMath.getMath((Number)receiver, (Number)args[0]); """ types.each { a -> print """ if (receiver instanceof $a) {""" types.each { b -> print """ if (args[0] instanceof $b) return new NumberNumberCallSite (site, metaClass, metaMethod, params, (Number)receiver, (Number)args[0]){ public final Object invoke(Object receiver, Object[] args) { return ${getMath(a,b)}.INSTANCE.addImpl(($a)receiver,($b)args[0]); } public final Object invokeBinop(Object receiver, Object arg) { return ${getMath(a,b)}.INSTANCE.addImpl(($a)receiver,($b)arg); } }; """ } println "}" } println """ return new NumberNumberCallSite (site, metaClass, metaMethod, params, (Number)receiver, (Number)args[0]){ public final Object invoke(Object receiver, Object[] args) { return math.addImpl((Number)receiver,(Number)args[0]); } public final Object invokeBinop(Object receiver, Object arg) { return math.addImpl((Number)receiver,(Number)arg); } } """ for (i in 2..256) { print "public Object invoke$i (Object receiver, " for (j in 1..(i-1)) { print "Object a$j, " } println "Object a$i) {" print " return invoke (receiver, new Object[] {" for (j in 1..(i-1)) { print "a$j, " } println "a$i} );" println "}" } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/0000755001501200150120000000000011713765676021677 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v4/0000755001501200150120000000000011707612046022211 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v4/package.html0000644001501200150120000000143111627206700024466 0ustar miguelmiguel

      Java 1.4 specific classes.

      groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v4/Java4.java0000644001501200150120000001003411707612046024017 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v4; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.vmplugin.VMPlugin; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Constructor; /** * java 4 based functions * @author Jochen Theodorou * */ public class Java4 implements VMPlugin { private static Class[] EMPTY_CLASS_ARRAY = new Class[0]; public void setAdditionalClassInformation(ClassNode c) { return; } public Class[] getPluginDefaultGroovyMethods() { return EMPTY_CLASS_ARRAY; } public Class[] getPluginStaticGroovyMethods() { return EMPTY_CLASS_ARRAY; } public void configureAnnotation(AnnotationNode an) { // do nothing } public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) { Class clazz = classNode.getTypeClass(); Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { classNode.addField(fields[i].getName(), fields[i].getModifiers(), classNode, null); } Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ClassHelper.make(m.getReturnType()), createParameters(m.getParameterTypes()), ClassHelper.make(m.getExceptionTypes()), null); classNode.addMethod(mn); } Constructor[] constructors = clazz.getDeclaredConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor ctor = constructors[i]; classNode.addConstructor(ctor.getModifiers(), createParameters(ctor.getParameterTypes()), ClassHelper.make(ctor.getExceptionTypes()), null); } Class sc = clazz.getSuperclass(); if (sc != null) classNode.setUnresolvedSuperClass(getPrimaryClassNode(compileUnit,sc)); buildInterfaceTypes(compileUnit,classNode,clazz); } private ClassNode getPrimaryClassNode(CompileUnit compileUnit,Class clazz) { // there might be a new super class from the compile unit, // we want to use this instead of simply referencing the old // class ClassNode result = null; if (compileUnit!=null) { result = compileUnit.getClass(clazz.getName()); } if (result==null) result = ClassHelper.make(clazz); return result; } private void buildInterfaceTypes(CompileUnit compileUnit, ClassNode classNode, Class c) { Class[] interfaces = c.getInterfaces(); ClassNode[] ret = new ClassNode[interfaces.length]; for (int i=0;i 0) { parameters = new Parameter[size]; for (int i = 0; i < size; i++) { parameters[i] = createParameter(types[i], i); } } return parameters; } private Parameter createParameter(Class parameterType, int idx) { return new Parameter(ClassHelper.make(parameterType), "param" + idx); } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/package.html0000644001501200150120000000143411627206700024140 0ustar miguelmiguel

      JVM version specific classes.

      groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/VMPlugin.java0000644001501200150120000000220311707612046024221 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin; import org.codehaus.groovy.ast.*; /** * Interface to access VM version based actions. * This interface is for internal use only! * * @author Jochen Theodorou */ public interface VMPlugin { void setAdditionalClassInformation(ClassNode c); Class[] getPluginDefaultGroovyMethods(); Class[] getPluginStaticGroovyMethods(); void configureAnnotation(AnnotationNode an); void configureClassNode(CompileUnit compileUnit, ClassNode classNode); } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/0000755001501200150120000000000011707612046022212 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/package.html0000644001501200150120000000142711627206700024474 0ustar miguelmiguel

      Java 5 specific classes.

      groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/TestNgUtils.java0000644001501200150120000000705611627206700025307 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v5; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * Java 5 code for working with TestNG tests. * * @author Paul King * */ public class TestNgUtils { /** * Utility method to check via reflection if the parsed class appears to be a TestNG test. * * @param scriptClass the class we want to check * @param loader the GroovyClassLoader to use to find classes * @return true if the class appears to be a test */ static Boolean realIsTestNgTest(Class scriptClass, GroovyClassLoader loader) { // check if there are appropriate class or method annotations // that suggest we have a TestNG test boolean isTest = false; try { try { Class testAnnotationClass = loader.loadClass("org.testng.annotations.Test"); Annotation annotation = scriptClass.getAnnotation(testAnnotationClass); if (annotation != null) { isTest = true; } else { Method[] methods = scriptClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; annotation = method.getAnnotation(testAnnotationClass); if (annotation != null) { isTest = true; break; } } } } catch (ClassNotFoundException e) { // fall through } } catch (Throwable e) { // fall through } return isTest ? Boolean.TRUE : Boolean.FALSE; } /** * Utility method to run a TestNG test. * * @param scriptClass the class we want to run as a test * @return the result of running the test */ static Object realRunTestNgTest(Class scriptClass, GroovyClassLoader loader) { // invoke through reflection to eliminate mandatory TestNG jar dependency try { Class testNGClass = loader.loadClass("org.testng.TestNG"); Object testng = InvokerHelper.invokeConstructorOf(testNGClass, new Object[]{}); InvokerHelper.invokeMethod(testng, "setTestClasses", new Object[]{scriptClass}); Class listenerClass = loader.loadClass("org.testng.TestListenerAdapter"); Object listener = InvokerHelper.invokeConstructorOf(listenerClass, new Object[]{}); InvokerHelper.invokeMethod(testng, "addListener", new Object[]{listener}); Object result = InvokerHelper.invokeMethod(testng, "run", new Object[]{}); return result; } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Error running TestNG test.", e); } } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/PluginDefaultGroovyMethods.java0000644001501200150120000001247511627206700030360 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v5; import groovy.lang.IntRange; import groovy.lang.EmptyRange; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport; import java.util.Arrays; import java.lang.reflect.Method; /** * This class defines new Java 5 specific groovy methods which extend the normal * JDK classes inside the Groovy environment. Static methods are used with the * first parameter the destination class. */ public class PluginDefaultGroovyMethods extends DefaultGroovyMethodsSupport { private static final Object[] NO_ARGS = new Object[0]; /** * This method is called by the ++ operator for enums. It will invoke * Groovy's default next behaviour for enums do not have their own * next method (Only works with JDK1.5 or later). * * @param self an Enum * @return the next defined enum from the enum class */ public static Object next(Enum self) { final Method[] methods = self.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals("next") && method.getParameterTypes().length == 0) { return InvokerHelper.invokeMethod(self, "next", NO_ARGS); } } Object[] values = (Object[]) InvokerHelper.invokeStaticMethod(self.getClass(), "values", NO_ARGS); int index = Arrays.asList(values).indexOf(self); return values[index < values.length - 1 ? index + 1 : 0]; } /** * This method is called by the -- operator for enums. It will invoke * Groovy's default previous behaviour for enums that do not have * their own previous method (Only works with JDK1.5 or later). * * @param self an Enum * @return the previous defined enum from the enum class */ public static Object previous(Enum self) { final Method[] methods = self.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals("previous") && method.getParameterTypes().length == 0) { return InvokerHelper.invokeMethod(self, "previous", NO_ARGS); } } Object[] values = (Object[]) InvokerHelper.invokeStaticMethod(self.getClass(), "values", NO_ARGS); int index = Arrays.asList(values).indexOf(self); return values[index > 0 ? index - 1 : values.length - 1]; } /** * Standard Groovy size() method for StringBuilders * (Only works with JDK1.5 or later). * * @param builder a StringBuilder * @return the length of the StringBuilder */ public static int size(StringBuilder builder) { return builder.length(); } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a StringBuilder (Only works with JDK1.5 or later). * * @param self a StringBuilder * @param value a value to append * @return the StringBuilder on which this operation was invoked */ public static StringBuilder leftShift(StringBuilder self, Object value) { if (value instanceof CharSequence) return self.append((CharSequence)value); else return self.append(value); } /** * Support the range subscript operator for StringBuilder (Only works with JDK1.5 or later). * Index values are treated as characters within the builder. * * @param self a StringBuilder * @param range a Range * @param value the object that's toString() will be inserted */ public static void putAt(StringBuilder self, IntRange range, Object value) { RangeInfo info = subListBorders(self.length(), range); self.replace(info.from, info.to, value.toString()); } /** * Support the range subscript operator for StringBuilder (Only works with JDK1.5 or later). * * @param self a StringBuilder * @param range a Range * @param value the object that's toString() will be inserted */ public static void putAt(StringBuilder self, EmptyRange range, Object value) { RangeInfo info = subListBorders(self.length(), range); self.replace(info.from, info.to, value.toString()); } /** * Appends a String to this StringBuilder (Only works with JDK1.5 or later). * * @param self a StringBuilder * @param value a String * @return a String */ public static String plus(StringBuilder self, String value) { return self + value; } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/JUnit4Utils.java0000644001501200150120000000766311627206700025224 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v5; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import java.util.List; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * Java 5 code for working with JUnit 4 tests. * * @author Paul King * */ public class JUnit4Utils { /** * Utility method to check via reflection if the parsed class appears to be a JUnit4 test. * * @param scriptClass the class we want to check * @param loader the GroovyClassLoader to use to find classes * @return true if the class appears to be a test */ static Boolean realIsJUnit4Test(Class scriptClass, GroovyClassLoader loader) { // check if there are appropriate class or method annotations // that suggest we have a JUnit 4 test boolean isTest = false; try { try { Class runWithAnnotationClass = loader.loadClass("org.junit.runner.RunWith"); Annotation annotation = scriptClass.getAnnotation(runWithAnnotationClass); if (annotation != null) { isTest = true; } else { Class testAnnotationClass = loader.loadClass("org.junit.Test"); Method[] methods = scriptClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; annotation = method.getAnnotation(testAnnotationClass); if (annotation != null) { isTest = true; break; } } } } catch (ClassNotFoundException e) { // fall through } } catch (Throwable e) { // fall through } return isTest ? Boolean.TRUE : Boolean.FALSE; } /** * Utility method to run a JUnit4 test. * * @param scriptClass the class we want to run as a test * @return the result of running the test */ static Object realRunJUnit4Test(Class scriptClass, GroovyClassLoader loader) { // invoke through reflection to eliminate mandatory JUnit 4 jar dependency try { Class junitCoreClass = loader.loadClass("org.junit.runner.JUnitCore"); Object result = InvokerHelper.invokeStaticMethod(junitCoreClass, "runClasses", new Object[]{scriptClass}); System.out.print("JUnit 4 Runner, Tests: " + InvokerHelper.getProperty(result, "runCount")); System.out.print(", Failures: " + InvokerHelper.getProperty(result, "failureCount")); System.out.println(", Time: " + InvokerHelper.getProperty(result, "runTime")); List failures = (List) InvokerHelper.getProperty(result, "failures"); for (int i = 0; i < failures.size(); i++) { Object f = failures.get(i); System.out.println("Test Failure: " + InvokerHelper.getProperty(f, "description")); System.out.println(InvokerHelper.getProperty(f, "trace")); } return result; } catch (ClassNotFoundException e) { throw new GroovyRuntimeException("Error running JUnit 4 test.", e); } } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v5/Java5.java0000644001501200150120000004161611707612046024033 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v5; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.vmplugin.VMPlugin; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.List; /** * java 5 based functions * * @author Jochen Theodorou */ public class Java5 implements VMPlugin { private static Class[] EMPTY_CLASS_ARRAY = new Class[0]; private static final Class[] PLUGIN_DGM = {PluginDefaultGroovyMethods.class}; public void setAdditionalClassInformation(ClassNode cn) { setGenericsTypes(cn); } private void setGenericsTypes(ClassNode cn) { TypeVariable[] tvs = cn.getTypeClass().getTypeParameters(); GenericsType[] gts = configureTypeVariable(tvs); cn.setGenericsTypes(gts); } private GenericsType[] configureTypeVariable(TypeVariable[] tvs) { if (tvs.length == 0) return null; GenericsType[] gts = new GenericsType[tvs.length]; for (int i = 0; i < tvs.length; i++) { gts[i] = configureTypeVariableDefinition(tvs[i]); } return gts; } private GenericsType configureTypeVariableDefinition(TypeVariable tv) { ClassNode base = configureTypeVariableReference(tv); ClassNode redirect = base.redirect(); base.setRedirect(null); Type[] tBounds = tv.getBounds(); GenericsType gt; if (tBounds.length == 0) { gt = new GenericsType(base); } else { ClassNode[] cBounds = configureTypes(tBounds); gt = new GenericsType(base, cBounds, null); gt.setName(base.getName()); gt.setPlaceholder(true); } base.setRedirect(redirect); return gt; } private ClassNode[] configureTypes(Type[] types) { if (types.length == 0) return null; ClassNode[] nodes = new ClassNode[types.length]; for (int i = 0; i < types.length; i++) { nodes[i] = configureType(types[i]); } return nodes; } private ClassNode configureType(Type type) { if (type instanceof WildcardType) { return configureWildcardType((WildcardType) type); } else if (type instanceof ParameterizedType) { return configureParameterizedType((ParameterizedType) type); } else if (type instanceof GenericArrayType) { return configureGenericArray((GenericArrayType) type); } else if (type instanceof TypeVariable) { return configureTypeVariableReference((TypeVariable) type); } else if (type instanceof Class) { return configureClass((Class) type); } else if (type==null) { throw new GroovyBugError("Type is null. Most probably you let a transform reuse existing ClassNodes with generics information, that is now used in a wrong context."); } else { throw new GroovyBugError("unknown type: " + type + " := " + type.getClass()); } } private ClassNode configureClass(Class c) { if (c.isPrimitive()) { return ClassHelper.make(c); } else { return ClassHelper.makeWithoutCaching(c, false); } } private ClassNode configureGenericArray(GenericArrayType genericArrayType) { Type component = genericArrayType.getGenericComponentType(); ClassNode node = configureType(component); return node.makeArray(); } private ClassNode configureWildcardType(WildcardType wildcardType) { ClassNode base = ClassHelper.makeWithoutCaching("?"); base.setRedirect(ClassHelper.OBJECT_TYPE); //TODO: more than one lower bound for wildcards? ClassNode[] lowers = configureTypes(wildcardType.getLowerBounds()); ClassNode lower = null; // TODO: is it safe to remove this? What was the original intention? if (lower != null) lower = lowers[0]; ClassNode[] upper = configureTypes(wildcardType.getUpperBounds()); GenericsType t = new GenericsType(base, upper, lower); t.setWildcard(true); ClassNode ref = ClassHelper.makeWithoutCaching(Object.class, false); ref.setGenericsTypes(new GenericsType[]{t}); return ref; } private ClassNode configureParameterizedType(ParameterizedType parameterizedType) { ClassNode base = configureType(parameterizedType.getRawType()); GenericsType[] gts = configureTypeArguments(parameterizedType.getActualTypeArguments()); base.setGenericsTypes(gts); return base; } private ClassNode configureTypeVariableReference(TypeVariable tv) { ClassNode cn = ClassHelper.makeWithoutCaching(tv.getName()); cn.setGenericsPlaceHolder(true); ClassNode cn2 = ClassHelper.makeWithoutCaching(tv.getName()); cn2.setGenericsPlaceHolder(true); GenericsType[] gts = new GenericsType[]{new GenericsType(cn2)}; cn.setGenericsTypes(gts); cn.setRedirect(ClassHelper.OBJECT_TYPE); return cn; } private GenericsType[] configureTypeArguments(Type[] ta) { if (ta.length == 0) return null; GenericsType[] gts = new GenericsType[ta.length]; for (int i = 0; i < ta.length; i++) { ClassNode t = configureType(ta[i]); if (ta[i] instanceof WildcardType) { GenericsType[] gen = t.getGenericsTypes(); gts[i] = gen[0]; } else { gts[i] = new GenericsType(t); } } return gts; } public Class[] getPluginDefaultGroovyMethods() { return PLUGIN_DGM; } public Class[] getPluginStaticGroovyMethods() { return EMPTY_CLASS_ARRAY; } private void setAnnotationMetaData(Annotation[] annotations, AnnotatedNode an) { for (Annotation annotation : annotations) { AnnotationNode node = new AnnotationNode(ClassHelper.make(annotation.annotationType())); configureAnnotation(node, annotation); an.addAnnotation(node); } } private void configureAnnotationFromDefinition(AnnotationNode definition, AnnotationNode root) { ClassNode type = definition.getClassNode(); if (!type.isResolved()) return; Class clazz = type.getTypeClass(); if (clazz == Retention.class) { Expression exp = definition.getMember("value"); if (!(exp instanceof PropertyExpression)) return; PropertyExpression pe = (PropertyExpression) exp; String name = pe.getPropertyAsString(); RetentionPolicy policy = RetentionPolicy.valueOf(name); setRetentionPolicy(policy, root); } else if (clazz == Target.class) { Expression exp = definition.getMember("value"); if (!(exp instanceof ListExpression)) return; ListExpression le = (ListExpression) exp; int bitmap = 0; for (Expression e : le.getExpressions()) { PropertyExpression element = (PropertyExpression) e; String name = element.getPropertyAsString(); ElementType value = ElementType.valueOf(name); bitmap |= getElementCode(value); } root.setAllowedTargets(bitmap); } } public void configureAnnotation(AnnotationNode node) { ClassNode type = node.getClassNode(); List annotations = type.getAnnotations(); for (AnnotationNode an : annotations) { configureAnnotationFromDefinition(an, node); } configureAnnotationFromDefinition(node, node); } private void configureAnnotation(AnnotationNode node, Annotation annotation) { Class type = annotation.annotationType(); if (type == Retention.class) { Retention r = (Retention) annotation; RetentionPolicy value = r.value(); setRetentionPolicy(value, node); node.setMember("value", new PropertyExpression( new ClassExpression(ClassHelper.makeWithoutCaching(RetentionPolicy.class, false)), value.toString())); } else if (type == Target.class) { Target t = (Target) annotation; ElementType[] elements = t.value(); ListExpression elementExprs = new ListExpression(); for (ElementType element : elements) { elementExprs.addExpression(new PropertyExpression( new ClassExpression(ClassHelper.ELEMENT_TYPE_TYPE), element.name())); } node.setMember("value", elementExprs); } else { Method[] declaredMethods = type.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { try { Object value = declaredMethod.invoke(annotation); Expression valueExpression = annotationValueToExpression(value); if (valueExpression == null) continue; node.setMember(declaredMethod.getName(), valueExpression); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } } private Expression annotationValueToExpression (Object value) { if (value == null || value instanceof String || value instanceof Number || value instanceof Character || value instanceof Boolean) return new ConstantExpression(value); if (value instanceof Class) return new ClassExpression(ClassHelper.makeWithoutCaching((Class)value)); if (value.getClass().isArray()) { ListExpression elementExprs = new ListExpression(); int len = Array.getLength(value); for (int i = 0; i != len; ++i) elementExprs.addExpression(annotationValueToExpression(Array.get(value, i))); return elementExprs; } return null; } private void setRetentionPolicy(RetentionPolicy value, AnnotationNode node) { switch (value) { case RUNTIME: node.setRuntimeRetention(true); break; case SOURCE: node.setSourceRetention(true); break; case CLASS: node.setClassRetention(true); break; default: throw new GroovyBugError("unsupported Retention " + value); } } private int getElementCode(ElementType value) { switch (value) { case TYPE: return AnnotationNode.TYPE_TARGET; case CONSTRUCTOR: return AnnotationNode.CONSTRUCTOR_TARGET; case METHOD: return AnnotationNode.METHOD_TARGET; case FIELD: return AnnotationNode.FIELD_TARGET; case PARAMETER: return AnnotationNode.PARAMETER_TARGET; case LOCAL_VARIABLE: return AnnotationNode.LOCAL_VARIABLE_TARGET; case ANNOTATION_TYPE: return AnnotationNode.ANNOTATION_TARGET; case PACKAGE: return AnnotationNode.PACKAGE_TARGET; default: throw new GroovyBugError("unsupported Target " + value); } } private void setMethodDefaultValue(MethodNode mn, Method m) { Object defaultValue = m.getDefaultValue(); ConstantExpression cExp = ConstantExpression.NULL; if (defaultValue!=null) cExp = new ConstantExpression(defaultValue); mn.setCode(new ReturnStatement(cExp)); mn.setAnnotationDefault(true); } public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) { Class clazz = classNode.getTypeClass(); Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType()); FieldNode fn = new FieldNode(f.getName(), f.getModifiers(), ret, classNode, null); setAnnotationMetaData(f.getAnnotations(), fn); classNode.addField(fn); } Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType()); Parameter[] params = makeParameters(compileUnit, m.getGenericParameterTypes(), m.getParameterTypes(), m.getParameterAnnotations()); ClassNode[] exceptions = makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes()); MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null); setMethodDefaultValue(mn, m); setAnnotationMetaData(m.getAnnotations(), mn); mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters())); classNode.addMethod(mn); } Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor ctor : constructors) { Parameter[] params = makeParameters(compileUnit, ctor.getGenericParameterTypes(), ctor.getParameterTypes(), ctor.getParameterAnnotations()); ClassNode[] exceptions = makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes()); classNode.addConstructor(ctor.getModifiers(), params, exceptions, null); } Class sc = clazz.getSuperclass(); if (sc != null) classNode.setUnresolvedSuperClass(makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc)); makeInterfaceTypes(compileUnit, classNode, clazz); setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode); PackageNode packageNode = classNode.getPackage(); if (packageNode != null) { setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode); } } private void makeInterfaceTypes(CompileUnit cu, ClassNode classNode, Class clazz) { Type[] interfaceTypes = clazz.getGenericInterfaces(); if (interfaceTypes.length == 0) { classNode.setInterfaces(ClassNode.EMPTY_ARRAY); } else { Class[] interfaceClasses = clazz.getInterfaces(); ClassNode[] ret = new ClassNode[interfaceTypes.length]; for (int i = 0; i < interfaceTypes.length; i++) { ret[i] = makeClassNode(cu, interfaceTypes[i], interfaceClasses[i]); } classNode.setInterfaces(ret); } } private ClassNode[] makeClassNodes(CompileUnit cu, Type[] types, Class[] cls) { ClassNode[] nodes = new ClassNode[types.length]; for (int i = 0; i < nodes.length; i++) { nodes[i] = makeClassNode(cu, types[i], cls[i]); } return nodes; } private ClassNode makeClassNode(CompileUnit cu, Type t, Class c) { ClassNode back = null; if (cu != null) back = cu.getClass(c.getName()); if (back == null) back = ClassHelper.make(c); if (!(t instanceof Class)) { ClassNode front = configureType(t); front.setRedirect(back); return front; } return back; } private Parameter[] makeParameters(CompileUnit cu, Type[] types, Class[] cls, Annotation[][] parameterAnnotations) { Parameter[] params = Parameter.EMPTY_ARRAY; if (types.length > 0) { params = new Parameter[types.length]; for (int i = 0; i < params.length; i++) { params[i] = makeParameter(cu, types[i], cls[i], parameterAnnotations[i], i); } } return params; } private Parameter makeParameter(CompileUnit cu, Type type, Class cl, Annotation[] annotations, int idx) { ClassNode cn = makeClassNode(cu, type, cl); Parameter parameter = new Parameter(cn, "param" + idx); setAnnotationMetaData(annotations, parameter); return parameter; } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/VMPluginFactory.java0000644001501200150120000000563411713765676025603 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin; import org.codehaus.groovy.vmplugin.v4.Java4; /** * factory class to get functionality based on the VM version. * The usage of this class is not for public use, only for the * runtime. * @author Jochen Theodorou */ public class VMPluginFactory { private static final String JDK5_CLASSNAME_CHECK = "java.lang.annotation.Annotation"; private static final String JDK5_PLUGIN_NAME = "org.codehaus.groovy.vmplugin.v5.Java5"; private static final String JDK6_CLASSNAME_CHECK = "javax.script.ScriptEngine"; private static final String JDK6_PLUGIN_NAME = "org.codehaus.groovy.vmplugin.v6.Java6"; private static final String JDK7_CLASSNAME_CHECK = "java.nio.file.FileRef"; private static final String JDK7_PLUGIN_NAME = "org.codehaus.groovy.vmplugin.v7.Java7"; private static VMPlugin plugin; static { try { // v6 plugin is the same as v5 but with some scripting stuff // so check below is good enough for now (can be true for JVM 5) ClassLoader loader = VMPluginFactory.class.getClassLoader(); loader.loadClass(JDK7_CLASSNAME_CHECK); plugin = (VMPlugin) loader.loadClass(JDK7_PLUGIN_NAME).newInstance(); } catch(Exception ex) { /* ignore */ } if (plugin == null) { try { // v6 plugin is the same as v5 but with some scripting stuff // so check below is good enough for now (can be true for JVM 5) ClassLoader loader = VMPluginFactory.class.getClassLoader(); loader.loadClass(JDK6_CLASSNAME_CHECK); plugin = (VMPlugin) loader.loadClass(JDK6_PLUGIN_NAME).newInstance(); } catch (Exception ex) { /* ignore */ } } if (plugin == null) { try { ClassLoader loader = VMPluginFactory.class.getClassLoader(); loader.loadClass(JDK5_CLASSNAME_CHECK); plugin = (VMPlugin) loader.loadClass(JDK5_PLUGIN_NAME).newInstance(); } catch(Exception ex) { plugin = new Java4(); } } } public static VMPlugin getPlugin() { return plugin; } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v7/0000755001501200150120000000000011713765676022233 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v7/Java7.java0000644001501200150120000000171411707612046024032 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v7; import org.codehaus.groovy.vmplugin.v6.Java6; /** * Java 7 based functions. Currently just a stub but you can * add your own methods to your own version and place it on the classpath * ahead of this one. * * @author Jochen Theodorou */ public class Java7 extends Java6 { } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v6/0000755001501200150120000000000011707612046022213 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v6/PluginStaticGroovyMethods.java0000644001501200150120000000345611707612046030226 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v6; import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * This class defines new Java 6 specific static groovy methods which extend the normal * JDK classes inside the Groovy environment. */ public class PluginStaticGroovyMethods extends DefaultGroovyMethodsSupport { /** * Provides a convenient shorthand for accessing a Scripting Engine with name languageShortName * using a newly created ScriptEngineManager instance. * * @param self Placeholder variable used by Groovy categories; ignored for default static methods * @param languageShortName The short name of the scripting engine of interest * @return the ScriptEngine corresponding to the supplied short name or null if no engine was found * @since 1.8.0 */ public static ScriptEngine $static_propertyMissing(ScriptEngineManager self, String languageShortName) { ScriptEngineManager manager = new ScriptEngineManager(); return manager.getEngineByName(languageShortName); } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v6/PluginDefaultGroovyMethods.java0000644001501200150120000000751711627206700030362 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v6; import groovy.lang.Binding; import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.io.Reader; import java.util.Map; import java.util.Set; /** * This class defines new Java 6 specific groovy methods which extend the normal * JDK classes inside the Groovy environment. Static methods are used with the * first parameter the destination class. */ public class PluginDefaultGroovyMethods extends DefaultGroovyMethodsSupport { /** * Executes the specified script. The default ScriptContext for the ScriptEngine * is used. Variables from a Groovy Binding are made available in the default scope of the * Bindings of the ScriptEngine. Resulting variables in the Bindings * are returned back to the Groovy Binding. * * @param self A ScriptEngine * @param script The script language source to be executed * @param binding A Groovy binding * @return The value returned from the execution of the script (if supported by the Script engine) * @throws javax.script.ScriptException if error occurs in script * @throws NullPointerException if the argument is null * @see #eval(javax.script.ScriptEngine, java.io.Reader, groovy.lang.Binding) * @since 1.7.3 */ public static Object eval(ScriptEngine self, String script, Binding binding) throws ScriptException { storeBindingVars(self, binding); Object result = self.eval(script); retrieveBindingVars(self, binding); return result; } /** * Same as eval(ScriptEngine, Reader, Binding) except that the * source of the script is provided as a Reader * * @param self A ScriptEngine * @param reader The source of the script * @param binding A Groovy binding * @return The value returned by the script * @throws javax.script.ScriptException if an error occurs in script * @throws NullPointerException if the argument is null * @see #eval(javax.script.ScriptEngine, java.lang.String, groovy.lang.Binding) * @since 1.7.3 */ public static Object eval(ScriptEngine self, Reader reader, Binding binding) throws ScriptException { storeBindingVars(self, binding); Object result = self.eval(reader); retrieveBindingVars(self, binding); return result; } private static void retrieveBindingVars(ScriptEngine self, Binding binding) { Set> returnVars = self.getBindings(ScriptContext.ENGINE_SCOPE).entrySet(); for (Map.Entry me : returnVars) { binding.setVariable(me.getKey(), me.getValue()); } } @SuppressWarnings("unchecked") private static void storeBindingVars(ScriptEngine self, Binding binding) { Set vars = binding.getVariables().entrySet(); for (Map.Entry me : vars) { self.put(me.getKey().toString(), me.getValue()); } } } groovy-1.8.6/src/main/org/codehaus/groovy/vmplugin/v6/Java6.java0000644001501200150120000000240211707612046024023 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.vmplugin.v6; import org.codehaus.groovy.vmplugin.v5.Java5; /** * Java 6 based functions * * @author Jochen Theodorou */ public class Java6 extends Java5 { private static final Class[] PLUGIN_DGM = {PluginDefaultGroovyMethods.class, org.codehaus.groovy.vmplugin.v5.PluginDefaultGroovyMethods.class}; private static final Class[] STATIC_PLUGIN_DGM = {PluginStaticGroovyMethods.class}; public Class[] getPluginDefaultGroovyMethods() { return PLUGIN_DGM; } public Class[] getPluginStaticGroovyMethods() { return STATIC_PLUGIN_DGM; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/0000755001501200150120000000000011715031256022146 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/reflection/MethodHandle.java0000644001501200150120000040163411715031256025355 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.codehaus.groovy.runtime.ArrayUtil; /** * This class is unused and will be removed in Groovy 1.9 */ @Deprecated public class MethodHandle { protected MethodHandle () { } public Object invoke(Object receiver, Object [] args) throws Throwable { throw new AbstractMethodError(); } public Object invoke(Object receiver) throws Throwable { return invoke(receiver,ArrayUtil.createArray()); } public Object invoke(Object receiver, Object arg1, Object arg2, Object arg3, Object arg4) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3,arg4)); } public Object invoke(Object receiver, boolean arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, boolean arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, boolean arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, boolean arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, char arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, char arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver, ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, char arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, byte arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, byte arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, byte arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, short arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, short arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, short arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, int arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, int arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, int arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, long arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, long arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, long arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, float arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, float arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, float arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, double arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, double arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, double arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); } public Object invoke(Object receiver, Object arg1, boolean arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, boolean arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, boolean arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, char arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, char arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, byte arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, byte arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, short arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, short arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, int arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, int arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, long arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, long arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, float arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, float arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, double arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, double arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); } public Object invoke(Object receiver, Object arg1, Object arg2, boolean arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, char arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, byte arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, short arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, int arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, long arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, float arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, double arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } public Object invoke(Object receiver, Object arg1, Object arg2, Object arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/MixinInMetaClass.java0000644001501200150120000001744211627206700026171 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.DelegatingMetaClass; import groovy.lang.ExpandoMetaClass; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import groovy.lang.MetaMethod; import groovy.lang.MetaProperty; import org.codehaus.groovy.runtime.HandleMetaClass; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.metaclass.MixedInMetaClass; import org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaMethod; import org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaProperty; import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod; import org.codehaus.groovy.util.ManagedConcurrentMap; import org.codehaus.groovy.util.ReferenceBundle; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; public class MixinInMetaClass extends ManagedConcurrentMap { final ExpandoMetaClass emc; final CachedClass mixinClass; final CachedConstructor constructor; private static ReferenceBundle softBundle = ReferenceBundle.getSoftBundle(); public MixinInMetaClass(ExpandoMetaClass emc, CachedClass mixinClass) { super(softBundle); this.emc = emc; this.mixinClass = mixinClass; constructor = findDefaultConstructor(mixinClass); emc.addMixinClass(this); } private CachedConstructor findDefaultConstructor(CachedClass mixinClass) { for (CachedConstructor constr : mixinClass.getConstructors()) { if (!Modifier.isPublic(constr.getModifiers())) continue; CachedClass[] classes = constr.getParameterTypes(); if (classes.length == 0) return constr; } throw new GroovyRuntimeException("No default constructor for class " + mixinClass.getName() + "! Can't be mixed in."); } public synchronized Object getMixinInstance(Object object) { Object mixinInstance = get(object); if (mixinInstance == null) { mixinInstance = constructor.invoke(MetaClassHelper.EMPTY_ARRAY); new MixedInMetaClass(mixinInstance, object); put(object, mixinInstance); } return mixinInstance; } public synchronized void setMixinInstance(Object object, Object mixinInstance) { if (mixinInstance == null) { remove(object); } else { put(object, mixinInstance); } } public CachedClass getInstanceClass() { return emc.getTheCachedClass(); } public CachedClass getMixinClass() { return mixinClass; } public static void mixinClassesToMetaClass(MetaClass self, List categoryClasses) { final Class selfClass = self.getTheClass(); if (self instanceof HandleMetaClass) { self = (MetaClass) ((HandleMetaClass) self).replaceDelegate(); } if (!(self instanceof ExpandoMetaClass)) { if (self instanceof DelegatingMetaClass && ((DelegatingMetaClass) self).getAdaptee() instanceof ExpandoMetaClass) { self = ((DelegatingMetaClass) self).getAdaptee(); } else { throw new GroovyRuntimeException("Can't mixin methods to meta class: " + self); } } ExpandoMetaClass mc = (ExpandoMetaClass) self; List arr = new ArrayList(); for (Class categoryClass : categoryClasses) { final CachedClass cachedCategoryClass = ReflectionCache.getCachedClass(categoryClass); final MixinInMetaClass mixin = new MixinInMetaClass(mc, cachedCategoryClass); final MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(categoryClass); final List propList = metaClass.getProperties(); for (MetaProperty prop : propList) if (self.getMetaProperty(prop.getName()) == null) { mc.registerBeanProperty(prop.getName(), new MixinInstanceMetaProperty(prop, mixin)); } for (MetaProperty prop : cachedCategoryClass.getFields()) if (self.getMetaProperty(prop.getName()) == null) { mc.registerBeanProperty(prop.getName(), new MixinInstanceMetaProperty(prop, mixin)); } for (MetaMethod method : metaClass.getMethods()) { final int mod = method.getModifiers(); if (!Modifier.isPublic(mod)) continue; if (method instanceof CachedMethod && ((CachedMethod) method).getCachedMethod().isSynthetic()) continue; if (Modifier.isStatic(mod)) { if (method instanceof CachedMethod) staticMethod(self, arr, (CachedMethod) method); } else if (method.getDeclaringClass().getTheClass() != Object.class || method.getName().equals("toString")) { // if (self.pickMethod(method.getName(), method.getNativeParameterTypes()) == null) { final MixinInstanceMetaMethod metaMethod = new MixinInstanceMetaMethod(method, mixin); arr.add(metaMethod); // } } } } for (Object res : arr) { final MetaMethod metaMethod = (MetaMethod) res; if (metaMethod.getDeclaringClass().isAssignableFrom(selfClass)) mc.registerInstanceMethod(metaMethod); else { mc.registerSubclassInstanceMethod(metaMethod); } } } private static void staticMethod(final MetaClass self, List arr, final CachedMethod method) { CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) return; NewInstanceMetaMethod metaMethod; if (paramTypes[0].isAssignableFrom(self.getTheClass())) { if (paramTypes[0].getTheClass() == self.getTheClass()) metaMethod = new NewInstanceMetaMethod(method); else metaMethod = new NewInstanceMetaMethod(method) { public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(self.getTheClass()); } }; arr.add(metaMethod); } else { if (self.getTheClass().isAssignableFrom(paramTypes[0].getTheClass())) { metaMethod = new NewInstanceMetaMethod(method); arr.add(metaMethod); } } } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MixinInMetaClass)) return false; if (!super.equals(o)) return false; MixinInMetaClass that = (MixinInMetaClass) o; if (mixinClass != null ? !mixinClass.equals(that.mixinClass) : that.mixinClass != null) return false; return true; } public int hashCode() { int result = super.hashCode(); result = 31 * result + (emc != null ? emc.hashCode() : 0); result = 31 * result + (mixinClass != null ? mixinClass.hashCode() : 0); result = 31 * result + (constructor != null ? constructor.hashCode() : 0); return result; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/CachedMethod.java0000644001501200150120000003035611715031256025330 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import groovy.lang.MissingMethodException; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.runtime.InvokerInvocationException; import org.codehaus.groovy.runtime.callsite.*; import org.codehaus.groovy.runtime.metaclass.MethodHelper; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * @author Alex.Tkachman */ public class CachedMethod extends MetaMethod implements Comparable { public final CachedClass cachedClass; private final Method cachedMethod; private int hashCode; private static MyComparator comparator = new MyComparator(); private SoftReference pogoCallSiteConstructor, pojoCallSiteConstructor, staticCallSiteConstructor; private boolean skipCompiled; public CachedMethod(CachedClass clazz, Method method) { this.cachedMethod = method; this.cachedClass = clazz; } public CachedMethod(Method method) { this(ReflectionCache.getCachedClass(method.getDeclaringClass()),method); } public static CachedMethod find(Method method) { CachedMethod[] methods = ReflectionCache.getCachedClass(method.getDeclaringClass()).getMethods(); // for (int i = 0; i < methods.length; i++) { // CachedMethod cachedMethod = methods[i]; // if (cachedMethod.cachedMethod.equals(method)) // return cachedMethod; // } // return null; int i = Arrays.binarySearch(methods, method, comparator); if (i < 0) return null; return methods[i]; } protected Class[] getPT() { return cachedMethod.getParameterTypes(); } public String getName() { return cachedMethod.getName(); } public String getDescriptor() { return BytecodeHelper.getMethodDescriptor(getReturnType(), getNativeParameterTypes()); } public CachedClass getDeclaringClass() { return cachedClass; } public final Object invoke(Object object, Object[] arguments) { try { return cachedMethod.invoke(object, arguments); } catch (IllegalArgumentException e) { throw new InvokerInvocationException(e); } catch (IllegalAccessException e) { throw new InvokerInvocationException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); throw (cause instanceof RuntimeException && !(cause instanceof MissingMethodException)) ? (RuntimeException) cause : new InvokerInvocationException(e); } } public ParameterTypes getParamTypes() { return null; } public Class getReturnType() { return cachedMethod.getReturnType(); } public int getParamsCount() { return getParameterTypes().length; } public int getModifiers() { return cachedMethod.getModifiers(); } public String getSignature() { return getName() + getDescriptor(); } public final Method setAccessible() { // if (queuedToCompile.compareAndSet(false,true)) { // if (isCompilable()) // CompileThread.addMethod(this); // } return cachedMethod; } public boolean isStatic() { return MethodHelper.isStatic(cachedMethod); } public int compareTo(Object o) { if (o instanceof CachedMethod) return compareToCachedMethod((CachedMethod)o); else return compareToMethod((Method)o); } private int compareToCachedMethod(CachedMethod m) { if (m == null) return -1; final int strComp = getName().compareTo(m.getName()); if (strComp != 0) return strComp; final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName()); if (retComp != 0) return retComp; CachedClass[] params = getParameterTypes(); CachedClass [] mparams = m.getParameterTypes(); final int pd = params.length - mparams.length; if (pd != 0) return pd; for (int i = 0; i != params.length; ++i) { final int nameComp = params[i].getName().compareTo(mparams[i].getName()); if (nameComp != 0) return nameComp; } throw new RuntimeException("Should never happen"); } private int compareToMethod(Method m) { if (m == null) return -1; final int strComp = getName().compareTo(m.getName()); if (strComp != 0) return strComp; final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName()); if (retComp != 0) return retComp; CachedClass[] params = getParameterTypes(); Class [] mparams = m.getParameterTypes(); final int pd = params.length - mparams.length; if (pd != 0) return pd; for (int i = 0; i != params.length; ++i) { final int nameComp = params[i].getName().compareTo(mparams[i].getName()); if (nameComp != 0) return nameComp; } return 0; } public boolean equals(Object o) { return (o instanceof CachedMethod && cachedMethod.equals(((CachedMethod)o).cachedMethod)) || (o instanceof Method && cachedMethod.equals(o)); } public int hashCode() { if (hashCode == 0) { hashCode = cachedMethod.hashCode(); if (hashCode == 0) hashCode = 0xcafebebe; } return hashCode; } public String toString() { return cachedMethod.toString(); } private Constructor getConstrcutor(SoftReference ref) { if (ref==null) return null; return ref.get(); } public CallSite createPogoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) { if (!skipCompiled) { Constructor constr = getConstrcutor(pogoCallSiteConstructor); if (constr==null) { if (CallSiteGenerator.isCompilable(this)) { constr = CallSiteGenerator.compilePogoMethod(this); } if (constr != null) { pogoCallSiteConstructor = new SoftReference (constr); } else { skipCompiled = true; } } if (constr!=null) { try { return (CallSite) constr.newInstance(site, metaClass, this, params, constr); } catch (Error e) { skipCompiled=true; throw e; } catch (Throwable e) { skipCompiled=true; } } } return new PogoMetaMethodSite.PogoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params); } public CallSite createPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) { if (!skipCompiled) { Constructor constr = getConstrcutor(pojoCallSiteConstructor); if (constr==null) { if (CallSiteGenerator.isCompilable(this)) { constr = CallSiteGenerator.compilePojoMethod(this); } if (constr != null) { pojoCallSiteConstructor = new SoftReference (constr); } else { skipCompiled = true; } } if (constr!=null) { try { return (CallSite) constr.newInstance(site, metaClass, this, params, constr); } catch (Error e) { skipCompiled=true; throw e; } catch (Throwable e) { skipCompiled=true; } } } return new PojoMetaMethodSite.PojoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params); } public CallSite createStaticMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) { if (!skipCompiled) { Constructor constr = getConstrcutor(staticCallSiteConstructor); if (constr==null) { if (CallSiteGenerator.isCompilable(this)) { constr = CallSiteGenerator.compileStaticMethod(this); } if (constr != null) { staticCallSiteConstructor = new SoftReference (constr); } else { skipCompiled = true; } } if (constr!=null) { try { return (CallSite) constr.newInstance(site, metaClass, this, params, constr); } catch (Error e) { skipCompiled=true; throw e; } catch (Throwable e) { skipCompiled=true; } } } return new StaticMetaMethodSite.StaticMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params); } //TODO: deprecate and remove this method public boolean hasPogoCallSiteConstructor() { return pogoCallSiteConstructor != null && pogoCallSiteConstructor.get() != null; } //TODO: deprecate and remove this method public boolean hasPojoCallSiteConstructor() { return pojoCallSiteConstructor != null && pojoCallSiteConstructor.get() != null; } //TODO: deprecate and remove this method public boolean hasStaticCallSiteConstructor() { return staticCallSiteConstructor != null && staticCallSiteConstructor.get() != null; } private static class MyComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 instanceof CachedMethod) return ((CachedMethod)o1).compareTo(o2); else if (o2 instanceof CachedMethod) return -((CachedMethod)o2).compareTo(o1); else // really, this should never happen, it's evidence of corruption if it does throw new ClassCastException("One of the two comparables must be a CachedMethod"); } } public Method getCachedMethod() { return cachedMethod; } // private static class CompileThread extends Thread { // static final LinkedBlockingQueue queue = new LinkedBlockingQueue(); // // static { // new CompileThread().start(); // } // // private CompileThread() { // setDaemon(true); // setPriority(Thread.MAX_PRIORITY-2); // } // // public void run() { // try { // while (true) { // final CachedMethod method = (CachedMethod) queue.take(); // if (method != null) { // CallSiteGenerator.compilePogoMethod(method); // } // } // } // catch (InterruptedException e) {// // } // } // // public static void addMethod (CachedMethod method) { // try { // queue.put(method); // } catch (InterruptedException e) { // } // } // } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/handlegen.groovy0000644001501200150120000000272011715031256025343 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection System.err.println "WARNING: this class is deprecated and will be removed in Groovy 1.9" def types = [ "boolean", "char", "byte", "short", "int", "long", "float", "double", "Object" ] types.each { arg1 -> println "public Object invoke(Object receiver, $arg1 arg1) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1)); }" types.each { arg2 -> println "public Object invoke(Object receiver, $arg1 arg1, $arg2 arg2) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2)); }" types.each { arg3 -> println "public Object invoke(Object receiver, $arg1 arg1, $arg2 arg2, $arg3 arg3) throws Throwable { return invoke(receiver,ArrayUtil.createArray(arg1,arg2,arg3)); }" } } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/SunClassLoader.java0000644001501200150120000000762411627206700025704 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.objectweb.asm.Opcodes; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.ClassReader; import java.util.Map; import java.util.HashMap; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; import java.security.PrivilegedAction; /** * Special class loader, which when running on Sun VM allows to generate accessor classes for any method */ public class SunClassLoader extends ClassLoader implements Opcodes { protected final Map knownClasses = new HashMap(); protected static final SunClassLoader sunVM; static { SunClassLoader res; try { res = AccessController.doPrivileged(new PrivilegedAction() { public SunClassLoader run() { try { return new SunClassLoader(); } catch (Throwable e) { return null; } } }); } catch (Throwable e) { res = null; } sunVM = res; } protected SunClassLoader() throws Throwable { super (SunClassLoader.class.getClassLoader()); final Class magic = ClassLoader.getSystemClassLoader().loadClass("sun.reflect.MagicAccessorImpl"); knownClasses.put("sun.reflect.MagicAccessorImpl", magic); loadMagic (); } private void loadMagic() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC, "sun/reflect/GroovyMagic", null, "sun/reflect/MagicAccessorImpl", null); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "sun/reflect/MagicAccessorImpl", "", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(0,0); mv.visitEnd(); cw.visitEnd(); define(cw.toByteArray(), "sun.reflect.GroovyMagic"); } protected void loadFromRes(String name) throws IOException { final InputStream asStream = SunClassLoader.class.getClassLoader().getResourceAsStream(resName(name)); ClassReader reader = new ClassReader(asStream); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); reader.accept(cw, ClassWriter.COMPUTE_MAXS); asStream.close(); define(cw.toByteArray(), name); } protected static String resName(String s) { return s.replace('.','/') + ".class"; } protected void define(byte[] bytes, final String name) { knownClasses.put(name, defineClass(name, bytes, 0, bytes.length)); } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { final Class aClass = knownClasses.get(name); if (aClass != null) return aClass; else { try { return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { return getClass().getClassLoader().loadClass(name); } } } public Class doesKnow(String name) { return knownClasses.get(name); } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/ParameterTypes.java0000644001501200150120000003341311713765676026004 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.runtime.MetaClassHelper; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.wrappers.Wrapper; import java.lang.reflect.Array; public class ParameterTypes { protected volatile Class [] nativeParamTypes; protected volatile CachedClass [] parameterTypes; protected boolean isVargsMethod; public ParameterTypes () { } public ParameterTypes(Class pt []) { nativeParamTypes = pt; } public ParameterTypes(String pt[]) { nativeParamTypes = new Class[pt.length]; for (int i = 0; i != pt.length; ++i) { try { nativeParamTypes[i] = Class.forName(pt[i]); } catch (ClassNotFoundException e){ NoClassDefFoundError err = new NoClassDefFoundError(); err.initCause(e); throw err; } } } public ParameterTypes(CachedClass[] parameterTypes) { setParametersTypes(parameterTypes); } protected final void setParametersTypes(CachedClass[] pt) { this.parameterTypes = pt; isVargsMethod = pt.length > 0 && pt [pt.length-1].isArray; } public CachedClass[] getParameterTypes() { if (parameterTypes == null) { getParametersTypes0(); } return parameterTypes; } private synchronized void getParametersTypes0() { if (parameterTypes != null) return; Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes; CachedClass[] pt = new CachedClass [npt.length]; for (int i = 0; i != npt.length; ++i) pt[i] = ReflectionCache.getCachedClass(npt[i]); nativeParamTypes = npt; setParametersTypes(pt); } public Class[] getNativeParameterTypes() { if (nativeParamTypes == null) { getNativeParameterTypes0(); } return nativeParamTypes; } private synchronized void getNativeParameterTypes0() { if (nativeParamTypes != null) return; Class [] npt; if (parameterTypes != null) { npt = new Class [parameterTypes.length]; for (int i = 0; i != parameterTypes.length; ++i) { npt[i] = parameterTypes[i].getTheClass(); } } else npt = getPT (); nativeParamTypes = npt; } protected Class[] getPT() { throw new UnsupportedOperationException(getClass().getName()); } public boolean isVargsMethod(Object[] arguments) { // Uncomment if at some point this method can be called before parameterTypes initialized // getParameterTypes(); if(!isVargsMethod) return false; final int lenMinus1 = parameterTypes.length - 1; // -1 because the varg part is optional if (lenMinus1 == arguments.length) return true; if (lenMinus1 > arguments.length) return false; if (arguments.length > parameterTypes.length) return true; // only case left is arguments.length == parameterTypes.length Object last = arguments[arguments.length - 1]; if (last == null) return true; Class clazz = last.getClass(); return !clazz.equals(parameterTypes[lenMinus1].getTheClass()); } public final Object[] coerceArgumentsToClasses(Object[] argumentArray) { // Uncomment if at some point this method can be called before parameterTypes initialized // getParameterTypes(); argumentArray = correctArguments(argumentArray); final CachedClass[] pt = parameterTypes; final int len = argumentArray.length; for (int i = 0; i < len; i++) { final Object argument = argumentArray[i]; if (argument != null) { argumentArray[i] = pt[i].coerceArgument(argument); } } return argumentArray; } public Object[] correctArguments(Object[] argumentArray) { // correct argumentArray's length if (argumentArray == null) { return MetaClassHelper.EMPTY_ARRAY; } final CachedClass[] pt = getParameterTypes(); if (pt.length == 1 && argumentArray.length == 0) { if (isVargsMethod) return new Object[]{Array.newInstance(pt[0].getTheClass().getComponentType(), 0)}; else return MetaClassHelper.ARRAY_WITH_NULL; } if (isVargsMethod && isVargsMethod(argumentArray)) { return fitToVargs(argumentArray, pt); } return argumentArray; } /** * this method is called when the number of arguments to a method is greater than 1 * and if the method is a vargs method. This method will then transform the given * arguments to make the method callable * * @param argumentArray the arguments used to call the method * @param paramTypes the types of the parameters the method takes */ private static Object[] fitToVargs(Object[] argumentArrayOrig, CachedClass[] paramTypes) { Class vargsClassOrig = paramTypes[paramTypes.length - 1].getTheClass().getComponentType(); Class vargsClass = ReflectionCache.autoboxType(vargsClassOrig); Object[] argumentArray = argumentArrayOrig.clone(); MetaClassHelper.unwrap(argumentArray); if (argumentArray.length == paramTypes.length - 1) { // the vargs argument is missing, so fill it with an empty array Object[] newArgs = new Object[paramTypes.length]; System.arraycopy(argumentArray, 0, newArgs, 0, argumentArray.length); Object vargs = Array.newInstance(vargsClass, 0); newArgs[newArgs.length - 1] = vargs; return newArgs; } else if (argumentArray.length == paramTypes.length) { // the number of arguments is correct, but if the last argument // is no array we have to wrap it in a array. If the last argument // is null, then we don't have to do anything Object lastArgument = argumentArray[argumentArray.length - 1]; if (lastArgument != null && !lastArgument.getClass().isArray()) { // no array so wrap it Object wrapped = makeCommonArray(argumentArray, paramTypes.length - 1, vargsClass); Object[] newArgs = new Object[paramTypes.length]; System.arraycopy(argumentArray, 0, newArgs, 0, paramTypes.length - 1); newArgs[newArgs.length - 1] = wrapped; return newArgs; } else { // we may have to box the argument! return argumentArray; } } else if (argumentArray.length > paramTypes.length) { // the number of arguments is too big, wrap all exceeding elements // in an array, but keep the old elements that are no vargs Object[] newArgs = new Object[paramTypes.length]; // copy arguments that are not a varg System.arraycopy(argumentArray, 0, newArgs, 0, paramTypes.length - 1); // create a new array for the vargs and copy them Object vargs = makeCommonArray(argumentArray, paramTypes.length - 1, vargsClass); newArgs[newArgs.length - 1] = vargs; return newArgs; } else { throw new GroovyBugError("trying to call a vargs method without enough arguments"); } } private static Object makeCommonArray(Object[] arguments, int offset, Class baseClass) { Object[] result = (Object[]) Array.newInstance(baseClass, arguments.length - offset); for (int i=offset; i= paramMinus1) return isValidVarargsMethod(arguments, size, pt, paramMinus1); else if (pt.length == size) return isValidExactMethod(arguments, pt); else if (pt.length == 1 && size == 0 && !pt[0].isPrimitive) return true; return false; } private boolean isValidExactMethod(Class[] arguments, CachedClass[] pt) { // lets check the parameter types match int size = pt.length; for (int i = 0; i < size; i++) { if (!pt[i].isAssignableFrom(arguments[i])) { return false; } } return true; } public boolean isValidExactMethod(Object [] args) { // lets check the parameter types match getParametersTypes0(); int size = args.length; if (size != parameterTypes.length) return false; for (int i = 0; i < size; i++) { if (args[i] != null && !parameterTypes[i].isAssignableFrom(args[i].getClass())) { return false; } } return true; } public boolean isValidExactMethod(Class [] args) { // lets check the parameter types match getParametersTypes0(); int size = args.length; if (size != parameterTypes.length) return false; for (int i = 0; i < size; i++) { if (args[i] != null && !parameterTypes[i].isAssignableFrom(args[i])) { return false; } } return true; } private static boolean testComponentAssignable(Class toTestAgainst, Class toTest) { Class component = toTest.getComponentType(); if (component==null) return false; return MetaClassHelper.isAssignableFrom(toTestAgainst, component); } private boolean isValidVarargsMethod(Class[] arguments, int size, CachedClass[] pt, int paramMinus1) { // first check normal number of parameters for (int i = 0; i < paramMinus1; i++) { if (pt[i].isAssignableFrom(arguments[i])) continue; return false; } // check direct match CachedClass varg = pt[paramMinus1]; Class clazz = varg.getTheClass().getComponentType(); if ( size==pt.length && (varg.isAssignableFrom(arguments[paramMinus1]) || testComponentAssignable(clazz, arguments[paramMinus1]))) { return true; } // check varged for (int i = paramMinus1; i < size; i++) { if (MetaClassHelper.isAssignableFrom(clazz, arguments[i])) continue; return false; } return true; } public boolean isValidMethod(Object[] arguments) { if (arguments == null) return true; final int size = arguments.length; CachedClass[] paramTypes = getParameterTypes(); final int paramMinus1 = paramTypes.length-1; if ( size >= paramMinus1 && paramTypes.length > 0 && paramTypes[(paramMinus1)].isArray) { // first check normal number of parameters for (int i = 0; i < paramMinus1; i++) { if (paramTypes[i].isAssignableFrom(getArgClass(arguments[i]))) continue; return false; } // check direct match CachedClass varg = paramTypes[paramMinus1]; Class clazz = varg.getTheClass().getComponentType(); if ( size==paramTypes.length && (varg.isAssignableFrom(getArgClass(arguments[paramMinus1])) || testComponentAssignable(clazz, getArgClass(arguments[paramMinus1])))) { return true; } // check varged for (int i = paramMinus1; i < size; i++) { if (MetaClassHelper.isAssignableFrom(clazz, getArgClass(arguments[i]))) continue; return false; } return true; } else if (paramTypes.length == size) { // lets check the parameter types match for (int i = 0; i < size; i++) { if (paramTypes[i].isAssignableFrom(getArgClass(arguments[i]))) continue; return false; } return true; } else if (paramTypes.length == 1 && size == 0 && !paramTypes[0].isPrimitive) { return true; } return false; } private Class getArgClass(Object arg) { Class cls; if (arg == null) { cls = null; } else { if (arg instanceof Wrapper) { cls = ((Wrapper)arg).getType(); } else cls = arg.getClass(); } return cls; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/ReflectionUtils.java0000644001501200150120000001254311627206700026131 0ustar miguelmiguel/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.Collections; /** * This class contains utility methods to determine which class called the * current class to multiple levels of depth. Calls used to handle the * groovy MOP are excluded from the level counting. */ public class ReflectionUtils { // these are packages in the call stack that are only part of the groovy MOP private static final Set IGNORED_PACKAGES = new HashSet(); static { //IGNORED_PACKAGES.add("java.lang.reflect"); IGNORED_PACKAGES.add("groovy.lang"); IGNORED_PACKAGES.add("org.codehaus.groovy.reflection"); IGNORED_PACKAGES.add("org.codehaus.groovy.runtime.callsite"); IGNORED_PACKAGES.add("org.codehaus.groovy.runtime.metaclass"); IGNORED_PACKAGES.add("org.codehaus.groovy.runtime"); IGNORED_PACKAGES.add("sun.reflect"); } private static final Method MAGIC_METHOD; static { Method meth; try { Class srr = Class.forName("sun.reflect.Reflection"); meth = srr.getMethod("getCallerClass", Integer.TYPE); } catch (Throwable t) { meth = null; } MAGIC_METHOD = meth; } /** * Determine whether or not the getCallingClass methods will return * any sensible results. On JVMs that are not Sun derived i.e. * (gcj, Harmony) this will likely return false. When not available * all getCallingClass methods will return null. * * @return true if getCallingClass can return anything but null, false if * it will only return null. */ public static boolean isCallingClassReflectionAvailable() { return MAGIC_METHOD != null; } /** * Get the immediate calling class, ignoring MOP frames. * * @return The Class of the caller */ public static Class getCallingClass() { return getCallingClass(1); } /** * Get the called that is matchLevel stack frames before the call, * ignoring MOP frames. * * @param matchLevel how may call stacks down to look. * If it is less than 1 it is treated as though it was 1. * @return The Class of the matched caller, or null if there aren't * enough stackframes to satisfy matchLevel */ public static Class getCallingClass(int matchLevel) { return getCallingClass(matchLevel, Collections.EMPTY_SET); } /** * Get the called that is matchLevel stack frames before the call, * ignoring MOP frames and desired exclude packages. * * @param matchLevel how may call stacks down to look. * If it is less than 1 it is treated as though it was 1. * @param extraIgnoredPackages A collection of string names of packages to exclude * in addition to the MOP packages when counting stack frames. * @return The Class of the matched caller, or null if there aren't * enough stackframes to satisfy matchLevel */ public static Class getCallingClass(int matchLevel, Collection extraIgnoredPackages) { if (MAGIC_METHOD == null) { return null; } int depth = 0; try { Class c; // this super class stuff is for Java 1.4 support only // it isn't needed on a 5.0 VM Class sc; do { do { c = (Class) MAGIC_METHOD.invoke(null, depth++); if (c != null) { sc = c.getSuperclass(); } else { sc = null; } } while (classShouldBeIgnored(c, extraIgnoredPackages) || superClassShouldBeIgnored(sc)); } while (c != null && matchLevel-- > 0); return c; } catch (Throwable t) { return null; } } private static boolean superClassShouldBeIgnored(Class sc) { return ((sc != null) && (sc.getPackage() != null) && "org.codehaus.groovy.runtime.callsite".equals(sc.getPackage().getName())); } private static boolean classShouldBeIgnored(Class c, Collection extraIgnoredPackages) { return ((c != null) && (c.isSynthetic() || (c.getPackage() != null && (IGNORED_PACKAGES.contains(c.getPackage().getName()) || extraIgnoredPackages.contains(c.getPackage().getName()))))); } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/GeneratedMetaMethod.java0000644001501200150120000001772211707612046026673 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaMethod; import java.lang.reflect.Modifier; import java.lang.reflect.Constructor; import java.io.*; import java.util.*; public abstract class GeneratedMetaMethod extends MetaMethod { private final String name; private final CachedClass declaringClass; private final Class returnType; public GeneratedMetaMethod(String name, CachedClass declaringClass, Class returnType, Class[] parameters) { this.name = name; this.declaringClass = declaringClass; this.returnType = returnType; nativeParamTypes = parameters; } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return returnType; } public CachedClass getDeclaringClass() { return declaringClass; } public static class Proxy extends GeneratedMetaMethod { private volatile MetaMethod proxy; private final String className; public Proxy(String className, String name, CachedClass declaringClass, Class returnType, Class[] parameters) { super(name, declaringClass, returnType, parameters); this.className = className; } @Override public boolean isValidMethod(Class[] arguments) { return proxy().isValidMethod(arguments); } @Override public Object doMethodInvoke(Object object, Object[] argumentArray) { return proxy().doMethodInvoke(object, argumentArray); } public Object invoke(Object object, Object[] arguments) { return proxy().invoke(object, arguments); } public final synchronized MetaMethod proxy() { if (proxy == null) { createProxy(); } return proxy; } private void createProxy() { try { Class aClass = getClass().getClassLoader().loadClass(className.replace('/', '.')); Constructor constructor = aClass.getConstructor(String.class, CachedClass.class, Class.class, Class[].class); proxy = (MetaMethod) constructor.newInstance(getName(), getDeclaringClass(), getReturnType(), getNativeParameterTypes()); } catch (Throwable t) { t.printStackTrace(); throw new GroovyRuntimeException("Failed to create DGM method proxy : " + t, t); } } } public static class DgmMethodRecord implements Serializable { public String className; public String methodName; public Class returnType; public Class[] parameters; private static final Class[] PRIMITIVE_CLASSES = { Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Double.TYPE, Float.TYPE, Void.TYPE, boolean[].class, char[].class, byte[].class, short[].class, int[].class, long[].class, double[].class, float[].class, Object[].class, String[].class, Class[].class, Byte[].class, CharSequence[].class, }; public static void saveDgmInfo(List records, String file) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Map classes = new LinkedHashMap(); int nextClassId = 0; for (Class primitive : PRIMITIVE_CLASSES) { classes.put(primitive.getName(), nextClassId++); } for (DgmMethodRecord record : records) { String name = record.returnType.getName(); Integer id = classes.get(name); if (id == null) { id = nextClassId++; classes.put(name, id); } for (int i = 0; i < record.parameters.length; i++) { name = record.parameters[i].getName(); id = classes.get(name); if (id == null) { id = nextClassId++; classes.put(name, id); } } } for (Map.Entry stringIntegerEntry : classes.entrySet()) { out.writeUTF(stringIntegerEntry.getKey()); out.writeInt(stringIntegerEntry.getValue()); } out.writeUTF(""); out.writeInt(records.size()); for (DgmMethodRecord record : records) { out.writeUTF(record.className); out.writeUTF(record.methodName); out.writeInt(classes.get(record.returnType.getName())); out.writeInt(record.parameters.length); for (int i = 0; i < record.parameters.length; i++) { Integer key = classes.get(record.parameters[i].getName()); out.writeInt(key); } } out.close(); } public static List loadDgmInfo() throws IOException, ClassNotFoundException { ClassLoader loader = DgmMethodRecord.class.getClassLoader(); DataInputStream in = new DataInputStream(new BufferedInputStream(loader.getResourceAsStream("META-INF/dgminfo"))); Map classes = new HashMap(); for (int i = 0; i < PRIMITIVE_CLASSES.length; i++) { classes.put(i, PRIMITIVE_CLASSES[i]); } int skip = 0; for (; ; ) { String name = in.readUTF(); if (name.length() == 0) break; int key = in.readInt(); if (skip++ < PRIMITIVE_CLASSES.length) continue; Class cls = null; try { cls = loader.loadClass(name); } catch (ClassNotFoundException e) { // under certain restrictive environments, loading certain classes may be forbidden // and could yield a ClassNotFoundException (Google App Engine) continue; } classes.put(key, cls); } int size = in.readInt(); List res = new ArrayList(size); for (int i = 0; i != size; ++i) { boolean skipRecord = false; DgmMethodRecord record = new DgmMethodRecord(); record.className = in.readUTF(); record.methodName = in.readUTF(); record.returnType = classes.get(in.readInt()); if (record.returnType == null) { skipRecord = true; } int psize = in.readInt(); record.parameters = new Class[psize]; for (int j = 0; j < record.parameters.length; j++) { record.parameters[j] = classes.get(in.readInt()); if (record.parameters[j] == null) { skipRecord = true; } } if (!skipRecord) { res.add(record); } } in.close(); return res; } } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/CachedClass.java0000644001501200150120000004353611707612046025164 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.*; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.runtime.callsite.CallSiteClassLoader; import org.codehaus.groovy.util.LazyReference; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.util.ReferenceBundle; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; /** * @author Alex.Tkachman */ public class CachedClass { private final Class cachedClass; public ClassInfo classInfo; private static ReferenceBundle softBundle = ReferenceBundle.getSoftBundle(); private final LazyReference fields = new LazyReference(softBundle) { public CachedField[] initValue() { final Field[] declaredFields = (Field[]) AccessController.doPrivileged(new PrivilegedAction/**/() { public /*Field[]*/ Object run() { final Field[] df = getTheClass().getDeclaredFields(); try { AccessibleObject.setAccessible(df, true); } catch (SecurityException e) { // swallow for strict security managers } return df; } }); CachedField [] fields = new CachedField[declaredFields.length]; for (int i = 0; i != fields.length; ++i) fields[i] = new CachedField(declaredFields[i]); return fields; } }; private LazyReference constructors = new LazyReference(softBundle) { public CachedConstructor[] initValue() { final Constructor[] declaredConstructors = (Constructor[]) AccessController.doPrivileged(new PrivilegedAction/**/() { public /*Constructor[]*/ Object run() { return getTheClass().getDeclaredConstructors(); } }); CachedConstructor [] constructors = new CachedConstructor[declaredConstructors.length]; for (int i = 0; i != constructors.length; ++i) constructors[i] = new CachedConstructor(CachedClass.this, declaredConstructors[i]); return constructors; } }; private LazyReference methods = new LazyReference(softBundle) { public CachedMethod[] initValue() { final Method[] declaredMethods = (Method[]) AccessController.doPrivileged(new PrivilegedAction/**/() { public /*Method[]*/ Object run() { final Method[] dm = getTheClass().getDeclaredMethods(); try { AccessibleObject.setAccessible(dm, true); } catch (SecurityException e) { // swallow for strict security managers } return dm; } }); List methods = new ArrayList(declaredMethods.length); List mopMethods = new ArrayList(declaredMethods.length); for (int i = 0; i != declaredMethods.length; ++i) { final CachedMethod cachedMethod = new CachedMethod(CachedClass.this, declaredMethods[i]); final String name = cachedMethod.getName(); if (declaredMethods[i].isBridge() || name.indexOf('+') >= 0) { // Skip Synthetic methods inserted by JDK 1.5 compilers and later continue; } /*else if (Modifier.isAbstract(reflectionMethod.getModifiers())) { continue; }*/ if (name.startsWith("this$") || name.startsWith("super$")) mopMethods.add(cachedMethod); else methods.add(cachedMethod); } CachedMethod [] resMethods = methods.toArray(new CachedMethod[methods.size()]); Arrays.sort(resMethods); final CachedClass superClass = getCachedSuperClass(); if (superClass != null) { superClass.getMethods(); final CachedMethod[] superMopMethods = superClass.mopMethods; for (int i = 0; i != superMopMethods.length; ++i) mopMethods.add(superMopMethods[i]); } CachedClass.this.mopMethods = mopMethods.toArray(new CachedMethod[mopMethods.size()]); Arrays.sort(CachedClass.this.mopMethods, CachedMethodComparatorByName.INSTANCE); return resMethods; } }; private LazyReference cachedSuperClass = new LazyReference(softBundle) { public CachedClass initValue() { if (!isArray) return ReflectionCache.getCachedClass(getTheClass().getSuperclass()); else if (cachedClass.getComponentType().isPrimitive() || cachedClass.getComponentType() == Object.class) return ReflectionCache.OBJECT_CLASS; else return ReflectionCache.OBJECT_ARRAY_CLASS; } }; private final LazyReference callSiteClassLoader = new LazyReference(softBundle) { public CallSiteClassLoader initValue() { return AccessController.doPrivileged(new PrivilegedAction() { public CallSiteClassLoader run() { return new CallSiteClassLoader(CachedClass.this.cachedClass); } }); } }; private final LazyReference> hierarchy = new LazyReference>(softBundle) { public LinkedList initValue() { Set res = new LinkedHashSet (); res.add(classInfo); for (CachedClass iface : getDeclaredInterfaces()) res.addAll(iface.getHierarchy()); final CachedClass superClass = getCachedSuperClass(); if (superClass != null) res.addAll(superClass.getHierarchy()); if (isInterface) res.add(ReflectionCache.OBJECT_CLASS.classInfo); return new LinkedList (res); } }; static final MetaMethod[] EMPTY = new MetaMethod[0]; int hashCode; public CachedMethod [] mopMethods; public static final CachedClass[] EMPTY_ARRAY = new CachedClass[0]; private final LazyReference> declaredInterfaces = new LazyReference> (softBundle) { public Set initValue() { Set res = new HashSet (0); Class[] classes = getTheClass().getInterfaces(); for (Class cls : classes) { res.add(ReflectionCache.getCachedClass(cls)); } return res; } }; private final LazyReference> interfaces = new LazyReference> (softBundle) { public Set initValue() { Set res = new HashSet (0); if (getTheClass().isInterface()) res.add(CachedClass.this); Class[] classes = getTheClass().getInterfaces(); for (Class cls : classes) { final CachedClass aClass = ReflectionCache.getCachedClass(cls); if (!res.contains(aClass)) res.addAll(aClass.getInterfaces()); } final CachedClass superClass = getCachedSuperClass(); if (superClass != null) res.addAll(superClass.getInterfaces()); return res; } }; public final boolean isArray; public final boolean isPrimitive; public final int modifiers; int distance = -1; public final boolean isInterface; public final boolean isNumber; public CachedClass(Class klazz, ClassInfo classInfo) { cachedClass = klazz; this.classInfo = classInfo; isArray = klazz.isArray(); isPrimitive = klazz.isPrimitive(); modifiers = klazz.getModifiers(); isInterface = klazz.isInterface(); isNumber = Number.class.isAssignableFrom(klazz); for (CachedClass inf : getInterfaces()) { ReflectionCache.isAssignableFrom(klazz, inf.cachedClass); } for (CachedClass cur = this; cur != null; cur = cur.getCachedSuperClass()) { ReflectionCache.setAssignableFrom(cur.cachedClass, klazz); } } public CachedClass getCachedSuperClass() { return cachedSuperClass.get(); } public Set getInterfaces() { return interfaces.get(); } public Set getDeclaredInterfaces() { return declaredInterfaces.get(); } public CachedMethod[] getMethods() { return methods.get(); } public CachedField[] getFields() { return fields.get(); } public CachedConstructor[] getConstructors() { return constructors.get(); } public CachedMethod searchMethods(String name, CachedClass[] parameterTypes) { CachedMethod[] methods = getMethods(); CachedMethod res = null; for (CachedMethod m : methods) { if (m.getName().equals(name) && ReflectionCache.arrayContentsEq(parameterTypes, m.getParameterTypes()) && (res == null || res.getReturnType().isAssignableFrom(m.getReturnType()))) res = m; } return res; } public int getModifiers() { return modifiers; } public Object coerceArgument(Object argument) { return argument; } public int getSuperClassDistance() { synchronized (getTheClass()) { if (distance == -1) { int distance = 0; for (Class klazz= getTheClass(); klazz != null; klazz = klazz.getSuperclass()) { distance++; } this.distance = distance; } return distance; } } public int hashCode() { if (hashCode == 0) { hashCode = super.hashCode(); if (hashCode == 0) hashCode = 0xcafebebe; } return hashCode; } public boolean isPrimitive() { return isPrimitive; } public boolean isVoid() { return getTheClass() == void.class; } public boolean isInterface() { return isInterface; } public String getName() { return getTheClass().getName(); } public String getTypeDescription() { return BytecodeHelper.getTypeDescription(getTheClass()); } public final Class getTheClass() { return cachedClass; } public MetaMethod[] getNewMetaMethods() { List arr = new ArrayList(); arr.addAll(Arrays.asList(classInfo.newMetaMethods)); final MetaClass metaClass = classInfo.getStrongMetaClass(); if (metaClass != null && metaClass instanceof ExpandoMetaClass) { arr.addAll(((ExpandoMetaClass)metaClass).getExpandoMethods()); } if (isInterface) { MetaClass mc = ReflectionCache.OBJECT_CLASS.classInfo.getStrongMetaClass(); addSubclassExpandos(arr, mc); } else { for (CachedClass cls = this; cls != null; cls = cls.getCachedSuperClass()) { MetaClass mc = cls.classInfo.getStrongMetaClass(); addSubclassExpandos(arr, mc); } } for (CachedClass inf : getInterfaces()) { MetaClass mc = inf.classInfo.getStrongMetaClass(); addSubclassExpandos(arr, mc); } return arr.toArray(new MetaMethod[arr.size()]); } private void addSubclassExpandos(List arr, MetaClass mc) { if (mc != null && mc instanceof ExpandoMetaClass) { ExpandoMetaClass emc = (ExpandoMetaClass) mc; for (Object mm : emc.getExpandoSubclassMethods()) { if (mm instanceof MetaMethod) { MetaMethod method = (MetaMethod) mm; if (method.getDeclaringClass() == this) arr.add(method); } else { FastArray farr = (FastArray) mm; for (int i = 0; i != farr.size; ++i) { MetaMethod method = (MetaMethod) farr.get(i); if (method.getDeclaringClass() == this) arr.add(method); } } } } } public void setNewMopMethods(List arr) { final MetaClass metaClass = classInfo.getStrongMetaClass(); if (metaClass != null) { if (metaClass.getClass() == MetaClassImpl.class) { classInfo.setStrongMetaClass(null); updateSetNewMopMethods(arr); classInfo.setStrongMetaClass(new MetaClassImpl(metaClass.getTheClass())); return; } if (metaClass.getClass() == ExpandoMetaClass.class) { classInfo.setStrongMetaClass(null); updateSetNewMopMethods(arr); ExpandoMetaClass newEmc = new ExpandoMetaClass(metaClass.getTheClass()); newEmc.initialize(); classInfo.setStrongMetaClass(newEmc); return; } throw new GroovyRuntimeException("Can't add methods to class " + getTheClass().getName() + ". Strong custom meta class already set."); } classInfo.setWeakMetaClass(null); updateSetNewMopMethods(arr); } private void updateSetNewMopMethods(List arr) { if (arr != null) { final MetaMethod[] metaMethods = arr.toArray(new MetaMethod[arr.size()]); classInfo.dgmMetaMethods = metaMethods; classInfo.newMetaMethods = metaMethods; } else classInfo.newMetaMethods = classInfo.dgmMetaMethods; } public void addNewMopMethods(List arr) { final MetaClass metaClass = classInfo.getStrongMetaClass(); if (metaClass != null) { if (metaClass.getClass() == MetaClassImpl.class) { classInfo.setStrongMetaClass(null); updateAddNewMopMethods(arr); classInfo.setStrongMetaClass(new MetaClassImpl(metaClass.getTheClass())); return; } if (metaClass.getClass() == ExpandoMetaClass.class) { ExpandoMetaClass emc = (ExpandoMetaClass)metaClass; classInfo.setStrongMetaClass(null); updateAddNewMopMethods(arr); ExpandoMetaClass newEmc = new ExpandoMetaClass(metaClass.getTheClass()); for (MetaMethod mm : emc.getExpandoMethods()) { newEmc.registerInstanceMethod(mm); } newEmc.initialize(); classInfo.setStrongMetaClass(newEmc); return; } throw new GroovyRuntimeException("Can't add methods to class " + getTheClass().getName() + ". Strong custom meta class already set."); } classInfo.setWeakMetaClass(null); updateAddNewMopMethods(arr); } private void updateAddNewMopMethods(List arr) { List res = new ArrayList(); res.addAll(Arrays.asList(classInfo.newMetaMethods)); res.addAll(arr); classInfo.newMetaMethods = res.toArray(new MetaMethod[res.size()]); } public boolean isAssignableFrom(Class argument) { return argument == null || ReflectionCache.isAssignableFrom(getTheClass(), argument); } public boolean isDirectlyAssignable(Object argument) { return ReflectionCache.isAssignableFrom(getTheClass(), argument.getClass()); } public CallSiteClassLoader getCallSiteLoader() { return callSiteClassLoader.get(); } public Collection getHierarchy() { return hierarchy.get(); } public static class CachedMethodComparatorByName implements Comparator { public static final Comparator INSTANCE = new CachedMethodComparatorByName(); public int compare(Object o1, Object o2) { return ((CachedMethod)o1).getName().compareTo(((CachedMethod)o2).getName()); } } public static class CachedMethodComparatorWithString implements Comparator { public static final Comparator INSTANCE = new CachedMethodComparatorWithString(); public int compare(Object o1, Object o2) { if (o1 instanceof CachedMethod) return ((CachedMethod)o1).getName().compareTo((String)o2); else return ((String)o1).compareTo(((CachedMethod)o2).getName()); } } public String toString() { return cachedClass.toString(); } /** * compatibility method * @return this */ public CachedClass getCachedClass () { return this; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/package.html0000644001501200150120000000025411627206700024430 0ustar miguelmiguel package org.codehaus.groovy.reflection.*

      Internal classes for assisting with reflection.

      groovy-1.8.6/src/main/org/codehaus/groovy/reflection/CachedConstructor.java0000644001501200150120000000764211627206700026437 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.InvokerInvocationException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; /** * @author Alex.Tkachman */ public class CachedConstructor extends ParameterTypes { CachedClass clazz; public final Constructor cachedConstructor; public CachedConstructor(CachedClass clazz, final Constructor c) { this.cachedConstructor = c; this.clazz = clazz; try { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { c.setAccessible(true); return null; } }); } catch (SecurityException e) { // IGNORE } } public CachedConstructor(Constructor c) { this(ReflectionCache.getCachedClass(c.getDeclaringClass()), c); } protected Class[] getPT() { return cachedConstructor.getParameterTypes(); } public static CachedConstructor find(Constructor constructor) { CachedConstructor[] constructors = ReflectionCache.getCachedClass(constructor.getDeclaringClass()).getConstructors(); for (int i = 0; i < constructors.length; i++) { CachedConstructor cachedConstructor = constructors[i]; if (cachedConstructor.cachedConstructor.equals(constructor)) return cachedConstructor; } throw new RuntimeException("Couldn't find method: " + constructor); } public Object doConstructorInvoke(Object[] argumentArray) { argumentArray = coerceArgumentsToClasses(argumentArray); return invoke(argumentArray); } public Object invoke(Object[] argumentArray) { Constructor constr = cachedConstructor; try { return constr.newInstance(argumentArray); } catch (InvocationTargetException e) { throw e.getCause() instanceof RuntimeException ? (RuntimeException)e.getCause() : new InvokerInvocationException(e); } catch (IllegalArgumentException e) { throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, false); } catch (IllegalAccessException e) { throw createExceptionText("could not access constructor: ", constr, argumentArray, e, false); } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException)e; else throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, true); } } private static GroovyRuntimeException createExceptionText(String init, Constructor constructor, Object[] argumentArray, Throwable e, boolean setReason) { throw new GroovyRuntimeException( init + constructor + " with arguments: " + InvokerHelper.toString(argumentArray) + " reason: " + e, setReason ? e : null); } public int getModifiers () { return cachedConstructor.getModifiers(); } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/ClassLoaderForClassArtifacts.java0000644001501200150120000000625611627206700030514 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.codehaus.groovy.runtime.callsite.GroovySunClassLoader; import org.codehaus.groovy.runtime.callsite.CallSite; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Set; import java.util.HashSet; import java.security.AccessController; import java.security.PrivilegedAction; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; public class ClassLoaderForClassArtifacts extends ClassLoader { public final SoftReference klazz; private final Set allocatedNames = new HashSet(); public ClassLoaderForClassArtifacts(Class klazz) { super(klazz.getClassLoader()); this.klazz = new SoftReference (klazz); } public Class define (String name, byte [] bytes) { Class cls = defineClass(name, bytes, 0, bytes.length, klazz.get().getProtectionDomain()); resolveClass(cls); return cls; } public Class loadClass(String name) throws ClassNotFoundException { Class cls = findLoadedClass(name); if (cls != null) return cls; if (GroovySunClassLoader.sunVM != null) { cls = GroovySunClassLoader.sunVM.doesKnow(name); if (cls != null) return cls; } return super.loadClass(name); } public synchronized String createClassName(Method method) { final String name; final String clsName = klazz.get().getName(); if (clsName.startsWith("java.")) name = clsName.replace('.','_') + "$" + method.getName(); else name = clsName + "$" + method.getName(); if (!allocatedNames.contains(name)) { allocatedNames.add(name); return name; } for (int i = 0; ; i++) { String newName = name + "$" + i; if (!allocatedNames.contains(newName)) { allocatedNames.add(newName); return newName; } } } public Constructor defineClassAndGetConstructor(final String name, final byte[] bytes) { final Class cls = AccessController.doPrivileged( new PrivilegedAction(){ public Class run() { return define(name, bytes); } }); if (cls != null) { try { return cls.getConstructor(CallSite.class, MetaClassImpl.class, MetaMethod.class, Class[].class, Constructor.class); } catch (NoSuchMethodException e) { // } } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/CachedField.java0000644001501200150120000000473111627206700025131 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.GroovyRuntimeException; import groovy.lang.MetaProperty; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class CachedField extends MetaProperty { public final Field field; public CachedField(Field field) { super (field.getName(), field.getType()); this.field = field; } public boolean isStatic() { return Modifier.isStatic(getModifiers()); } public boolean isFinal() { return Modifier.isFinal(getModifiers()); } public int getModifiers() { return field.getModifiers(); } /** * @return the property of the given object * @throws RuntimeException if the property could not be evaluated */ public Object getProperty(final Object object) { try { return field.get(object); } catch (IllegalAccessException e) { throw new GroovyRuntimeException("Cannot get the property '" + name + "'.", e); } } /** * Sets the property on the given object to the new value * * @param object on which to set the property * @param newValue the new value of the property * @throws RuntimeException if the property could not be set */ public void setProperty(final Object object, Object newValue) { final Object goalValue = DefaultTypeTransformation.castToType(newValue, field.getType()); if (isFinal()) { throw new GroovyRuntimeException("Cannot set the property '" + name + "' because the backing field is final."); } try { field.set(object, goalValue); } catch (IllegalAccessException ex) { throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", ex); } } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/ClassInfo.java0000644001501200150120000003743511627206700024706 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import groovy.lang.*; import org.codehaus.groovy.reflection.stdclasses.*; import org.codehaus.groovy.util.*; import java.lang.ref.PhantomReference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Handle for all information we want to keep about the class * * @author Alex.Tkachman */ public class ClassInfo extends ManagedConcurrentMap.Entry { private static final Set modifiedExpandos = new HashSet(); private final LazyCachedClassRef cachedClassRef; private final LazyClassLoaderRef artifactClassLoader; private final LockableObject lock = new LockableObject(); public final int hash; private volatile int version; private MetaClass strongMetaClass; private ManagedReference weakMetaClass; MetaMethod[] dgmMetaMethods = CachedClass.EMPTY; MetaMethod[] newMetaMethods = CachedClass.EMPTY; private ManagedConcurrentMap perInstanceMetaClassMap; private static ReferenceBundle softBundle = ReferenceBundle.getSoftBundle(); private static ReferenceBundle weakBundle = ReferenceBundle.getWeakBundle(); private static final ClassInfoSet globalClassSet = new ClassInfoSet(softBundle); ClassInfo(ManagedConcurrentMap.Segment segment, Class klazz, int hash) { super (softBundle, segment, klazz, hash); if (ClassInfo.DebugRef.debug) new DebugRef(klazz); this.hash = hash; cachedClassRef = new LazyCachedClassRef(softBundle, this); artifactClassLoader = new LazyClassLoaderRef(softBundle, this); } public int getVersion() { return version; } public void incVersion() { version++; } public ExpandoMetaClass getModifiedExpando() { return strongMetaClass == null ? null : strongMetaClass instanceof ExpandoMetaClass ? (ExpandoMetaClass)strongMetaClass : null; } public static void clearModifiedExpandos() { for (Iterator it = modifiedExpandos.iterator(); it.hasNext(); ) { ClassInfo info = it.next(); it.remove(); info.setStrongMetaClass(null); } } public CachedClass getCachedClass() { return cachedClassRef.get(); } public ClassLoaderForClassArtifacts getArtifactClassLoader() { return artifactClassLoader.get(); } public static ClassInfo getClassInfo (Class cls) { ThreadLocalMapHandler handler = localMapRef.get(); SoftReference ref=null; if (handler!=null) ref = handler.get(); LocalMap map=null; if (ref!=null) map = ref.get(); if (map!=null) return map.get(cls); return (ClassInfo) globalClassSet.getOrPut(cls,null); } public MetaClass getStrongMetaClass() { return strongMetaClass; } public void setStrongMetaClass(MetaClass answer) { version++; if (strongMetaClass instanceof ExpandoMetaClass) { ((ExpandoMetaClass)strongMetaClass).inRegistry = false; modifiedExpandos.remove(this); } strongMetaClass = answer; if (strongMetaClass instanceof ExpandoMetaClass) { ((ExpandoMetaClass)strongMetaClass).inRegistry = true; modifiedExpandos.add(this); } weakMetaClass = null; } public MetaClass getWeakMetaClass() { return weakMetaClass == null ? null : weakMetaClass.get(); } public void setWeakMetaClass(MetaClass answer) { version++; strongMetaClass = null; if (answer == null) { weakMetaClass = null; } else { weakMetaClass = new ManagedReference (softBundle,answer); } } public MetaClass getMetaClassForClass() { return strongMetaClass != null ? strongMetaClass : weakMetaClass == null ? null : weakMetaClass.get(); } private MetaClass getMetaClassUnderLock() { MetaClass answer = getStrongMetaClass(); if (answer!=null) return answer; answer = getWeakMetaClass(); final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); MetaClassRegistry.MetaClassCreationHandle mccHandle = metaClassRegistry.getMetaClassCreationHandler(); if (answer != null) { boolean enableGloballyOn = (mccHandle instanceof ExpandoMetaClassCreationHandle); boolean cachedAnswerIsEMC = (answer instanceof ExpandoMetaClass); // if EMC.enableGlobally() is OFF, return whatever the cached answer is. // but if EMC.enableGlobally() is ON and the cached answer is not an EMC, come up with a fresh answer if(!enableGloballyOn || cachedAnswerIsEMC) { return answer; } } answer = mccHandle.create(get(), metaClassRegistry); answer.initialize(); if (GroovySystem.isKeepJavaMetaClasses()) { setStrongMetaClass(answer); } else { setWeakMetaClass(answer); } return answer; } public final MetaClass getMetaClass() { MetaClass answer = getMetaClassForClass(); if (answer != null) return answer; lock(); try { return getMetaClassUnderLock(); } finally { unlock(); } } public MetaClass getMetaClass(Object obj) { final MetaClass instanceMetaClass = getPerInstanceMetaClass(obj); if (instanceMetaClass != null) return instanceMetaClass; lock(); try { return getMetaClassUnderLock(); } finally { unlock(); } } public static int size () { return globalClassSet.size(); } public static int fullSize () { return globalClassSet.fullSize(); } public void finalizeRef() { setStrongMetaClass(null); cachedClassRef.clear(); artifactClassLoader.clear(); super.finalizeRef(); } private static CachedClass createCachedClass(Class klazz, ClassInfo classInfo) { if (klazz == Object.class) return new ObjectCachedClass(classInfo); if (klazz == String.class) return new StringCachedClass(classInfo); CachedClass cachedClass; if (Number.class.isAssignableFrom(klazz) || klazz.isPrimitive()) { if (klazz == Number.class) { cachedClass = new NumberCachedClass(klazz, classInfo); } else if (klazz == Integer.class || klazz == Integer.TYPE) { cachedClass = new IntegerCachedClass(klazz, classInfo, klazz==Integer.class); } else if (klazz == Double.class || klazz == Double.TYPE) { cachedClass = new DoubleCachedClass(klazz, classInfo, klazz==Double.class); } else if (klazz == BigDecimal.class) { cachedClass = new BigDecimalCachedClass(klazz, classInfo); } else if (klazz == Long.class || klazz == Long.TYPE) { cachedClass = new LongCachedClass(klazz, classInfo, klazz==Long.class); } else if (klazz == Float.class || klazz == Float.TYPE) { cachedClass = new FloatCachedClass(klazz, classInfo, klazz==Float.class); } else if (klazz == Short.class || klazz == Short.TYPE) { cachedClass = new ShortCachedClass(klazz, classInfo, klazz==Short.class); } else if (klazz == Boolean.TYPE) { cachedClass = new BooleanCachedClass(klazz, classInfo, false); } else if (klazz == Character.TYPE) { cachedClass = new CharacterCachedClass(klazz, classInfo, false); } else if (klazz == BigInteger.class) { cachedClass = new BigIntegerCachedClass(klazz, classInfo); } else if (klazz == Byte.class || klazz == Byte.TYPE) { cachedClass = new ByteCachedClass(klazz, classInfo, klazz==Byte.class); } else { cachedClass = new CachedClass(klazz, classInfo); } } else { if (klazz.getName().charAt(0) == '[') cachedClass = new ArrayCachedClass(klazz, classInfo); else if (klazz == Boolean.class) { cachedClass = new BooleanCachedClass(klazz, classInfo, true); } else if (klazz == Character.class) { cachedClass = new CharacterCachedClass(klazz, classInfo, true); } else if (Closure.class.isAssignableFrom(klazz)) { cachedClass = new CachedClosureClass (klazz, classInfo); } else { cachedClass = new CachedClass(klazz, classInfo); } } return cachedClass; } public void lock () { lock.lock(); } public void unlock () { lock.unlock(); } public MetaClass getPerInstanceMetaClass(Object obj) { if (perInstanceMetaClassMap == null) return null; return (MetaClass) perInstanceMetaClassMap.get(obj); } public void setPerInstanceMetaClass(Object obj, MetaClass metaClass) { version++; if (metaClass != null) { if (perInstanceMetaClassMap == null) perInstanceMetaClassMap = new ManagedConcurrentMap(ReferenceBundle.getWeakBundle()); perInstanceMetaClassMap.put(obj, metaClass); } else { if (perInstanceMetaClassMap != null) { perInstanceMetaClassMap.remove(obj); } } } public boolean hasPerInstanceMetaClasses () { return perInstanceMetaClassMap != null; } public static class ClassInfoSet extends ManagedConcurrentMap { public ClassInfoSet(ReferenceBundle bundle) { super(bundle); } protected Segment createSegment(Object segmentInfo, int cap) { ReferenceBundle bundle = (ReferenceBundle) segmentInfo; if (bundle==null) throw new IllegalArgumentException("bundle must not be null "); return new Segment(bundle, cap); } static final class Segment extends ManagedConcurrentMap.Segment { Segment(ReferenceBundle bundle, int initialCapacity) { super(bundle, initialCapacity); } protected ClassInfo createEntry(Class key, int hash, ClassInfo unused) { return new ClassInfo(this, key, hash); } } } private static final class LocalMap extends HashMap { private static final int CACHE_SIZE = 5; // We use a PhantomReference or a WeakReference for the Thread // because the ThreadLocal manages a map with the thread as key. // If we make a strong reference to the thread here, then it is // possible, that the map cannot be cleaned. If the number of // threads is not limited, then this map may consume too much memory // This reference here is unmanaged (queue==null) because if the map // key gets collected, the reference will too. private final PhantomReference myThread = new PhantomReference(Thread.currentThread(),null); private int nextCacheEntry; private final ClassInfo[] cache = new ClassInfo[CACHE_SIZE]; private static final ClassInfo NOINFO = new ClassInfo(null,null,0); private LocalMap() { for (int i = 0; i < cache.length; i++) { cache[i] = NOINFO; } } public ClassInfo get(Class key) { ClassInfo info = getFromCache(key); if (info != null) return info; info = super.get(key); if (info != null) return putToCache(info); return putToCache((ClassInfo) globalClassSet.getOrPut(key,null)); } private ClassInfo getFromCache (Class klazz) { for (int i = 0, k = nextCacheEntry-1; i < cache.length; i++, k--) { if (k < 0) k += CACHE_SIZE; final ClassInfo info = cache[k]; if (klazz == info.get()) { nextCacheEntry = k+1; if (nextCacheEntry == CACHE_SIZE) nextCacheEntry = 0; return info; } } return null; } private ClassInfo putToCache (ClassInfo classInfo) { cache [nextCacheEntry++] = classInfo; if (nextCacheEntry == CACHE_SIZE) nextCacheEntry = 0; return classInfo; } } private static class ThreadLocalMapHandler extends ThreadLocal> { SoftReference recentThreadMapRef; protected SoftReference initialValue() { return new SoftReference(new LocalMap(),null); } public SoftReference get() { SoftReference mapRef = recentThreadMapRef; LocalMap recent = null; if (mapRef!=null) recent = mapRef.get(); // we don't need to handle myThread.get()==null, because in that // case the thread has been collected, meaning the entry for the // thread is invalid anyway, so it is valid if recent has a // different value. if (recent != null && recent.myThread.get() == Thread.currentThread()) { return mapRef; } else { SoftReference ref = super.get(); recentThreadMapRef = ref; return ref; } } } private static final WeakReference localMapRef; static { ThreadLocalMapHandler localMap = new ThreadLocalMapHandler(); localMapRef = new WeakReference(localMap,null); } private static class LazyCachedClassRef extends LazyReference { private final ClassInfo info; LazyCachedClassRef(ReferenceBundle bundle, ClassInfo info) { super(bundle); this.info = info; } public CachedClass initValue() { return createCachedClass(info.get(), info); } } private static class LazyClassLoaderRef extends LazyReference { private final ClassInfo info; LazyClassLoaderRef(ReferenceBundle bundle, ClassInfo info) { super(bundle); this.info = info; } public ClassLoaderForClassArtifacts initValue() { return new ClassLoaderForClassArtifacts(info.get()); } } private static class DebugRef extends ManagedReference { public static final boolean debug = false; private static final AtomicInteger count = new AtomicInteger(); final String name; public DebugRef(Class klazz) { super(softBundle, klazz); name = klazz == null ? "" : klazz.getName(); count.incrementAndGet(); } public void finalizeRef() { System.out.println(name + " unloaded " + count.decrementAndGet() + " classes kept"); super.finalizeReference(); } } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/MethodHandleFactory.java0000644001501200150120000002635311715031256026706 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.MethodVisitor; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Constructor; /** * his class is unused and will be removed in Groovy 1.9 */ @Deprecated public class MethodHandleFactory implements Opcodes{ @Deprecated public static MethodHandle unreflect (Method method) { if (SunClassLoader.sunVM != null || checkAccessable(method)) { return createCompiledMethodHandle (method, ClassInfo.getClassInfo(method.getDeclaringClass()).getArtifactClassLoader()); } return new ReflectiveMethodHandle(method); } private static boolean checkAccessable(Method method) { if (!Modifier.isPublic(method.getDeclaringClass().getModifiers())) return false; if (!Modifier.isPublic(method.getModifiers())) return false; for (Class paramType : method.getParameterTypes()) if (!Modifier.isPublic(paramType.getModifiers())) return false; return true; } @Deprecated public static void genLoadParameters(int argumentIndex, MethodVisitor mv, Method method) { Class[] parameters = method.getParameterTypes(); int size = parameters.length; for (int i = 0; i < size; i++) { // unpack argument from Object[] mv.visitVarInsn(Opcodes.ALOAD, argumentIndex); BytecodeHelper.pushConstant(mv, i); mv.visitInsn(Opcodes.AALOAD); // cast argument to parameter class, inclusive unboxing // for methods with primitive types BytecodeHelper.doCast(mv, parameters[i]); } } @Deprecated public static void genLoadParametersDirect(int argumentIndex, MethodVisitor mv, Method method) { Class[] parameters = method.getParameterTypes(); int size = parameters.length; for (int i = 0; i < size; i++) { mv.visitVarInsn(Opcodes.ALOAD, argumentIndex+i); // cast argument to parameter class, inclusive unboxing // for methods with primitive types BytecodeHelper.doCast(mv, parameters[i]); } } @Deprecated public static void genLoadParametersPrimitiveDirect(int argumentIndex, MethodVisitor mv, Method method) { Class[] parameters = method.getParameterTypes(); int size = parameters.length; int idx = 0; for (int i = 0; i < size; i++, idx++) { Class type = parameters[i]; if (type == double.class) { mv.visitVarInsn(DLOAD, idx++); } else if (type == float.class) { mv.visitVarInsn(FLOAD, idx); } else if (type == long.class) { mv.visitVarInsn(LLOAD, idx++); } else if ( type == boolean.class || type == char.class || type == byte.class || type == int.class || type == short.class) { mv.visitVarInsn(ILOAD, idx); } else { mv.visitVarInsn(ALOAD, idx); BytecodeHelper.doCast(mv, type); } } } @Deprecated private static class ReflectiveMethodHandle extends MethodHandle { private final Method method; public ReflectiveMethodHandle(Method method) { this.method = method; method.setAccessible(true); } public Object invoke (Object receiver, Object [] args) throws Throwable{ return method.invoke(receiver, args); } } private static MethodHandle createCompiledMethodHandle(Method method, ClassLoaderForClassArtifacts loader) { try { Constructor c = compileMethodHandle(method, loader); if (c != null) return (MethodHandle) c.newInstance(); } catch (Throwable e) { // } return new ReflectiveMethodHandle(method); } private static Constructor compileMethodHandle(Method cachedMethod, ClassLoaderForClassArtifacts loader) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final String name = loader.createClassName(cachedMethod); final byte[] bytes = genMethodHandle(cachedMethod, cw, name); return loader.defineClassAndGetConstructor(name, bytes); } private static byte[] genMethodHandle(Method method, ClassWriter cw, String name) { cw.visit(Opcodes.V1_4, Opcodes.ACC_PUBLIC, name.replace('.','/'), null, "org/codehaus/groovy/reflection/MethodHandle", null); genConstructor(cw, "org/codehaus/groovy/reflection/MethodHandle"); genInvokeXxxWithArray(cw, method); genInvokeWithFixedParams(cw, method); genInvokeWithFixedPrimitiveParams(cw, method); cw.visitEnd(); return cw.toByteArray(); } private static void genConstructor(ClassWriter cw, final String superClass) { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass, "", "()V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } @Deprecated public static void genInvokeXxxWithArray(ClassWriter cw, Method method) { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, EXCEPTIONS); mv.visitCode(); Class callClass = method.getDeclaringClass(); boolean useInterface = callClass.isInterface(); String type = BytecodeHelper.getClassInternalName(callClass.getName()); String descriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()); // make call if (Modifier.isStatic(method.getModifiers())) { genLoadParameters(2, mv, method); mv.visitMethodInsn(Opcodes.INVOKESTATIC, type, method.getName(), descriptor); } else { mv.visitVarInsn(Opcodes.ALOAD, 1); BytecodeHelper.doCast(mv, callClass); genLoadParameters(2, mv, method); mv.visitMethodInsn((useInterface) ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, type, method.getName(), descriptor); } BytecodeHelper.box(mv, method.getReturnType()); if (method.getReturnType() == void.class) { mv.visitInsn(Opcodes.ACONST_NULL); } mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private static void genInvokeWithFixedParams(ClassWriter cw, Method method) { MethodVisitor mv; final int pc = method.getParameterTypes().length; if (pc <= 4) { StringBuilder pdescb = new StringBuilder(); for (int i = 0; i != pc; ++i) pdescb.append("Ljava/lang/Object;"); String pdesc = pdescb.toString(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", "(Ljava/lang/Object;" + pdesc + ")Ljava/lang/Object;", null, EXCEPTIONS); mv.visitCode(); Class callClass = method.getDeclaringClass(); boolean useInterface = callClass.isInterface(); String type = BytecodeHelper.getClassInternalName(callClass.getName()); String descriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()); // make call if (Modifier.isStatic(method.getModifiers())) { MethodHandleFactory.genLoadParametersDirect(2, mv, method); mv.visitMethodInsn(Opcodes.INVOKESTATIC, type, method.getName(), descriptor); } else { mv.visitVarInsn(Opcodes.ALOAD, 1); BytecodeHelper.doCast(mv, callClass); MethodHandleFactory.genLoadParametersDirect(2, mv, method); mv.visitMethodInsn((useInterface) ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, type, method.getName(), descriptor); } BytecodeHelper.box(mv, method.getReturnType()); if (method.getReturnType() == void.class) { mv.visitInsn(Opcodes.ACONST_NULL); } mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } private static void genInvokeWithFixedPrimitiveParams(ClassWriter cw, Method method) { MethodVisitor mv; final Class[] pt = method.getParameterTypes(); final int pc = pt.length; if (pc > 0 && pc <= 3) { StringBuilder pdescb = new StringBuilder(); boolean hasPrimitive = false; for (int i = 0; i != pc; ++i) if (pt[i].isPrimitive()) { hasPrimitive = true; pdescb.append(BytecodeHelper.getTypeDescription(pt[i])); } else pdescb.append("Ljava/lang/Object;"); if (!hasPrimitive) return; String pdesc = pdescb.toString(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", "(Ljava/lang/Object;" + pdesc + ")Ljava/lang/Object;", null, EXCEPTIONS); mv.visitCode(); Class callClass = method.getDeclaringClass(); boolean useInterface = callClass.isInterface(); String type = BytecodeHelper.getClassInternalName(callClass.getName()); String descriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()); // make call if (Modifier.isStatic(method.getModifiers())) { MethodHandleFactory.genLoadParametersPrimitiveDirect(2, mv, method); mv.visitMethodInsn(Opcodes.INVOKESTATIC, type, method.getName(), descriptor); } else { mv.visitVarInsn(Opcodes.ALOAD, 1); BytecodeHelper.doCast(mv, callClass); MethodHandleFactory.genLoadParametersPrimitiveDirect(2, mv, method); mv.visitMethodInsn((useInterface) ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, type, method.getName(), descriptor); } BytecodeHelper.box(mv, method.getReturnType()); if (method.getReturnType() == void.class) { mv.visitInsn(Opcodes.ACONST_NULL); } mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } private static final String[] EXCEPTIONS = new String[] { "java/lang/Throwable" }; } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/0000755001501200150120000000000011645141222024313 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/LongCachedClass.java0000644001501200150120000000367711627206700030153 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class LongCachedClass extends NumberCachedClass { private boolean allowNull; public LongCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public Object coerceArgument(Object argument) { if (argument instanceof Long) { return argument; } if (argument instanceof Number) { return ((Number) argument).longValue(); } return argument; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Long; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Integer.TYPE || classToTransformFrom == Long.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/DoubleCachedClass.java0000644001501200150120000000546711645141222030462 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigDecimal; import java.math.BigInteger; /** * @author Alex.Tkachman */ public class DoubleCachedClass extends NumberCachedClass { // Double, double private boolean allowNull; public DoubleCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Double; } public Object coerceArgument(Object argument) { if (argument instanceof Double) { return argument; } if (argument instanceof Number) { Double res = ((Number) argument).doubleValue(); if (argument instanceof BigDecimal && res.isInfinite()) { throw new IllegalArgumentException(Double.class + " out of range while converting from BigDecimal"); } return res; } return argument; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Double.class || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Float.class || classToTransformFrom == Double.TYPE || classToTransformFrom == Integer.TYPE || classToTransformFrom == Long.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE || classToTransformFrom == Float.TYPE || classToTransformFrom == BigDecimal.class || classToTransformFrom == BigInteger.class || (classToTransformFrom!=null && BigDecimal.class.isAssignableFrom(classToTransformFrom)) || (classToTransformFrom!=null && BigInteger.class.isAssignableFrom(classToTransformFrom)) ; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/BooleanCachedClass.java0000644001501200150120000000264511627206700030625 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class BooleanCachedClass extends CachedClass { private boolean allowNull; public BooleanCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Boolean; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Boolean.class || classToTransformFrom == Boolean.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java0000644001501200150120000000253111627206700031220 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigDecimal; /** * @author Alex.Tkachman */ public class BigDecimalCachedClass extends DoubleCachedClass { public BigDecimalCachedClass(Class klazz, ClassInfo classInfo) { super(klazz, classInfo, true); } public boolean isDirectlyAssignable(Object argument) { return argument instanceof BigDecimal; } public Object coerceArgument(Object argument) { if (argument instanceof BigDecimal) { return argument; } if (argument instanceof Number) { return new BigDecimal(((Number) argument).doubleValue()); } return argument; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/ObjectCachedClass.java0000644001501200150120000000215011627206700030443 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class ObjectCachedClass extends CachedClass { public ObjectCachedClass(ClassInfo classInfo) { super(Object.class,classInfo); } public synchronized CachedClass getCachedSuperClass() { return null; } public boolean isAssignableFrom(Class argument) { return true; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/IntegerCachedClass.java0000644001501200150120000000371111627206700030636 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigInteger; /** * @author Alex.Tkachman */ public class IntegerCachedClass extends NumberCachedClass { // int, Integer private boolean allowNull; public IntegerCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public Object coerceArgument(Object argument) { if (argument instanceof Integer) { return argument; } if (argument instanceof Number) { return ((Number) argument).intValue(); } return argument; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Integer; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Integer.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == BigInteger.class || classToTransformFrom == Integer.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/ByteCachedClass.java0000644001501200150120000000315411627206700030145 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class ByteCachedClass extends NumberCachedClass { private boolean allowNull; public ByteCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public Object coerceArgument(Object argument) { if (argument instanceof Byte) { return argument; } if (argument instanceof Number) { return ((Number) argument).byteValue(); } return argument; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Byte; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Byte.class || classToTransformFrom == Byte.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/NumberCachedClass.java0000644001501200150120000000401311627206700030465 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigInteger; /** * @author Alex.Tkachman */ public class NumberCachedClass extends CachedClass { public NumberCachedClass(Class klazz, ClassInfo classInfo) { super(klazz, classInfo); } public Object coerceArgument(Object argument) { if (argument instanceof Number) { return coerceNumber(argument); } return argument; } public boolean isAssignableFrom(Class classToTransformFrom) { return classToTransformFrom == null || Number.class.isAssignableFrom(classToTransformFrom) || classToTransformFrom == Byte.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Integer.TYPE || classToTransformFrom == Long.TYPE || classToTransformFrom == Float.TYPE || classToTransformFrom == Double.TYPE ; } private Object coerceNumber(Object argument) { Class param = getTheClass(); if (param == Byte.class /*|| param == Byte.TYPE*/) { argument = new Byte(((Number) argument).byteValue()); } else if (param == BigInteger.class) { argument = new BigInteger(String.valueOf((Number) argument)); } return argument; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/CachedClosureClass.java0000644001501200150120000000406611627206700030661 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.reflection.CachedMethod; public class CachedClosureClass extends CachedClass { private final Class[] parameterTypes; private final int maximumNumberOfParameters; public CachedClosureClass(Class klazz, ClassInfo classInfo) { super(klazz, classInfo); CachedMethod methods [] = getMethods(); // set it to -1 for starters so parameterTypes will always get a type int maximumNumberOfParameters = -1; Class[] parameterTypes = null; for (CachedMethod method : methods) { if ("doCall".equals(method.getName())) { final Class[] pt = method.getNativeParameterTypes(); if (pt.length > maximumNumberOfParameters) { parameterTypes = pt; maximumNumberOfParameters = parameterTypes.length; } } } // this line should be useless, but well, just in case maximumNumberOfParameters = Math.max(maximumNumberOfParameters,0); this.maximumNumberOfParameters = maximumNumberOfParameters; this.parameterTypes = parameterTypes; } public Class[] getParameterTypes() { return parameterTypes; } public int getMaximumNumberOfParameters() { return maximumNumberOfParameters; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.java0000644001501200150120000000402011627206700030311 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import groovy.lang.GString; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; /** * @author Alex.Tkachman */ public class ArrayCachedClass extends CachedClass { public ArrayCachedClass(Class klazz, ClassInfo classInfo) { super(klazz, classInfo); } public Object coerceArgument(Object argument) { Class argumentClass = argument.getClass(); if (argumentClass.getName().charAt(0) != '[') return argument; Class argumentComponent = argumentClass.getComponentType(); Class paramComponent = getTheClass().getComponentType(); if (paramComponent.isPrimitive()) { argument = DefaultTypeTransformation.convertToPrimitiveArray(argument, paramComponent); } else if (paramComponent == String.class && argument instanceof GString[]) { GString[] strings = (GString[]) argument; String[] ret = new String[strings.length]; for (int i = 0; i < strings.length; i++) { ret[i] = strings[i].toString(); } argument = ret; } else if (paramComponent==Object.class && argumentComponent.isPrimitive()){ argument = DefaultTypeTransformation.primitiveArrayBox(argument); } return argument; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/ShortCachedClass.java0000644001501200150120000000334711627206700030345 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class ShortCachedClass extends NumberCachedClass { private boolean allowNull; public ShortCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public Object coerceArgument(Object argument) { if (argument instanceof Short) { return argument; } if (argument instanceof Number) { return ((Number) argument).shortValue(); } return argument; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Short; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/FloatCachedClass.java0000644001501200150120000000471011627206700030306 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigDecimal; import java.math.BigInteger; /** * @author Alex.Tkachman */ public class FloatCachedClass extends NumberCachedClass { private boolean allowNull; public FloatCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public Object coerceArgument(Object argument) { if (argument instanceof Float) { return argument; } if (argument instanceof Number) { Float res = ((Number) argument).floatValue(); if (argument instanceof BigDecimal && res.isInfinite()) { throw new IllegalArgumentException(Float.class + " out of range while converting from BigDecimal"); } return res; } return argument; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Float; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Float.class || classToTransformFrom == Integer.class || classToTransformFrom == Long.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == Float.TYPE || classToTransformFrom == Integer.TYPE || classToTransformFrom == Long.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE || classToTransformFrom == BigDecimal.class || classToTransformFrom == BigInteger.class; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/CharacterCachedClass.java0000644001501200150120000000265711627206700031145 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; /** * @author Alex.Tkachman */ public class CharacterCachedClass extends CachedClass { private boolean allowNull; public CharacterCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) { super(klazz, classInfo); this.allowNull = allowNull; } public boolean isDirectlyAssignable(Object argument) { return (allowNull && argument == null) || argument instanceof Character; } public boolean isAssignableFrom(Class classToTransformFrom) { return (allowNull && classToTransformFrom == null) || classToTransformFrom == Character.class || classToTransformFrom == Character.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/BigIntegerCachedClass.java0000644001501200150120000000316111627206700031257 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import org.codehaus.groovy.reflection.ClassInfo; import java.math.BigInteger; /** * @author Alex.Tkachman */ public class BigIntegerCachedClass extends NumberCachedClass { public BigIntegerCachedClass(Class klazz, ClassInfo classInfo) { super(klazz, classInfo); } public boolean isDirectlyAssignable(Object argument) { return argument instanceof BigInteger; } public boolean isAssignableFrom(Class classToTransformFrom) { return classToTransformFrom == null || classToTransformFrom == Integer.class || classToTransformFrom == Short.class || classToTransformFrom == Byte.class || classToTransformFrom == BigInteger.class || classToTransformFrom == Long.class || classToTransformFrom == Integer.TYPE || classToTransformFrom == Short.TYPE || classToTransformFrom == Byte.TYPE || classToTransformFrom == Long.TYPE; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/stdclasses/StringCachedClass.java0000644001501200150120000000320511627206700030505 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection.stdclasses; import groovy.lang.GString; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.reflection.ReflectionCache; /** * @author Alex.Tkachman */ public class StringCachedClass extends CachedClass { private static final Class STRING_CLASS = String.class; private static final Class GSTRING_CLASS = GString.class; public StringCachedClass(ClassInfo classInfo) { super(STRING_CLASS, classInfo); } public boolean isDirectlyAssignable(Object argument) { return argument instanceof String; } public boolean isAssignableFrom(Class classToTransformFrom) { return classToTransformFrom == null || classToTransformFrom == STRING_CLASS || ReflectionCache.isAssignableFrom(GSTRING_CLASS,classToTransformFrom); } public Object coerceArgument(Object argument) { return argument instanceof GString ? argument.toString() : argument; } } groovy-1.8.6/src/main/org/codehaus/groovy/reflection/ReflectionCache.java0000644001501200150120000000751011627206700026032 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.reflection; import org.codehaus.groovy.util.TripleKeyHashMap; import java.util.HashMap; import java.util.Map; public class ReflectionCache { private static Map primitiveTypesMap = new HashMap(); static { primitiveTypesMap.put(byte.class, Byte.class); primitiveTypesMap.put(boolean.class, Boolean.class); primitiveTypesMap.put(char.class, Character.class); primitiveTypesMap.put(double.class, Double.class); primitiveTypesMap.put(float.class, Float.class); primitiveTypesMap.put(int.class, Integer.class); primitiveTypesMap.put(long.class, Long.class); primitiveTypesMap.put(short.class, Short.class); } public static Class autoboxType(Class type) { final Class res = (Class) primitiveTypesMap.get(type); return res == null ? type : res; } static TripleKeyHashMap mopNames = new TripleKeyHashMap(); public static String getMOPMethodName(CachedClass declaringClass, String name, boolean useThis) { TripleKeyHashMap.Entry mopNameEntry = mopNames.getOrPut(declaringClass, name, Boolean.valueOf(useThis)); if (mopNameEntry.value == null) { mopNameEntry.value = new StringBuffer().append(useThis ? "this$" : "super$").append(declaringClass.getSuperClassDistance()).append("$").append(name).toString(); } return (String) mopNameEntry.value; } static final CachedClass STRING_CLASS = getCachedClass(String.class); public static boolean isArray(Class klazz) { return klazz.getName().charAt(0) == '['; } static void setAssignableFrom(Class klazz, Class aClass) { // SoftDoubleKeyMap.Entry val = (SoftDoubleKeyMap.Entry) assignableMap.getOrPut(klazz, aClass, null); // if (val.getValue() == null) { // val.setValue(Boolean.TRUE); // } } public static boolean isAssignableFrom(Class klazz, Class aClass) { if (klazz == aClass) return true; // SoftDoubleKeyMap.Entry val = (SoftDoubleKeyMap.Entry) assignableMap.getOrPut(klazz, aClass, null); // if (val.getValue() == null) { // val.setValue(Boolean.valueOf(klazz.isAssignableFrom(aClass))); // } // return ((Boolean)val.getValue()).booleanValue(); return klazz.isAssignableFrom(aClass); } static boolean arrayContentsEq(Object[] a1, Object[] a2) { if (a1 == null) { return a2 == null || a2.length == 0; } if (a2 == null) { return a1.length == 0; } if (a1.length != a2.length) { return false; } for (int i = 0; i < a1.length; i++) { if (a1[i] != a2[i]) { return false; } } return true; } public static final CachedClass OBJECT_CLASS = getCachedClass(Object.class); public static final CachedClass OBJECT_ARRAY_CLASS = getCachedClass(Object[].class); public static CachedClass getCachedClass(Class klazz) { if (klazz == null) return null; return ClassInfo.getClassInfo(klazz).getCachedClass (); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/0000755001501200150120000000000011715031256021154 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/ErrorReporter.java0000644001501200150120000001237311627206700024641 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.io.PrintStream; import java.io.PrintWriter; import org.codehaus.groovy.GroovyExceptionInterface; import org.codehaus.groovy.control.CompilationFailedException; import groovy.lang.GroovyRuntimeException; /** * Provides services for reporting compilation errors to the * user. Primary entry point is write(). * * @author Chris Poirier * @version $Revision$ */ public class ErrorReporter { private Throwable base = null; // The exception on which to report private boolean debug = false; // If true, stack traces are always output private Object output = null; // The stream/writer to which to output /** * Configures a new Reporter. Default mode is not to report a stack trace unless * the error was not of one of the supported types. * * @param e the exception on which to report */ public ErrorReporter( Throwable e ) { this.base = e; } /** * Configures a new Reporter. * * @param e the exception on which to report * @param debug if set, stack traces will be output for all reports */ public ErrorReporter( Throwable e, boolean debug ) { this.base = e; this.debug = debug; } /** * Writes the error to the specified PrintStream. */ public void write( PrintStream stream ) { this.output = stream; dispatch( base, false ); stream.flush(); } /** * Writes the error to the specified PrintWriter. */ public void write( PrintWriter writer ) { this.output = writer; dispatch( base, false ); writer.flush(); } /** * Runs the report once all initialization is complete. */ protected void dispatch( Throwable object, boolean child ) { if( object instanceof CompilationFailedException ) { report( (CompilationFailedException)object, child ); } else if( object instanceof GroovyExceptionInterface ) { report( (GroovyExceptionInterface)object, child ); } else if( object instanceof GroovyRuntimeException ) { report( (GroovyRuntimeException)object, child ); } else if( object instanceof Exception ) { report( (Exception)object, child ); } else { report( object, child ); } } //--------------------------------------------------------------------------- // REPORTING ROUTINES /** * For CompilationFailedException. */ protected void report( CompilationFailedException e, boolean child ) { println( e.toString() ); stacktrace( e, false ); } /** * For GroovyException. */ protected void report( GroovyExceptionInterface e, boolean child ) { println( ((Exception)e).getMessage() ); stacktrace( (Exception)e, false ); } /** * For Exception. */ protected void report( Exception e, boolean child ) { println( e.getMessage() ); stacktrace( e, false ); } /** * For everything else. */ protected void report( Throwable e, boolean child ) { println( ">>> a serious error occurred: " + e.getMessage() ); stacktrace( e, true ); } //--------------------------------------------------------------------------- // GENERAL SUPPORT ROUTINES /** * Prints a line to the underlying PrintStream */ protected void println( String line ) { if( output instanceof PrintStream ) { ((PrintStream)output).println( line ); } else { ((PrintWriter)output).println( line ); } } protected void println( StringBuffer line ) { if( output instanceof PrintStream ) { ((PrintStream)output).println( line ); } else { ((PrintWriter)output).println( line ); } } /** * Displays an exception's stack trace, if debug or * always. */ protected void stacktrace( Throwable e, boolean always ) { if( debug || always ) { println( ">>> stacktrace:" ); if( output instanceof PrintStream ) { e.printStackTrace( (PrintStream)output ); } else { e.printStackTrace( (PrintWriter)output ); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/FileSystemCompiler.java0000644001501200150120000003365211715031256025607 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import groovy.lang.GroovyResourceLoader; import org.apache.commons.cli.*; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.ConfigurationException; import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit; import groovy.lang.GroovySystem; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; /** * Command-line compiler (aka. groovyc). * * @version $Id$ */ public class FileSystemCompiler { private final CompilationUnit unit; public FileSystemCompiler(CompilerConfiguration configuration) throws ConfigurationException { this(configuration, null); } public FileSystemCompiler(CompilerConfiguration configuration, CompilationUnit cu) throws ConfigurationException { if (cu != null) { unit = cu; } else if (configuration.getJointCompilationOptions() != null) { unit = new JavaAwareCompilationUnit(configuration); } else { unit = new CompilationUnit(configuration); } } public void compile(String[] paths) throws Exception { unit.addSources(paths); unit.compile(); } public void compile(File[] files) throws Exception { unit.addSources(files); unit.compile(); } public static void displayHelp(final Options options) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(80, "groovyc [options] ", "options:", options, ""); } public static void displayVersion() { String version = GroovySystem.getVersion(); System.err.println("Groovy compiler version " + version); System.err.println("Copyright 2003-2011 The Codehaus. http://groovy.codehaus.org/"); System.err.println(""); } public static int checkFiles(String[] filenames) { int errors = 0; for (String filename : filenames) { File file = new File(filename); if (!file.exists()) { System.err.println("error: file not found: " + file); ++errors; } else if (!file.canRead()) { System.err.println("error: file not readable: " + file); ++errors; } } return errors; } public static boolean validateFiles(String[] filenames) { return checkFiles(filenames) == 0; } private static boolean displayStackTraceOnError = false; /** * Same as main(args) except that exceptions are thrown out instead of causing * the VM to exit. */ public static void commandLineCompile(String[] args) throws Exception { commandLineCompile(args, true); } /** * Same as main(args) except that exceptions are thrown out instead of causing * the VM to exit and the lookup for .groovy files can be controlled */ public static void commandLineCompile(String[] args, boolean lookupUnnamedFiles) throws Exception { Options options = createCompilationOptions(); PosixParser cliParser = new PosixParser(); CommandLine cli; cli = cliParser.parse(options, args); if (cli.hasOption('h')) { displayHelp(options); return; } if (cli.hasOption('v')) { displayVersion(); return; } displayStackTraceOnError = cli.hasOption('e'); CompilerConfiguration configuration = generateCompilerConfigurationFromOptions(cli); // // Load the file name list String[] filenames = generateFileNamesFromOptions(cli); boolean fileNameErrors = filenames == null; if (!fileNameErrors && (filenames.length == 0)) { displayHelp(options); return; } fileNameErrors = fileNameErrors && !validateFiles(filenames); if (!fileNameErrors) { doCompilation(configuration, null, filenames, lookupUnnamedFiles); } } /** * Primary entry point for compiling from the command line * (using the groovyc script). * * If calling inside a process and you don't want the JVM to exit on an * error call commandLineCompile(String[]), which this method simply wraps * * @param args command line arguments */ public static void main(String[] args) { commandLineCompileWithErrorHandling(args,true); } /** * Primary entry point for compiling from the command line * (using the groovyc script). * * If calling inside a process and you don't want the JVM to exit on an * error call commandLineCompile(String[]), which this method simply wraps * * @param args command line arguments * @param lookupUnnamedFiles do a lookup for .groovy files not part of * the given list of files to compile */ public static void commandLineCompileWithErrorHandling(String[] args, boolean lookupUnnamedFiles) { try { commandLineCompile(args, lookupUnnamedFiles); } catch( Throwable e ) { new ErrorReporter( e, displayStackTraceOnError).write( System.err ); System.exit(1); } } public static void doCompilation(CompilerConfiguration configuration, CompilationUnit unit, String[] filenames) throws Exception { doCompilation(configuration, unit, filenames, true); } public static void doCompilation(CompilerConfiguration configuration, CompilationUnit unit, String[] filenames, boolean lookupUnnamedFiles) throws Exception { File tmpDir = null; // if there are any joint compilation options set stubDir if not set try { if ((configuration.getJointCompilationOptions() != null) && !configuration.getJointCompilationOptions().containsKey("stubDir")) { tmpDir = createTempDir(); configuration.getJointCompilationOptions().put("stubDir", tmpDir); } FileSystemCompiler compiler = new FileSystemCompiler(configuration, unit); if (lookupUnnamedFiles) { for (String filename : filenames) { File file = new File(filename); if (file.isFile()) { URL url = file.getAbsoluteFile().getParentFile().toURI().toURL(); compiler.unit.getClassLoader().addURL(url); } } } else { compiler.unit.getClassLoader().setResourceLoader(new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return null; } }); } compiler.compile(filenames); } finally { try { if (tmpDir != null) deleteRecursive(tmpDir); } catch (Throwable t) { System.err.println("error: could not delete temp files - " + tmpDir.getPath()); } } } public static String[] generateFileNamesFromOptions(CommandLine cli) { String[] filenames = cli.getArgs(); List fileList = new ArrayList(filenames.length); boolean errors = false; for (String filename : filenames) { if (filename.startsWith("@")) { try { BufferedReader br = new BufferedReader(new FileReader(filename.substring(1))); String file; while ((file = br.readLine()) != null) { fileList.add(file); } } catch (IOException ioe) { System.err.println("error: file not readable: " + filename.substring(1)); errors = true; } } else { fileList.add(filename); } } if (errors) { return null; } else { return fileList.toArray(new String[fileList.size()]); } } public static CompilerConfiguration generateCompilerConfigurationFromOptions(CommandLine cli) { // // Setup the configuration data CompilerConfiguration configuration = new CompilerConfiguration(); if (cli.hasOption("classpath")) { configuration.setClasspath(cli.getOptionValue("classpath")); } if (cli.hasOption('d')) { configuration.setTargetDirectory(cli.getOptionValue('d')); } if (cli.hasOption("encoding")) { configuration.setSourceEncoding(cli.getOptionValue("encoding")); } // joint compilation parameters if (cli.hasOption('j')) { Map compilerOptions = new HashMap(); String[] opts = cli.getOptionValues("J"); compilerOptions.put("namedValues", opts); opts = cli.getOptionValues("F"); compilerOptions.put("flags", opts); configuration.setJointCompilationOptions(compilerOptions); } return configuration; } @SuppressWarnings({"AccessStaticViaInstance"}) public static Options createCompilationOptions() { // // Parse the command line Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("path").withDescription("Specify where to find the class files - must be first argument").create("classpath")); options.addOption(OptionBuilder.withLongOpt("classpath").hasArg().withArgName("path").withDescription("Aliases for '-classpath'").create("cp")); options.addOption(OptionBuilder.withLongOpt("sourcepath").hasArg().withArgName("path").withDescription("Specify where to find the source files").create()); options.addOption(OptionBuilder.withLongOpt("temp").hasArg().withArgName("temp").withDescription("Specify temporary directory").create()); options.addOption(OptionBuilder.withLongOpt("encoding").hasArg().withArgName("encoding").withDescription("Specify the encoding of the user class files").create()); options.addOption(OptionBuilder.hasArg().withDescription("Specify where to place generated class files").create('d')); // options.addOption(OptionBuilder.withLongOpt("strict").withDescription("Turn on strict type safety.").create('s')); options.addOption(OptionBuilder.withLongOpt("help").withDescription("Print a synopsis of standard options").create('h')); options.addOption(OptionBuilder.withLongOpt("version").withDescription("Print the version").create('v')); options.addOption(OptionBuilder.withLongOpt("exception").withDescription("Print stack trace on error").create('e')); options.addOption(OptionBuilder.withLongOpt("jointCompilation").withDescription("Attach javac compiler to compile .java files").create('j')); options.addOption( OptionBuilder.withArgName("property=value") .withValueSeparator() .hasArgs(2) .withDescription("name-value pairs to pass to javac") .create("J")); options.addOption( OptionBuilder.withArgName("flag") .hasArg() .withDescription("passed to javac for joint compilation") .create("F")); return options; } public static File createTempDir() throws IOException { final int MAXTRIES = 3; int accessDeniedCounter = 0; File tempFile=null; for (int i=0; i packageDocs; private List packageDocValues = null; private Map classDocs; private List classDocValues = null; private String description = ""; public SimpleGroovyRootDoc(String name) { super(name); packageDocs = new HashMap(); classDocs = new HashMap(); } public GroovyClassDoc classNamed(String name) { // look for full match or match excluding package for (String key : classDocs.keySet()) { if (key.equals(name)) return classDocs.get(key); int lastSlashIdx = key.lastIndexOf('/'); if (lastSlashIdx > 0) { String shortKey = key.substring(lastSlashIdx + 1); if (shortKey.equals(name)) { return classDocs.get(key); } } } return null; } public GroovyClassDoc classNamedExact(String name) { for (String key : classDocs.keySet()) { if (key.equals(name)) return classDocs.get(key); } return null; } public void setDescription(String description) { this.description = description; } public String description() { return description; } public String summary() { return SimpleGroovyDoc.calculateFirstSentence(description); } public GroovyClassDoc[] classes() { if (classDocValues == null) { classDocValues = new ArrayList(classDocs.values()); Collections.sort(classDocValues); } return classDocValues.toArray(new GroovyClassDoc[classDocValues.size()]); } public String[][] options() {/*todo*/ return null; } public GroovyPackageDoc packageNamed(String packageName) { return packageDocs.get(packageName); } public void putAllClasses(Map classes) { classDocs.putAll(classes); classDocValues = null; } public void put(String packageName, GroovyPackageDoc packageDoc) { packageDocs.put(packageName, packageDoc); packageDocValues = null; } public GroovyClassDoc[] specifiedClasses() {/*todo*/ return null; } public GroovyPackageDoc[] specifiedPackages() { if (packageDocValues == null) { packageDocValues = new ArrayList(packageDocs.values()); Collections.sort(packageDocValues); } return packageDocValues.toArray(new GroovyPackageDoc[packageDocValues.size()]); } public Map getVisibleClasses(List importedClassesAndPackages) { Map visibleClasses = new HashMap(); for (String fullClassName : classDocs.keySet()) { String equivalentPackageImport = fullClassName.replaceAll("[^/]+$", "*"); if (importedClassesAndPackages.contains(fullClassName) || importedClassesAndPackages.contains(equivalentPackageImport)) { GroovyClassDoc classDoc = classDocs.get(fullClassName); visibleClasses.put(classDoc.name(), classDoc); } } return visibleClasses; } // GroovyDocErrorReporter interface public void printError(String arg0) {/*todo*/} // public void printError(GroovySourcePosition arg0, String arg1) {/*todo*/} public void printNotice(String arg0) {/*todo*/} // public void printNotice(GroovySourcePosition arg0, String arg1) {/*todo*/} public void printWarning(String arg0) {/*todo*/} // public void printWarning(GroovySourcePosition arg0, String arg1) {/*todo*/} public void resolve() { //resolve class names at the end of adding all files to the tree for (GroovyClassDoc groovyClassDoc : classDocs.values()) { SimpleGroovyClassDoc classDoc = (SimpleGroovyClassDoc) groovyClassDoc; classDoc.resolve(this); } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/MockOutputTool.java0000644001501200150120000000275111627206700027007 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MockOutputTool implements OutputTool { Set outputAreas; // dirs Map output; public MockOutputTool() { outputAreas = new HashSet(); output = new HashMap(); } public void makeOutputArea(String filename) { outputAreas.add(filename); } public void writeToOutput(String fileName, String text) throws Exception { output.put(fileName, text); } public boolean isValidOutputArea(String fileName) { return outputAreas.contains(fileName); } public String getText(String fileName) { return (String) output.get(fileName); } public String toString() { return "dirs:" + outputAreas + ", files:" + output.keySet(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyProgramElementDoc.java0000644001501200150120000000600311627206700031760 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyAnnotationRef; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import org.codehaus.groovy.groovydoc.GroovyProgramElementDoc; import java.util.ArrayList; import java.util.List; public class SimpleGroovyProgramElementDoc extends SimpleGroovyDoc implements GroovyProgramElementDoc { private GroovyPackageDoc packageDoc; private boolean staticElement; private boolean finalElement; private boolean publicScope; private boolean protectedScope; private boolean packagePrivateScope; private boolean privateScope; private final List annotationRefs; public SimpleGroovyProgramElementDoc(String name) { super(name); annotationRefs = new ArrayList(); } public GroovyPackageDoc containingPackage() { return packageDoc; } public void setContainingPackage(GroovyPackageDoc packageDoc) { this.packageDoc = packageDoc; } public void setStatic(boolean b) { staticElement = b; } public boolean isStatic() { return staticElement; } public void setFinal(boolean b) { this.finalElement = b; } public boolean isFinal() { return finalElement; } public void setPublic(boolean b) { publicScope = b; } public boolean isPublic() { return publicScope; } public void setProtected(boolean b) { protectedScope = b; } public boolean isProtected() { return protectedScope; } public void setPackagePrivate(boolean b) { packagePrivateScope = b; } public boolean isPackagePrivate() { return packagePrivateScope; } public void setPrivate(boolean b) { privateScope = b; } public boolean isPrivate() { return privateScope; } public GroovyAnnotationRef[] annotations() { return annotationRefs.toArray(new GroovyAnnotationRef[annotationRefs.size()]); } public void addAnnotationRef(GroovyAnnotationRef ref) { annotationRefs.add(ref); } public GroovyClassDoc containingClass() {/*todo*/return null;} public String modifiers() {/*todo*/return null;} public int modifierSpecifier() {/*todo*/return 0;} public String qualifiedName() {/*todo*/return null;} } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/ClasspathResourceManager.java0000644001501200150120000000261011627206700030756 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.codehaus.groovy.runtime.DefaultGroovyMethods; public class ClasspathResourceManager implements ResourceManager { ClassLoader classLoader; public ClasspathResourceManager() { classLoader = getClass().getClassLoader(); } public ClasspathResourceManager(ClassLoader classLoader) { this.classLoader = classLoader; } public InputStream getInputStream(String resourceName) throws IOException { return classLoader.getResourceAsStream(resourceName); } public Reader getReader(String resourceName) throws IOException { return DefaultGroovyMethods.newReader(getInputStream(resourceName)); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyParameter.java0000644001501200150120000000433411707612046030341 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; import java.util.List; import java.util.ArrayList; public class SimpleGroovyParameter implements GroovyParameter { private String name; private String typeName; private String defaultValue; private GroovyType type; private boolean vararg; private final List annotationRefs; public SimpleGroovyParameter(String name) { this.name = name; annotationRefs = new ArrayList(); } public String defaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public String name() { return name; } public String typeName() { if (type == null) { return typeName; } return type.simpleTypeName(); } public void setTypeName(String typeName) { this.typeName = typeName; } public GroovyAnnotationRef[] annotations() { return annotationRefs.toArray(new GroovyAnnotationRef[annotationRefs.size()]); } public void addAnnotationRef(GroovyAnnotationRef ref) { annotationRefs.add(ref); } public GroovyType type() { return type; } /* for later class resolution */ public void setType(GroovyType type) { this.type = type; } public boolean isTypeAvailable() { return !(type == null); } public boolean vararg() { return vararg; } public void setVararg(boolean vararg) { this.vararg = vararg; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyType.java0000644001501200150120000000360111627206700027333 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyType; public class SimpleGroovyType implements GroovyType { private String typeName; public SimpleGroovyType(String typeName) { this.typeName = typeName; } public String typeName() { return typeName; } public boolean isPrimitive() { return false; // TODO } public String qualifiedTypeName() { return typeName.startsWith("DefaultPackage.") ? typeName.substring("DefaultPackage.".length()) : typeName; } public String simpleTypeName() { int lastDot = typeName.lastIndexOf('.'); if (lastDot < 0) return typeName; return typeName.substring(lastDot + 1); } // public GroovyAnnotationTypeDoc asAnnotationTypeDoc() {/*todo*/ // return null; // } // // public GroovyClassDoc asClassDoc() {/*todo*/ // return null; // } // // public GroovyParameterizedType asParameterizedType() {/*todo*/ // return null; // } // // public GroovyTypeVariable asTypeVariable() {/*todo*/ // return null; // } // // public GroovyWildcardType asWildcardType() {/*todo*/ // return null; // } // // public String dimension() {/*todo*/ // return null; // } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.java0000644001501200150120000007666311707612046031770 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import antlr.collections.AST; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.LineColumn; import org.codehaus.groovy.antlr.SourceBuffer; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import org.codehaus.groovy.antlr.treewalker.VisitorAdapter; import org.codehaus.groovy.control.ResolveVisitor; import org.codehaus.groovy.groovydoc.*; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleGroovyClassDocAssembler extends VisitorAdapter implements GroovyTokenTypes { private static final String FS = "/"; private static final Pattern PREV_JAVADOC_COMMENT_PATTERN = Pattern.compile("(?s)/\\*\\*(.*?)\\*/"); private final Stack stack; private Map classDocs; private List importedClassesAndPackages; private List links; private Properties properties; private SimpleGroovyFieldDoc currentFieldDoc; private SourceBuffer sourceBuffer; private String packagePath; private LineColumn lastLineCol; private boolean insideEnum; private Map foundClasses; private boolean isGroovy; private boolean deferSetup; private String className; public SimpleGroovyClassDocAssembler(String packagePath, String file, SourceBuffer sourceBuffer, List links, Properties properties, boolean isGroovy) { this.sourceBuffer = sourceBuffer; this.packagePath = packagePath; this.links = links; this.properties = properties; this.isGroovy = isGroovy; stack = new Stack(); classDocs = new HashMap(); className = file; if (file != null) { // todo: replace this simple idea of default class name int idx = file.lastIndexOf("."); className = file.substring(0, idx); } deferSetup = packagePath.equals("DefaultPackage"); importedClassesAndPackages = new ArrayList(); if (!deferSetup) setUpImports(packagePath, links, isGroovy, className); lastLineCol = new LineColumn(1, 1); } private void setUpImports(String packagePath, List links, boolean isGroovy, String className) { importedClassesAndPackages.add(packagePath + "/*"); // everything in this package if (isGroovy) { for (String pkg : ResolveVisitor.DEFAULT_IMPORTS) { importedClassesAndPackages.add(pkg.replace('.', '/') + "*"); } } else { importedClassesAndPackages.add("java/lang/*"); } SimpleGroovyClassDoc currentClassDoc = new SimpleGroovyClassDoc(importedClassesAndPackages, className, links); currentClassDoc.setFullPathName(packagePath + FS + className); currentClassDoc.setGroovy(isGroovy); classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc); } public Map getGroovyClassDocs() { postProcessClassDocs(); return classDocs; } @Override public void visitInterfaceDef(GroovySourceAST t, int visit) { visitClassDef(t, visit); } @Override public void visitEnumDef(GroovySourceAST t, int visit) { visitClassDef(t, visit); SimpleGroovyClassDoc currentClassDoc = getCurrentOrTopLevelClassDoc(t); if (visit == CLOSING_VISIT && currentClassDoc != null) { adjustForAutomaticEnumMethods(currentClassDoc); } } @Override public void visitAnnotationDef(GroovySourceAST t, int visit) { visitClassDef(t, visit); } @Override public void visitClassDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { SimpleGroovyClassDoc parent = getCurrentClassDoc(); String shortName = getIdentFor(t); String className = shortName; if (parent != null && isNested() && !insideAnonymousInnerClass()) { className = parent.name() + "." + className; } else { foundClasses = new HashMap(); } SimpleGroovyClassDoc current = (SimpleGroovyClassDoc) classDocs.get(packagePath + FS + className); if (current == null) { current = new SimpleGroovyClassDoc(importedClassesAndPackages, className, links); current.setGroovy(isGroovy); } current.setRawCommentText(getJavaDocCommentsBeforeNode(t)); current.setFullPathName(packagePath + FS + current.name()); current.setTokenType(t.getType()); processAnnotations(t, current); processModifiers(t, current); classDocs.put(current.getFullPathName(), current); foundClasses.put(shortName, current); if (parent != null) { parent.addNested(current); current.setOuter(parent); } } } @Override public void visitPackageDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT && deferSetup) { String packageWithSlashes = extractImportPath(t); setUpImports(packageWithSlashes, links, isGroovy, className); } } @Override public void visitImport(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { String importTextWithSlashesInsteadOfDots = extractImportPath(t); importedClassesAndPackages.add(importTextWithSlashesInsteadOfDots); } } // TODO is this needed so we can click through on default values? // @Override // public void visitStaticImport(GroovySourceAST t, int visit) { // if (visit == OPENING_VISIT) { // // TODO // String importTextWithSlashesInsteadOfDots = extractImportPath(t); // System.out.println(currentClassDoc.name() + " has static import: " + importTextWithSlashesInsteadOfDots); // } // } @Override public void visitExtendsClause(GroovySourceAST t, int visit) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); if (visit == OPENING_VISIT) { for (GroovySourceAST superClassNode : findTypeNames(t)) { String superClassName = extractName(superClassNode); if (currentClassDoc.isInterface()) { currentClassDoc.addInterfaceName(superClassName); } else { currentClassDoc.setSuperClassName(superClassName); } } } } @Override public void visitImplementsClause(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { for (GroovySourceAST classNode : findTypeNames(t)) { getCurrentClassDoc().addInterfaceName(extractName(classNode)); } } } private List findTypeNames(GroovySourceAST t) { List types = new ArrayList(); for (AST child = t.getFirstChild(); child != null; child = child.getNextSibling()) { GroovySourceAST groovySourceAST = (GroovySourceAST) child; if (groovySourceAST.getType() == TYPE) { types.add((GroovySourceAST) groovySourceAST.getFirstChild()); } else { types.add(groovySourceAST); } } return types; } @Override public void visitCtorIdent(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT && !insideEnum && !insideAnonymousInnerClass()) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); SimpleGroovyConstructorDoc currentConstructorDoc = new SimpleGroovyConstructorDoc(currentClassDoc.name(), currentClassDoc); currentConstructorDoc.setRawCommentText(getJavaDocCommentsBeforeNode(t)); processModifiers(t, currentConstructorDoc); addParametersTo(t, currentConstructorDoc); processAnnotations(t, currentConstructorDoc); currentClassDoc.add(currentConstructorDoc); } } @Override public void visitMethodDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT && !insideEnum && !insideAnonymousInnerClass()) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); if (currentClassDoc == null) { // assume we have a script if ("true".equals(properties.getProperty("processScripts", "true"))) { currentClassDoc = new SimpleGroovyClassDoc(importedClassesAndPackages, className, links); currentClassDoc.setFullPathName(packagePath + FS + className); currentClassDoc.setPublic(true); currentClassDoc.setScript(true); currentClassDoc.setGroovy(isGroovy); currentClassDoc.setSuperClassName("groovy/lang/Script"); if ("true".equals(properties.getProperty("includeMainForScripts", "true"))) { currentClassDoc.add(createMainMethod(currentClassDoc)); } classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc); if (foundClasses == null) { foundClasses = new HashMap(); } foundClasses.put(className, currentClassDoc); } else { return; } } String methodName = getIdentFor(t); SimpleGroovyMethodDoc currentMethodDoc = new SimpleGroovyMethodDoc(methodName, currentClassDoc); currentMethodDoc.setRawCommentText(getJavaDocCommentsBeforeNode(t)); processModifiers(t, currentMethodDoc); currentMethodDoc.setReturnType(new SimpleGroovyType(getTypeOrDefault(t))); addParametersTo(t, currentMethodDoc); processAnnotations(t, currentMethodDoc); currentClassDoc.add(currentMethodDoc); } } private GroovyMethodDoc createMainMethod(SimpleGroovyClassDoc currentClassDoc) { SimpleGroovyMethodDoc mainMethod = new SimpleGroovyMethodDoc("main", currentClassDoc); mainMethod.setPublic(true); mainMethod.setStatic(true); mainMethod.setCommentText("Implicit main method for Groovy Scripts"); mainMethod.setFirstSentenceCommentText(mainMethod.commentText()); SimpleGroovyParameter args = new SimpleGroovyParameter("args"); GroovyType argsType = new SimpleGroovyType("java.lang.String[]"); args.setType(argsType); mainMethod.add(args); GroovyType returnType = new SimpleGroovyType("void"); mainMethod.setReturnType(returnType); return mainMethod; } @Override public void visitAnnotationFieldDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { visitVariableDef(t, visit); String defaultText = getDefaultValue(t); if (defaultText != null) { currentFieldDoc.setConstantValueExpression(defaultText); String orig = currentFieldDoc.getRawCommentText(); currentFieldDoc.setRawCommentText(orig + "\n* @default " + defaultText); } } } @Override public void visitEnumConstantDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); insideEnum = true; String enumConstantName = getIdentFor(t); SimpleGroovyFieldDoc currentEnumConstantDoc = new SimpleGroovyFieldDoc(enumConstantName, currentClassDoc); currentEnumConstantDoc.setRawCommentText(getJavaDocCommentsBeforeNode(t)); processModifiers(t, currentEnumConstantDoc); String typeName = getTypeNodeAsText(t.childOfType(TYPE), currentClassDoc.getTypeDescription()); currentEnumConstantDoc.setType(new SimpleGroovyType(typeName)); currentClassDoc.addEnumConstant(currentEnumConstantDoc); } else if (visit == CLOSING_VISIT) { insideEnum = false; } } @Override public void visitVariableDef(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT && !insideAnonymousInnerClass() && isFieldDefinition()) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); if (currentClassDoc != null) { String fieldName = getIdentFor(t); currentFieldDoc = new SimpleGroovyFieldDoc(fieldName, currentClassDoc); currentFieldDoc.setRawCommentText(getJavaDocCommentsBeforeNode(t)); boolean isProp = processModifiers(t, currentFieldDoc); currentFieldDoc.setType(new SimpleGroovyType(getTypeOrDefault(t))); processAnnotations(t, currentFieldDoc); if (isProp) { currentClassDoc.addProperty(currentFieldDoc); } else { currentClassDoc.add(currentFieldDoc); } } } } @Override public void visitAssign(GroovySourceAST t, int visit) { gobbleComments(t, visit); } @Override public void visitMethodCall(GroovySourceAST t, int visit) { gobbleComments(t, visit); } private void gobbleComments(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc(); if (currentClassDoc == null || currentClassDoc.isScript()) { if (t.getLine() > lastLineCol.getLine() || (t.getLine() == lastLineCol.getLine() && t.getColumn() > lastLineCol.getColumn())) { getJavaDocCommentsBeforeNode(t); // not normally set for non-major types but appropriate for a script lastLineCol = new LineColumn(t.getLine(), t.getColumn()); } } } } // Step through ClassDocs and tie up loose ends private void postProcessClassDocs() { for (GroovyClassDoc groovyClassDoc : classDocs.values()) { SimpleGroovyClassDoc classDoc = (SimpleGroovyClassDoc) groovyClassDoc; // potentially add default constructor to class docs (but not interfaces) if (classDoc.isClass()) { GroovyConstructorDoc[] constructors = classDoc.constructors(); if (constructors != null && constructors.length == 0) { // add default constructor to doc // name of class for the constructor GroovyConstructorDoc constructorDoc = new SimpleGroovyConstructorDoc(classDoc.name(), classDoc); // don't forget to tell the class about this default constructor. classDoc.add(constructorDoc); } } } } private boolean isNested() { return getCurrentClassDoc() != null; } private boolean isTopLevelConstruct(GroovySourceAST node) { if (node == null) return false; int type = node.getType(); return type == CLASS_DEF || type == INTERFACE_DEF || type == ANNOTATION_DEF || type == ENUM_DEF; } private void adjustForAutomaticEnumMethods(SimpleGroovyClassDoc currentClassDoc) { SimpleGroovyMethodDoc valueOf = new SimpleGroovyMethodDoc("valueOf", currentClassDoc); valueOf.setRawCommentText("Returns the enum constant of this type with the specified name."); SimpleGroovyParameter parameter = new SimpleGroovyParameter("name"); parameter.setTypeName("String"); valueOf.add(parameter); valueOf.setReturnType(new SimpleGroovyType(currentClassDoc.name())); currentClassDoc.add(valueOf); SimpleGroovyMethodDoc values = new SimpleGroovyMethodDoc("values", currentClassDoc); values.setRawCommentText("Returns an array containing the constants of this enum type, in the order they are declared."); values.setReturnType(new SimpleGroovyType(currentClassDoc.name() + "[]")); currentClassDoc.add(values); } private String extractImportPath(GroovySourceAST t) { GroovySourceAST child = t.childOfType(DOT); if (child == null) { child = t.childOfType(IDENT); } return recurseDownImportBranch(child); } private String recurseDownImportBranch(GroovySourceAST t) { if (t != null) { if (t.getType() == DOT) { GroovySourceAST firstChild = (GroovySourceAST) t.getFirstChild(); GroovySourceAST secondChild = (GroovySourceAST) firstChild.getNextSibling(); return (recurseDownImportBranch(firstChild) + "/" + recurseDownImportBranch(secondChild)); } if (t.getType() == IDENT) { return t.getText(); } if (t.getType() == STAR) { return t.getText(); } } return ""; } private void addAnnotationRef(SimpleGroovyProgramElementDoc node, GroovySourceAST t) { GroovySourceAST classNode = t.childOfType(IDENT); if (classNode != null) { node.addAnnotationRef(new SimpleGroovyAnnotationRef(extractName(classNode), getChildTextFromSource(t).trim())); } } private void addAnnotationRef(SimpleGroovyParameter node, GroovySourceAST t) { GroovySourceAST classNode = t.childOfType(IDENT); if (classNode != null) { node.addAnnotationRef(new SimpleGroovyAnnotationRef(extractName(classNode), getChildTextFromSource(t).trim())); } } private void addAnnotationRefs(SimpleGroovyProgramElementDoc node, List nodes) { for (GroovySourceAST t : nodes) { addAnnotationRef(node, t); } } private void processAnnotations(GroovySourceAST t, SimpleGroovyProgramElementDoc node) { GroovySourceAST modifiers = t.childOfType(MODIFIERS); if (modifiers != null) { addAnnotationRefs(node, modifiers.childrenOfType(ANNOTATION)); } } // hack warning! fragile! TODO find a better way private String getDefaultValue(GroovySourceAST t) { GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (t.getNumberOfChildren() != 4) return null; for (int i = 1; i < t.getNumberOfChildren(); i++) { child = (GroovySourceAST) child.getNextSibling(); } GroovySourceAST nodeToProcess = child; if (child.getNumberOfChildren() > 0) { nodeToProcess = (GroovySourceAST) child.getFirstChild(); } return getChildTextFromSource(nodeToProcess, ";"); } private String getChildTextFromSource(GroovySourceAST child) { return sourceBuffer.getSnippet( new LineColumn(child.getLine(), child.getColumn()), new LineColumn(child.getLineLast(), child.getColumnLast())); } private String getChildTextFromSource(GroovySourceAST child, String tokens) { String text = sourceBuffer.getSnippet( new LineColumn(child.getLine(), child.getColumn()), new LineColumn(child.getLine() + 1, 0)); StringTokenizer st = new StringTokenizer(text, tokens); return st.nextToken(); } private boolean isFieldDefinition() { GroovySourceAST parentNode = getParentNode(); return parentNode != null && parentNode.getType() == OBJBLOCK; } private boolean insideAnonymousInnerClass() { GroovySourceAST grandParentNode = getGrandParentNode(); return grandParentNode != null && grandParentNode.getType() == LITERAL_new; } // return true if a property is found private boolean processModifiers(GroovySourceAST t, SimpleGroovyAbstractableElementDoc memberOrClass) { GroovySourceAST modifiers = t.childOfType(MODIFIERS); boolean hasNonPublicVisibility = false; boolean hasPublicVisibility = false; if (modifiers != null) { AST currentModifier = modifiers.getFirstChild(); while (currentModifier != null) { int type = currentModifier.getType(); switch (type) { case LITERAL_public: memberOrClass.setPublic(true); hasPublicVisibility = true; break; case LITERAL_protected: memberOrClass.setProtected(true); hasNonPublicVisibility = true; break; case LITERAL_private: memberOrClass.setPrivate(true); hasNonPublicVisibility = true; break; case LITERAL_static: memberOrClass.setStatic(true); break; case FINAL: memberOrClass.setFinal(true); break; case ABSTRACT: memberOrClass.setAbstract(true); break; } currentModifier = currentModifier.getNextSibling(); } if (!hasNonPublicVisibility && isGroovy && !(memberOrClass instanceof GroovyFieldDoc)) { // in groovy methods and classes are assumed public, unless informed otherwise memberOrClass.setPublic(true); } else if (!hasNonPublicVisibility && !hasPublicVisibility && !isGroovy) { if (insideInterface(memberOrClass)) { memberOrClass.setPublic(true); } else { memberOrClass.setPackagePrivate(true); } } if (memberOrClass instanceof GroovyFieldDoc && !hasNonPublicVisibility && !hasPublicVisibility && isGroovy) return true; } else if (isGroovy && !(memberOrClass instanceof GroovyFieldDoc)) { // in groovy methods and classes are assumed public, unless informed otherwise memberOrClass.setPublic(true); } else if (!isGroovy) { if (insideInterface(memberOrClass)) { memberOrClass.setPublic(true); } else { memberOrClass.setPackagePrivate(true); } } return memberOrClass instanceof GroovyFieldDoc && isGroovy && !hasNonPublicVisibility & !hasPublicVisibility; } private boolean insideInterface(SimpleGroovyAbstractableElementDoc memberOrClass) { SimpleGroovyClassDoc current = getCurrentClassDoc(); if (current == null || current == memberOrClass) return false; return current.isInterface(); } // todo - If no comment before node, then get comment from same node on parent class - ouch! private String getJavaDocCommentsBeforeNode(GroovySourceAST t) { String result = ""; LineColumn thisLineCol = new LineColumn(t.getLine(), t.getColumn()); String text = sourceBuffer.getSnippet(lastLineCol, thisLineCol); if (text != null) { Matcher m = PREV_JAVADOC_COMMENT_PATTERN.matcher(text); if (m.find()) { result = m.group(1); } } if (isMajorType(t)) { lastLineCol = thisLineCol; } return result; } private boolean isMajorType(GroovySourceAST t) { if (t == null) return false; int tt = t.getType(); return tt == CLASS_DEF || tt == INTERFACE_DEF || tt == METHOD_DEF || tt == ANNOTATION_DEF || tt == ENUM_DEF || tt == VARIABLE_DEF || tt == ANNOTATION_FIELD_DEF || tt == ENUM_CONSTANT_DEF || tt == CTOR_IDENT; } private String getText(GroovySourceAST node) { String returnValue = null; if (node != null) { returnValue = node.getText(); } return returnValue; } // preempt resolve as info is partially available here (star imports won't match here) private String extractName(GroovySourceAST typeNode) { String typeName = buildName(typeNode); if (typeName.indexOf("/") == -1) { String slashName = "/" + typeName; for (String name : importedClassesAndPackages) { if (name.endsWith(slashName)) { typeName = name; } } } return typeName; } private String buildName(GroovySourceAST t) { if (t != null) { if (t.getType() == DOT) { GroovySourceAST firstChild = (GroovySourceAST) t.getFirstChild(); GroovySourceAST secondChild = (GroovySourceAST) firstChild.getNextSibling(); return (buildName(firstChild) + "/" + buildName(secondChild)); } if (t.getType() == IDENT) { return t.getText(); } } return ""; } private String getTypeOrDefault(GroovySourceAST t) { GroovySourceAST typeNode = t.childOfType(TYPE); return getTypeNodeAsText(typeNode, "def"); } private String getTypeNodeAsText(GroovySourceAST typeNode, String defaultText) { if (typeNode != null && typeNode.getType() == TYPE && typeNode.getNumberOfChildren() > 0) { return getAsText(typeNode, defaultText); } return defaultText; } private String getAsText(GroovySourceAST typeNode, String defaultText) { GroovySourceAST child = (GroovySourceAST) typeNode.getFirstChild(); return getAsTextCurrent(child, defaultText); } private String getAsTextCurrent(GroovySourceAST node, String defaultText) { switch (node.getType()) { // literals case LITERAL_boolean: return "boolean"; case LITERAL_byte: return "byte"; case LITERAL_char: return "char"; // note: LITERAL_def never created case LITERAL_double: return "double"; case LITERAL_float: return "float"; case LITERAL_int: return "int"; case LITERAL_long: return "long"; case LITERAL_short: return "short"; case LITERAL_void: return "void"; case ARRAY_DECLARATOR: String componentType = getAsText(node, defaultText); if (!componentType.equals("def")) return componentType + "[]"; return "java/lang/Object[]"; // identifiers case IDENT: return node.getText(); case DOT: List result = new ArrayList(); GroovySourceAST child = (GroovySourceAST) node.getFirstChild(); while (child != null) { if (child.getType() == IDENT) { result.add(child.getText()); } else if (child.getType() == DOT) { result.add(getAsTextCurrent(child, defaultText)); } child = (GroovySourceAST) child.getNextSibling(); } return DefaultGroovyMethods.join(result, "/"); } return defaultText; } private void addParametersTo(GroovySourceAST t, SimpleGroovyExecutableMemberDoc executableMemberDoc) { // parameters GroovySourceAST parametersNode = t.childOfType(PARAMETERS); if (parametersNode != null && parametersNode.getNumberOfChildren() > 0) { GroovySourceAST currentNode = (GroovySourceAST) parametersNode.getFirstChild(); while (currentNode != null) { String parameterTypeName = getTypeOrDefault(currentNode); String parameterName = getText(currentNode.childOfType(IDENT)); SimpleGroovyParameter parameter = new SimpleGroovyParameter(parameterName); parameter.setVararg(currentNode.getType() == VARIABLE_PARAMETER_DEF); parameter.setTypeName(parameterTypeName); GroovySourceAST modifiers = currentNode.childOfType(MODIFIERS); if (modifiers != null) { List annotations = modifiers.childrenOfType(ANNOTATION); for (GroovySourceAST a : annotations) { addAnnotationRef(parameter, a); } } executableMemberDoc.add(parameter); if (currentNode.getNumberOfChildren() == 4) { handleDefaultValue(currentNode, parameter); } currentNode = (GroovySourceAST) currentNode.getNextSibling(); } } } private void handleDefaultValue(GroovySourceAST currentNode, SimpleGroovyParameter parameter) { GroovySourceAST paramPart = (GroovySourceAST) currentNode.getFirstChild(); for (int i = 1; i < currentNode.getNumberOfChildren(); i++) { paramPart = (GroovySourceAST) paramPart.getNextSibling(); } GroovySourceAST nodeToProcess = paramPart; if (paramPart.getNumberOfChildren() > 0) { nodeToProcess = (GroovySourceAST) paramPart.getFirstChild(); } // hack warning! // TODO handle , and ) when they occur within Strings parameter.setDefaultValue(getChildTextFromSource(nodeToProcess, ",)")); } public void push(GroovySourceAST t) { stack.push(t); } public GroovySourceAST pop() { if (!stack.empty()) { return stack.pop(); } return null; } private GroovySourceAST getParentNode() { GroovySourceAST parentNode = null; GroovySourceAST currentNode = stack.pop(); if (!stack.empty()) { parentNode = stack.peek(); } stack.push(currentNode); return parentNode; } private GroovySourceAST getGrandParentNode() { GroovySourceAST grandParentNode = null; GroovySourceAST parentNode; GroovySourceAST currentNode = stack.pop(); if (!stack.empty()) { parentNode = stack.pop(); if (!stack.empty()) { grandParentNode = stack.peek(); } stack.push(parentNode); } stack.push(currentNode); return grandParentNode; } private SimpleGroovyClassDoc getCurrentOrTopLevelClassDoc(GroovySourceAST node) { SimpleGroovyClassDoc current = getCurrentClassDoc(); if (current != null) return current; return foundClasses.get(getIdentFor(node)); } private SimpleGroovyClassDoc getCurrentClassDoc() { if (stack.isEmpty()) return null; GroovySourceAST node = getParentNode(); if (isTopLevelConstruct(node)) return foundClasses.get(getIdentFor(node)); GroovySourceAST saved = stack.pop(); SimpleGroovyClassDoc result = getCurrentClassDoc(); stack.push(saved); return result; } private String getIdentFor(GroovySourceAST gpn) { return gpn.childOfType(IDENT).getText(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/ResourceManager.java0000644001501200150120000000146111627206700027116 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.io.IOException; import java.io.Reader; public interface ResourceManager { Reader getReader(String resourceName) throws IOException; } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java0000644001501200150120000007301711713766062030125 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc implements GroovyClassDoc { public static final Pattern TAG_REGEX = Pattern.compile("(?sm)\\s*@([a-zA-Z.]+)\\s+(.*?)(?=\\s+@)"); public static final Pattern LINK_REGEX = Pattern.compile("(?m)[{]@(link)\\s+([^}]*)}"); public static final Pattern CODE_REGEX = Pattern.compile("(?m)[{]@(code)\\s+([^}]*)}"); public static final Pattern REF_LABEL_REGEX = Pattern.compile("([\\w.#\\$]*(\\(.*\\))?)(\\s(.*))?"); public static final Pattern NAME_ARGS_REGEX = Pattern.compile("([^(]+)\\(([^)]*)\\)"); public static final Pattern SPLIT_ARGS_REGEX = Pattern.compile(",\\s*"); private static final List PRIMITIVES = Arrays.asList("void", "boolean", "byte", "short", "char", "int", "long", "float", "double"); private static final Map TAG_TEXT = new HashMap(); static { TAG_TEXT.put("see", "See Also"); TAG_TEXT.put("param", "Parameters"); TAG_TEXT.put("throw", "Throws"); TAG_TEXT.put("exception", "Throws"); TAG_TEXT.put("return", "Returns"); TAG_TEXT.put("since", "Since"); TAG_TEXT.put("author", "Authors"); TAG_TEXT.put("version", "Version"); } private final List constructors; private final List fields; private final List properties; private final List enumConstants; private final List methods; private final List importedClassesAndPackages; private final List interfaceNames; private final List interfaceClasses; private final List nested; private final List links; private GroovyClassDoc superClass; private GroovyClassDoc outer; private String superClassName; private String fullPathName; private boolean isgroovy; private GroovyRootDoc savedRootDoc = null; public SimpleGroovyClassDoc(List importedClassesAndPackages, String name, List links) { super(name); this.importedClassesAndPackages = importedClassesAndPackages; this.links = links; constructors = new ArrayList(); fields = new ArrayList(); properties = new ArrayList(); enumConstants = new ArrayList(); methods = new ArrayList(); interfaceNames = new ArrayList(); interfaceClasses = new ArrayList(); nested = new ArrayList(); } public SimpleGroovyClassDoc(List importedClassesAndPackages, String name) { this(importedClassesAndPackages, name, new ArrayList()); } /** * returns a sorted array of constructors */ public GroovyConstructorDoc[] constructors() { Collections.sort(constructors); return constructors.toArray(new GroovyConstructorDoc[constructors.size()]); } public boolean add(GroovyConstructorDoc constructor) { return constructors.add(constructor); } // TODO remove? public GroovyClassDoc getOuter() { return outer; } public void setOuter(GroovyClassDoc outer) { this.outer = outer; } public boolean isGroovy() { return isgroovy; } public void setGroovy(boolean isgroovy) { this.isgroovy = isgroovy; } /** * returns a sorted array of nested classes and interfaces */ public GroovyClassDoc[] innerClasses() { Collections.sort(nested); return nested.toArray(new GroovyClassDoc[nested.size()]); } public boolean addNested(GroovyClassDoc nestedClass) { return nested.add(nestedClass); } /** * returns a sorted array of fields */ public GroovyFieldDoc[] fields() { Collections.sort(fields); return fields.toArray(new GroovyFieldDoc[fields.size()]); } public boolean add(GroovyFieldDoc field) { return fields.add(field); } /** * returns a sorted array of properties */ public GroovyFieldDoc[] properties() { Collections.sort(properties); return properties.toArray(new GroovyFieldDoc[properties.size()]); } public boolean addProperty(GroovyFieldDoc property) { return properties.add(property); } /** * returns a sorted array of enum constants */ public GroovyFieldDoc[] enumConstants() { Collections.sort(enumConstants); return enumConstants.toArray(new GroovyFieldDoc[enumConstants.size()]); } public boolean addEnumConstant(GroovyFieldDoc field) { return enumConstants.add(field); } /** * returns a sorted array of methods */ public GroovyMethodDoc[] methods() { Collections.sort(methods); return methods.toArray(new GroovyMethodDoc[methods.size()]); } public boolean add(GroovyMethodDoc method) { return methods.add(method); } public String getSuperClassName() { return superClassName; } public void setSuperClassName(String className) { superClassName = className; } public GroovyClassDoc superclass() { return superClass; } public void setSuperClass(GroovyClassDoc doc) { superClass = doc; } public String getFullPathName() { return fullPathName; } public void setFullPathName(String fullPathName) { this.fullPathName = fullPathName; } public String getRelativeRootPath() { StringTokenizer tokenizer = new StringTokenizer(fullPathName, "/"); // todo windows?? StringBuilder sb = new StringBuilder(); if (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // ignore the first token, as we want n-1 parent dirs } while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); sb.append("../"); } return sb.toString(); } // TODO move logic here into resolve public List getParentClasses() { List result = new LinkedList(); if (isInterface()) return result; result.add(0, this); GroovyClassDoc next = this; while (next.superclass() != null && !"java.lang.Object".equals(next.qualifiedTypeName())) { next = next.superclass(); result.add(0, next); } GroovyClassDoc prev = next; Class nextClass = getClassOf(next.qualifiedTypeName()); while (nextClass != null && nextClass.getSuperclass() != null && !Object.class.equals(nextClass)) { nextClass = nextClass.getSuperclass(); GroovyClassDoc nextDoc = new ExternalGroovyClassDoc(nextClass); if (prev instanceof SimpleGroovyClassDoc) { SimpleGroovyClassDoc parent = (SimpleGroovyClassDoc) prev; parent.setSuperClass(nextDoc); } result.add(0, nextDoc); prev = nextDoc; } if (!result.get(0).qualifiedTypeName().equals("java.lang.Object")) { result.add(0, new ExternalGroovyClassDoc(Object.class)); } return result; } public Set getParentInterfaces() { Set result = new HashSet(); result.add(this); Set next = new HashSet(); next.addAll(Arrays.asList(this.interfaces())); while (next.size() > 0) { Set temp = next; next = new HashSet(); for (GroovyClassDoc t : temp) { if (t instanceof SimpleGroovyClassDoc) { next.addAll(((SimpleGroovyClassDoc)t).getParentInterfaces()); } else if (t instanceof ExternalGroovyClassDoc) { ExternalGroovyClassDoc d = (ExternalGroovyClassDoc) t; next.addAll(getJavaInterfaces(d)); } } next = DefaultGroovyMethods.minus(next, result); result.addAll(next); } return result; } private Set getJavaInterfaces(ExternalGroovyClassDoc d) { Set result = new HashSet(); Class[] interfaces = d.externalClass().getInterfaces(); if (interfaces != null) { for (Class i : interfaces) { ExternalGroovyClassDoc doc = new ExternalGroovyClassDoc(i); result.add(doc); result.addAll(getJavaInterfaces(doc)); } } return result; } private Class getClassOf(String next) { try { return Class.forName(next.replace("/", ".")); } catch (Throwable t) { return null; } } void resolve(GroovyRootDoc rootDoc) { this.savedRootDoc = rootDoc; Map visibleClasses = rootDoc.getVisibleClasses(importedClassesAndPackages); // resolve constructor parameter types for (GroovyConstructorDoc constructor : constructors) { // parameters for (GroovyParameter groovyParameter : constructor.parameters()) { SimpleGroovyParameter param = (SimpleGroovyParameter) groovyParameter; String paramTypeName = param.typeName(); if (visibleClasses.containsKey(paramTypeName)) { param.setType((GroovyType) visibleClasses.get(paramTypeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, paramTypeName); if (doc != null) param.setType(doc); } } } for (GroovyFieldDoc field : fields) { SimpleGroovyFieldDoc mutableField = (SimpleGroovyFieldDoc) field; GroovyType fieldType = field.type(); String typeName = fieldType.typeName(); if (visibleClasses.containsKey(typeName)) { mutableField.setType((GroovyType) visibleClasses.get(typeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, typeName); if (doc != null) mutableField.setType(doc); } } // resolve method return types and parameter types for (GroovyMethodDoc method : methods) { // return types GroovyType returnType = method.returnType(); String typeName = returnType.typeName(); if (visibleClasses.containsKey(typeName)) { method.setReturnType((GroovyType) visibleClasses.get(typeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, typeName); if (doc != null) method.setReturnType(doc); } // parameters for (GroovyParameter groovyParameter : method.parameters()) { SimpleGroovyParameter param = (SimpleGroovyParameter) groovyParameter; String paramTypeName = param.typeName(); if (visibleClasses.containsKey(paramTypeName)) { param.setType((GroovyType) visibleClasses.get(paramTypeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, paramTypeName); if (doc != null) param.setType(doc); } } } if (superClassName != null && superClass == null) { superClass = resolveClass(rootDoc, superClassName); } for (String name : interfaceNames) { interfaceClasses.add(resolveClass(rootDoc, name)); } for (GroovyAnnotationRef annotation : annotations()) { SimpleGroovyAnnotationRef ref = (SimpleGroovyAnnotationRef) annotation; ref.setType(resolveClass(rootDoc, ref.name())); } } public String getDocUrl(String type) { return getDocUrl(type, false); } public String getDocUrl(String type, boolean full) { return getDocUrl(type, full, links, getRelativeRootPath(), savedRootDoc, this); } private static String resolveMethodArgs(GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc, String type) { if (!type.contains("(")) return type; Matcher m = NAME_ARGS_REGEX.matcher(type); if (m.matches()) { String name = m.group(1); String args = m.group(2); StringBuilder sb = new StringBuilder(); sb.append(name); sb.append("("); String[] argParts = SPLIT_ARGS_REGEX.split(args); boolean first = true; for (String argPart : argParts) { if (first) first = false; else sb.append(", "); GroovyClassDoc doc = classDoc.resolveClass(rootDoc, argPart); sb.append(doc == null ? argPart : doc.qualifiedTypeName()); } sb.append(")"); return sb.toString(); } return type; } public static String getDocUrl(String type, boolean full, List links, String relativePath, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) { if (type == null) return type; type = type.trim(); if (isPrimitiveType(type)) return type; if (type.equals("def")) type = "java.lang.Object def"; String label = null; Matcher matcher = REF_LABEL_REGEX.matcher(type); if (matcher.find()) { type = matcher.group(1); label = matcher.group(4); } if (type.startsWith("#")) return "" + (label == null ? type.substring(1) : label) + ""; if (type.endsWith("[]")) { if (label != null) return getDocUrl(type.substring(0, type.length() - 2) + " " + label, full, links, relativePath, rootDoc, classDoc); return getDocUrl(type.substring(0, type.length() - 2), full, links, relativePath, rootDoc, classDoc) + "[]"; } if (type.indexOf('.') == -1 && classDoc != null) { String[] pieces = type.split("#"); String candidate = pieces[0]; Class c = classDoc.resolveExternalClassFromImport(candidate); if (c != null) type = c.getName(); if (pieces.length > 1) type += "#" + pieces[1]; type = resolveMethodArgs(rootDoc, classDoc, type); } if (type.indexOf('.') == -1) return type; final String[] target = type.split("#"); String shortClassName = target[0].replaceAll(".*\\.", ""); shortClassName += (target.length > 1 ? "#" + target[1].split("\\(")[0] : ""); String name = (full ? target[0] : shortClassName).replaceAll("#", ".").replace('$', '.'); // last chance lookup for classes within the current codebase if (rootDoc != null) { String slashedName = target[0].replaceAll("\\.", "/"); GroovyClassDoc doc = rootDoc.classNamed(slashedName); if (doc != null) { return buildUrl(relativePath, target, label == null ? name : label); } } for (LinkArgument link : links) { final StringTokenizer tokenizer = new StringTokenizer(link.getPackages(), ", "); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (type.startsWith(token)) { return buildUrl(link.getHref(), target, label == null ? name : label); } } } return type; } private static String buildUrl(String relativeRoot, String[] target, String shortClassName) { if (relativeRoot.length() > 0 && !relativeRoot.endsWith("/")) { relativeRoot += "/"; } String url = relativeRoot + target[0].replace('.', '/').replace('$', '.') + ".html" + (target.length > 1 ? "#" + target[1] : ""); return "" + shortClassName + ""; } private GroovyClassDoc resolveClass(GroovyRootDoc rootDoc, String name) { if (isPrimitiveType(name)) return null; if (name.endsWith("[]")) { GroovyClassDoc componentClass = resolveClass(rootDoc, name.substring(0, name.length() - 2)); if (componentClass != null) return new ArrayClassDocWrapper(componentClass); return null; } if (name.equals("T") || name.equals("U") || name.equals("K") || name.equals("V") || name.equals("G")) { name = "java/lang/Object"; } GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(name); if (doc != null) return doc; int slashIndex = name.lastIndexOf("/"); if (slashIndex < 1) { doc = resolveInternalClassDocFromImport(rootDoc, name); if (doc != null) return doc; for (GroovyClassDoc nestedDoc : nested) { if (nestedDoc.name().endsWith("." + name)) return nestedDoc; } doc = rootDoc.classNamed(name); if (doc != null) return doc; } // The class is not in the tree being documented String shortname = name; Class c; if (slashIndex > 0) { shortname = name.substring(slashIndex + 1); c = resolveExternalFullyQualifiedClass(name); } else { c = resolveExternalClassFromImport(name); } if (c == null) { c = resolveFromJavaLang(name); } if (c != null) { return new ExternalGroovyClassDoc(c); } if (name.contains("/")) { // search for nested class if (slashIndex > 0) { String outerName = name.substring(0, slashIndex); GroovyClassDoc gcd = resolveClass(rootDoc, outerName); if (gcd instanceof ExternalGroovyClassDoc) { ExternalGroovyClassDoc egcd = (ExternalGroovyClassDoc) gcd; String innerName = name.substring(slashIndex+1); Class outerClass = egcd.externalClass(); for (Class inner : outerClass.getDeclaredClasses()) { if (inner.getName().equals(outerClass.getName() + "$" + innerName)) { return new ExternalGroovyClassDoc(inner); } } } } } // and we can't find it SimpleGroovyClassDoc placeholder = new SimpleGroovyClassDoc(null, shortname); placeholder.setFullPathName(name); return placeholder; } private Class resolveFromJavaLang(String name) { try { return Class.forName("java.lang." + name); } catch (NoClassDefFoundError e) { // ignore } catch (ClassNotFoundException e) { // ignore } return null; } private static boolean isPrimitiveType(String name) { String type = name; if (name.endsWith("[]")) type = name.substring(0, name.length() - 2); return PRIMITIVES.contains(type); } private GroovyClassDoc resolveInternalClassDocFromImport(GroovyRootDoc rootDoc, String baseName) { if (isPrimitiveType(baseName)) return null; for (String importName : importedClassesAndPackages) { if (importName.endsWith("/" + baseName)) { GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(importName); if (doc != null) return doc; } else if (importName.endsWith("/*")) { GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(importName.substring(0, importName.length() - 2) + baseName); if (doc != null) return doc; } } return null; } private Class resolveExternalClassFromImport(String name) { if (isPrimitiveType(name)) return null; for (String importName : importedClassesAndPackages) { String candidate = null; if (importName.endsWith("/" + name)) { candidate = importName.replaceAll("/", "."); } else if (importName.endsWith("/*")) { candidate = importName.substring(0, importName.length() - 2).replace('/', '.') + "." + name; } if (candidate != null) { try { // TODO cache these?? return Class.forName(candidate); } catch (NoClassDefFoundError e) { // ignore } catch (ClassNotFoundException e) { // ignore } } } return null; } private Class resolveExternalFullyQualifiedClass(String name) { String candidate = name.replace('/', '.'); try { // TODO cache these?? return Class.forName(candidate); } catch (NoClassDefFoundError e) { // ignore } catch (ClassNotFoundException e) { // ignore } return null; } // methods from GroovyClassDoc public GroovyConstructorDoc[] constructors(boolean filter) {/*todo*/ return null; } public boolean definesSerializableFields() {/*todo*/ return false; } public GroovyFieldDoc[] fields(boolean filter) {/*todo*/ return null; } public GroovyClassDoc findClass(String className) {/*todo*/ return null; } public GroovyClassDoc[] importedClasses() {/*todo*/ return null; } public GroovyPackageDoc[] importedPackages() {/*todo*/ return null; } public GroovyClassDoc[] innerClasses(boolean filter) {/*todo*/ return null; } public GroovyClassDoc[] interfaces() { Collections.sort(interfaceClasses); return interfaceClasses.toArray(new GroovyClassDoc[interfaceClasses.size()]); } public GroovyType[] interfaceTypes() {/*todo*/ return null; } public boolean isExternalizable() {/*todo*/ return false; } public boolean isSerializable() {/*todo*/ return false; } public GroovyMethodDoc[] methods(boolean filter) {/*todo*/ return null; } public GroovyFieldDoc[] serializableFields() {/*todo*/ return null; } public GroovyMethodDoc[] serializationMethods() {/*todo*/ return null; } public boolean subclassOf(GroovyClassDoc gcd) {/*todo*/ return false; } public GroovyType superclassType() {/*todo*/ return null; } // public GroovyTypeVariable[] typeParameters() {/*todo*/return null;} // not supported in groovy // public GroovyParamTag[] typeParamTags() {/*todo*/return null;} // not supported in groovy // methods from GroovyType (todo: remove this horrible copy of SimpleGroovyType.java) // public GroovyAnnotationTypeDoc asAnnotationTypeDoc() {/*todo*/return null;} // public GroovyClassDoc asClassDoc() {/*todo*/ return null; } // public GroovyParameterizedType asParameterizedType() {/*todo*/return null;} // public GroovyTypeVariable asTypeVariable() {/*todo*/return null;} // public GroovyWildcardType asWildcardType() {/*todo*/return null;} // public String dimension() {/*todo*/ return null; } public boolean isPrimitive() {/*todo*/ return false; } public String qualifiedTypeName() { String qtnWithSlashes = fullPathName.startsWith("DefaultPackage/") ? fullPathName.substring("DefaultPackage/".length()) : fullPathName; return qtnWithSlashes.replace('/', '.'); } // TODO remove dupe with SimpleGroovyType public String simpleTypeName() { String typeName = qualifiedTypeName(); int lastDot = typeName.lastIndexOf('.'); if (lastDot < 0) return typeName; return typeName.substring(lastDot + 1); } public String typeName() {/*todo*/ return null; } public void addInterfaceName(String className) { interfaceNames.add(className); } public String firstSentenceCommentText() { if (super.firstSentenceCommentText() == null) setFirstSentenceCommentText(replaceTags(calculateFirstSentence(getRawCommentText()))); return super.firstSentenceCommentText(); } public String commentText() { if (super.commentText() == null) setCommentText(replaceTags(getRawCommentText())); return super.commentText(); } public String replaceTags(String comment) { String result = comment.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex // {@link processing hack} result = replaceAllTags(result, "", "", LINK_REGEX); // {@code processing hack} result = replaceAllTags(result, "", "", CODE_REGEX); // hack to reformat other groovydoc block tags (@see, @return, @param, @throws, @author, @since) into html result = replaceAllTagsCollated(result, "
      ", ":
      ", "
      ", "
      ", TAG_REGEX); return decodeSpecialSymbols(result); } public String replaceAllTags(String self, String s1, String s2, Pattern regex) { return replaceAllTags(self, s1, s2, regex, links, getRelativeRootPath(), savedRootDoc, this); } // TODO: this should go away once we have proper tags public static String replaceAllTags(String self, String s1, String s2, Pattern regex, List links, String relPath, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) { Matcher matcher = regex.matcher(self); if (matcher.find()) { matcher.reset(); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tagname = matcher.group(1); if (!"interface".equals(tagname)) { String content = encodeSpecialSymbols(matcher.group(2)); if ("link".equals(tagname) || "see".equals(tagname)) { content = getDocUrl(content, false, links, relPath, rootDoc, classDoc); } matcher.appendReplacement(sb, s1 + content + s2); } } matcher.appendTail(sb); return sb.toString(); } else { return self; } } // TODO: is there a better way to do this? public String replaceAllTagsCollated(String self, String preKey, String postKey, String valueSeparator, String postValues, Pattern regex) { Matcher matcher = regex.matcher(self + "@endMarker"); if (matcher.find()) { matcher.reset(); Map> savedTags = new HashMap>(); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tagname = matcher.group(1); if (!"interface".equals(tagname)) { String content = encodeSpecialSymbols(matcher.group(2)); if ("see".equals(tagname) || "link".equals(tagname)) { content = getDocUrl(content); } else if ("param".equals(tagname)) { int index = content.indexOf(" "); if (index >= 0) { content = "" + content.substring(0, index) + " - " + content.substring(index); } } if (TAG_TEXT.containsKey(tagname)) { String text = TAG_TEXT.get(tagname); List contents = savedTags.get(text); if (contents == null) { contents = new ArrayList(); savedTags.put(text, contents); } contents.add(content); matcher.appendReplacement(sb, ""); } else { matcher.appendReplacement(sb, preKey + tagname + postKey + content + postValues); } } } matcher.appendTail(sb); // remove @endMarker sb = new StringBuffer(sb.substring(0, sb.length() - 10)); for (Map.Entry> e : savedTags.entrySet()) { sb.append(preKey); sb.append(e.getKey()); sb.append(postKey); sb.append(DefaultGroovyMethods.join(e.getValue(), valueSeparator)); sb.append(postValues); } return sb.toString(); } else { return self; } } public static String encodeSpecialSymbols(String text) { return Matcher.quoteReplacement(text.replaceAll("@", "&at;")); } public static String decodeSpecialSymbols(String text) { return text.replaceAll("&at;", "@"); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/OutputTool.java0000644001501200150120000000145311627206700026173 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; public interface OutputTool { void makeOutputArea(String filename); void writeToOutput(String fileName, String text) throws Exception; } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyExecutableMemberDoc.java0000644001501200150120000000367111627206700032260 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.util.*; import org.codehaus.groovy.groovydoc.*; public class SimpleGroovyExecutableMemberDoc extends SimpleGroovyMemberDoc implements GroovyExecutableMemberDoc { List parameters; public SimpleGroovyExecutableMemberDoc(String name, GroovyClassDoc belongsToClass) { super(name, belongsToClass); parameters = new ArrayList(); } public GroovyParameter[] parameters() { return (GroovyParameter[]) parameters.toArray(new GroovyParameter[parameters.size()]); } public void add(GroovyParameter parameter) { parameters.add(parameter); } public String flatSignature() {/*todo*/return null;} public boolean isNative() {/*todo*/return false;} public boolean isSynchronized() {/*todo*/return false;} public boolean isVarArgs() {/*todo*/return false;} // public GroovyParamTag[] paramTags() {/*todo*/return null;} public String signature() {/*todo*/return null;} public GroovyClassDoc[] thrownExceptions() {/*todo*/return null;} public GroovyType[] thrownExceptionTypes() {/*todo*/return null;} // public GroovyThrowsTag[] throwsTags() {/*todo*/return null;} // public GroovyTypeVariable[] typeParameters() {/*todo*/return null;} // public GroovyParamTag[] typeParamTags() {/*todo*/return null;} } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/FileOutputTool.java0000644001501200150120000000215111627206700026767 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.io.File; import org.codehaus.groovy.runtime.DefaultGroovyMethods; public class FileOutputTool implements OutputTool { public void makeOutputArea(String filename) { File dir = new File(filename); dir.mkdirs(); } public void writeToOutput(String fileName, String text) throws Exception { File file = new File(fileName); file.getParentFile().mkdirs(); DefaultGroovyMethods.write(file, text); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java0000644001501200150120000001135111707612046027146 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.io.File; import java.util.Iterator; import java.util.Properties; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import org.codehaus.groovy.groovydoc.GroovyRootDoc; import org.codehaus.groovy.tools.shell.util.Logger; /** * Write GroovyDoc resources to destination. */ public class GroovyDocWriter { private final Logger log = Logger.create(GroovyDocWriter.class); private GroovyDocTool tool; private OutputTool output; private GroovyDocTemplateEngine templateEngine; private static final String FS = "/"; private Properties properties; public GroovyDocWriter(GroovyDocTool tool, OutputTool output, GroovyDocTemplateEngine templateEngine, Properties properties) { this.tool = tool; this.output = output; this.templateEngine = templateEngine; this.properties = properties; } public void writeClasses(GroovyRootDoc rootDoc, String destdir) throws Exception { for (GroovyClassDoc classDoc : rootDoc.classes()) { writeClassToOutput(classDoc, destdir); } } public void writeClassToOutput(GroovyClassDoc classDoc, String destdir) throws Exception { if (classDoc.isPublic() || classDoc.isProtected() && "true".equals(properties.getProperty("protectedScope")) || classDoc.isPackagePrivate() && "true".equals(properties.getProperty("packageScope")) || "true".equals(properties.getProperty("privateScope"))) { String destFileName = destdir + FS + classDoc.getFullPathName() + ".html"; log.debug("Generating " + destFileName); String renderedSrc = templateEngine.applyClassTemplates(classDoc); output.writeToOutput(destFileName, renderedSrc); } } public void writePackages(GroovyRootDoc rootDoc, String destdir) throws Exception { for (GroovyPackageDoc packageDoc : rootDoc.specifiedPackages()) { if (new File(packageDoc.name()).isAbsolute()) continue; output.makeOutputArea(destdir + FS + packageDoc.name()); writePackageToOutput(packageDoc, destdir); } StringBuilder sb = new StringBuilder(); for (GroovyPackageDoc packageDoc : rootDoc.specifiedPackages()) { sb.append(packageDoc.nameWithDots()); sb.append("\n"); } String destFileName = destdir + FS + "package-list"; log.debug("Generating " + destFileName); output.writeToOutput(destFileName, sb.toString()); } public void writePackageToOutput(GroovyPackageDoc packageDoc, String destdir) throws Exception { Iterator templates = templateEngine.packageTemplatesIterator(); while (templates.hasNext()) { String template = templates.next(); String renderedSrc = templateEngine.applyPackageTemplate(template, packageDoc); String destFileName = destdir + FS + packageDoc.name() + FS + tool.getFile(template); log.debug("Generating " + destFileName); output.writeToOutput(destFileName, renderedSrc); } } public void writeRoot(GroovyRootDoc rootDoc, String destdir) throws Exception { output.makeOutputArea(destdir); writeRootDocToOutput(rootDoc, destdir); } public void writeRootDocToOutput(GroovyRootDoc rootDoc, String destdir) throws Exception { Iterator templates = templateEngine.docTemplatesIterator(); while (templates.hasNext()) { String template = templates.next(); String destFileName = destdir + FS + tool.getFile(template); log.debug("Generating " + destFileName); if (hasBinaryExtension(template)) { templateEngine.copyBinaryResource(template, destFileName); } else { String renderedSrc = templateEngine.applyRootDocTemplate(template, rootDoc); output.writeToOutput(destFileName, renderedSrc); } } } private boolean hasBinaryExtension(String template) { return template.endsWith(".gif") || template.endsWith(".ico"); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyTag.java0000644001501200150120000000235211627206700027127 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyTag; /** * Stores info about GroovyDoc tags. */ public class SimpleGroovyTag implements GroovyTag { private String name; private String param; private String text; public SimpleGroovyTag(String name, String param, String text) { this.name = name; this.param = param; this.text = text; } public String name() { return name; } public String param() { return param; } public String text() { return text; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/package.html0000644001501200150120000000022111627206700025443 0ustar miguelmiguel package org.codehaus.groovy.tools.groovydoc.*

      GroovyDoc tool.

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/0000755001501200150120000000000011627206700026523 5ustar miguelmiguel././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.javagroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.jav0000644001501200150120000000416611627206700033457 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc.gstringTemplates; public class GroovyDocTemplateInfo { private static final String TEMPLATE_BASEDIR = "org/codehaus/groovy/tools/groovydoc/gstringTemplates/"; private static final String DOCGEN_BASEDIR = "org/codehaus/groovy/tools/"; public static final String[] DEFAULT_DOC_TEMPLATES = new String[]{ // top level templates TEMPLATE_BASEDIR + "topLevel/index.html", TEMPLATE_BASEDIR + "topLevel/overview-frame.html", // needs all package names TEMPLATE_BASEDIR + "topLevel/allclasses-frame.html", // needs all packages / class names TEMPLATE_BASEDIR + "topLevel/overview-summary.html", // needs all packages TEMPLATE_BASEDIR + "topLevel/help-doc.html", TEMPLATE_BASEDIR + "topLevel/index-all.html", TEMPLATE_BASEDIR + "topLevel/deprecated-list.html", TEMPLATE_BASEDIR + "topLevel/stylesheet.css", // copy default one, may override later TEMPLATE_BASEDIR + "topLevel/inherit.gif", DOCGEN_BASEDIR + "groovy.ico", }; public static final String[] DEFAULT_PACKAGE_TEMPLATES = new String[]{ // package level templates TEMPLATE_BASEDIR + "packageLevel/package-frame.html", TEMPLATE_BASEDIR + "packageLevel/package-summary.html" }; public static final String[] DEFAULT_CLASS_TEMPLATES = new String[]{ // class level templates TEMPLATE_BASEDIR + "classLevel/classDocName.html" }; } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/0000755001501200150120000000000011627206700031106 5ustar miguelmiguel././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summ0000644001501200150120000001124511627206700033406 0ustar miguelmiguel <% def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } def title = packageDoc.nameWithDots() + (props.windowTitle ? " ($props.windowTitle)" : "") // TODO enable errors(), enums() etc in SimpleGroovyPackageDoc then replace closures below def classTypes = [ "Interface" : { it.isInterface() }, "Class" : { it.isClass() && !it.parentClasses*.qualifiedTypeName().contains('java.lang.Throwable') }, "Enum" : { it.isEnum() }, "Exception" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Exception') }, "Error" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Error') }, "Annotation Type" : { it.isAnnotationType() }, "Script" : { it.isScript() } ] %> ${title}
      <% if (props.header) { %>${props.header}<% } %>

      Package ${packageDoc.nameWithDots()}

      ${packageDoc.description()}

       

      <% classTypes.each{ k, v -> if (packageDoc.allClasses().any{ isVisible(it) && v(it) }) { %> <% for (classDoc in packageDoc.allClasses().findAll{ isVisible(it) && v(it) }) { %> <% } %>
      ${k} Summary
      ${classDoc.name()} ${classDoc.firstSentenceCommentText()}
       


      <% } %> <% } %>

      ${props['footer']?:""}


      ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-frame.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-fram0000644001501200150120000000377111627206700033357 0ustar miguelmiguel ${packageDoc.nameWithDots()} <% // TODO enable errors(), enums() etc in SimpleGroovyPackageDoc then replace closures below def classTypes = [ "Interface" : { it.isInterface() }, "Class" : { it.isClass() && !it.parentClasses*.qualifiedTypeName().contains('java.lang.Throwable') }, "Enum" : { it.isEnum() }, "Exception" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Exception') }, "Error" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Error') }, "Annotation Type" : { it.isAnnotationType() }, "Script" : { it.isScript() } ] def pluralize = { name -> name + (name.endsWith("s") ? "es" : "s") } %> ${packageDoc.nameWithDots()} <% def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } classTypes.each{ k, v -> if (packageDoc.allClasses().any{ isVisible(it) && v(it) }) { %>
      ${pluralize(k)}  <% for (classDoc in packageDoc.allClasses().findAll{ isVisible(it) && v(it) }) { %>
      <% if (classDoc.isInterface()) { %><% } %>${classDoc.name()}<% if (classDoc.isInterface()) { %><% } %><% } %>
      <% } %> <% } %> ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/packageDocStructuredData.xmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/packageDocSt0000644001501200150120000000021611627206700033360 0ustar miguelmiguel <% for (classDoc in packageDoc.allClasses()) { %> <% } %> groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/0000755001501200150120000000000011707612046030320 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index.html0000644001501200150120000000252411627206700032315 0ustar miguelmiguel {todo.title} <H2> Frame Alert</H2> <P> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/stylesheet.css0000644001501200150120000000226011627206700033220 0ustar miguelmiguel/* Groovydoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF } /* Headings */ h1 { font-size: 145% } /* Table colors */ .TableHeadingColor { background: #97D0E8 } /* Dark cyan */ .TableSubHeadingColor { background: #E0F0FF } /* Light cyan */ .TableRowColor { background: #FFFFFF } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif } .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif } .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#EEEEFF;} /* Light mauve */ .NavBarCell1Rev { background-color:#00008B;} /* Dark Blue */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;}././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.0000644001501200150120000001653011645141222033371 0ustar miguelmiguel <% def subtitle = 'Deprecated API' def title = subtitle + (props.windowTitle ? " (${props.windowTitle})" : "") // TODO enable errors(), enums() etc in SimpleGroovyPackageDoc then replace closures below def classTypes = [ "Interface" : { it.isInterface() && it.isDeprecated() }, "Class" : { it.isClass() && !it.parentClasses*.qualifiedTypeName().contains('java.lang.Throwable') && it.isDeprecated() }, "Enum" : { it.isEnum() && it.isDeprecated() }, "Exception" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Exception') && it.isDeprecated() }, "Error" : { it.isClass() && it.parentClasses*.qualifiedTypeName().contains('java.lang.Error') && it.isDeprecated() }, "Annotation Type" : { it.isAnnotationType() && it.isDeprecated() } ] // TODO fields, properties, enum constants def methodTypes = [ "Method" : { it.methods().findAll{ it.isDeprecated() } }, "Constructor" : { it.constructors().findAll{ it.isDeprecated() } }, ] def pluralize = { name -> name + (name.endsWith("s") ? "es" : "s") } def dolink = { t, classDoc, boolean b -> if (!t || t instanceof String) { return classDoc.getDocUrl(t, b) } if (t instanceof org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc) { return "" + (b ? t.qualifiedTypeName() : t.name()) + "" } return classDoc.getDocUrl(t.qualifiedTypeName(), b) } def linkable = { t, classDoc -> dolink(t, classDoc, false) } def modifiersBrief = { t -> (t.isPrivate()?"private ":"") + (t.isProtected()?"protected ":"") + (t.isStatic()?"static ":"") } def paramsOf = { n, classDoc, boolean brief -> n.parameters().collect{ param -> (brief?'':annotations(param, ' ')) + linkable(param.isTypeAvailable()?param.type():param.typeName(), classDoc) + ' ' + param.name() + (param.defaultValue() ? " = " + param.defaultValue():"") }.join(", ") } def nameFromParams = { n -> n.name() + '(' + n.parameters().collect{ param -> param.isTypeAvailable()?param.type().qualifiedTypeName():param.typeName() }.join(', ') + ')' } %> ${title}
      <% if (props.header) { %>${props.header}<% } %>

      Deprecated API


      <% def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } classTypes.each{ k, v -> if (rootDoc.classes().any{ isVisible(it) && v(it) }) { %> <% for (classDoc in rootDoc.classes().findAll{ isVisible(it) && v(it) }) { def packageOrInnerName = classDoc.qualifiedTypeName() - ('.' + classDoc.simpleTypeName()) %><% } %>
      ${pluralize(k)}
      <% if (classDoc.isInterface()) { %><% } %>${classDoc.name()}<% if (classDoc.isInterface()) { %><% } %>
            ${classDoc.firstSentenceCommentText()}

      <% } %> <% } %> <% methodTypes.each{ k, v -> if (rootDoc.classes().any{ isVisible(it) && v(it) }) { %> <% for (classDoc in rootDoc.classes().findAll{ isVisible(it) && v(it) }) { for (methOrConstr in v(classDoc)) { %><% } } %>
      ${pluralize(k)}
      ${classDoc.name()}#${methOrConstr.name()}(${paramsOf(methOrConstr, classDoc, true)})
            ${methOrConstr.firstSentenceCommentText()}

      <% } %> <% } %>

      ${props['footer']?:""}


      groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html0000644001501200150120000001675011707612046032712 0ustar miguelmiguel <% def subtitle = 'API Help' %> <% def title = subtitle + (props.windowTitle ? " (${props.windowTitle})" : "") %> ${title}
      <% if (props.header) { %>${props.header}<% } %>

      How This API Document Is Organized

      This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

      Overview

      The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

      Package

      Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

      • Interfaces (italic)
      • Classes
      • Enums
      • Exceptions
      • Errors
      • Annotation Types

      Class/Interface

      Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

      • Class inheritance diagram
      • Direct Subclasses
      • All Known Subinterfaces
      • All Known Implementing Classes
      • Class/interface declaration
      • Class/interface description

      • Nested Class Summary
      • Field Summary
      • Constructor Summary
      • Method Summary

      • Field Detail
      • Constructor Detail
      • Method Detail
      Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

      Annotation Type

      Each annotation type has its own separate page with the following sections:

      • Annotation Type declaration
      • Annotation Type description
      • Required Element Summary
      • Optional Element Summary
      • Element Detail

      Enum

      Each enum has its own separate page with the following sections:

      • Enum declaration
      • Enum description
      • Enum Constant Summary
      • Enum Constant Detail

      Tree (Class Hierarchy)

      There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
      • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
      • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

      Deprecated API

      The Deprecated API page lists all of the parts of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

      Index

      The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

      Prev/Next

      These links take you to the next or previous class, interface, package, or related page.

      Frames/No Frames

      These links show and hide the HTML frames. All pages are available with or without frames.

      Constant Field Values

      The Constant Field Values page lists the static final fields and their values.

      This help file applies to API documentation generated using the standard doclet.


      ${props['footer']?:""}


      ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame0000644001501200150120000000245211627206700033461 0ustar miguelmiguel All Classes All Classes
      <% def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } for (classDoc in rootDoc.classes().findAll(isVisible)) { def packageOrInnerName = classDoc.qualifiedTypeName() - ('.' + classDoc.simpleTypeName()) %>${classDoc.isInterface()?'':''}${classDoc.name()}${classDoc.isInterface()?'':''}
      <% } %>
      ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.h0000644001501200150120000000175611627206700033435 0ustar miguelmiguel Overview ${props.docTitle ? ("(" + props.docTitle + ")") : ""}
      ${props.docTitle}
      All Classes

      Packages
      <% for (packageDoc in rootDoc.specifiedPackages()) { %> ${packageDoc.nameWithDots()}
      <% } %>

        ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/rootDocStructuredData.xmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/rootDocStructure0000644001501200150120000000045011627206700033571 0ustar miguelmiguel <% for (packageDoc in rootDoc.specifiedPackages()) { %> <% } %> <% for (classDoc in rootDoc.classes()) { %> <% } %> groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html0000644001501200150120000001452411645141222033063 0ustar miguelmiguel <% def subtitle = 'Index' def title = subtitle + (props.windowTitle ? " (${props.windowTitle})" : "") def letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_' as char[] def elementTypes = [ "Method" : { it.methods() }, "Constructor" : { it.constructors() }, "Field" : { it.fields() }, "Property" : { it.properties() }, "Enum Constant" : { it.enumConstants() }, ] def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } def paramsOf = { n, classDoc, boolean brief -> n.parameters().collect{ param -> param.isTypeAvailable()?param.type().name():param.typeName() }.join(", ") } def nameFromParams = { n -> n.name() + '(' + n.parameters().collect{ param -> param.isTypeAvailable()?param.type().qualifiedTypeName():param.typeName() }.join(', ') + ')' } %> ${title}


      <% if (props.header) { %>${props.header}<% } %>
      <% letters.each { letter -> %> ${letter} <% } %> <% letters.each { letter -> def entries = [] as TreeMap def upperLower = "$letter${letter.toLowerCase()}" for (classDoc in rootDoc.classes()) { def classLower = classDoc.name().toLowerCase() if (isVisible(classDoc) && upperLower.contains(classDoc.name()[0])) { def packageOrInnerName = classDoc.qualifiedTypeName() - ('.' + classDoc.simpleTypeName()) def packageName = classDoc.qualifiedTypeName() - ('.' + classDoc.name()) def desc = classDoc.typeDescription + ' in ' entries[classLower] = """
      ${classDoc.name()} - ${desc}${packageName}
      ${classDoc.firstSentenceCommentText()}
      """ } elementTypes.each { k, v -> def elements = v(classDoc) elements.each { e -> if (isVisible(e) && upperLower.contains(e.name()[0])) { def packageOrInnerName = classDoc.qualifiedTypeName() - ('.' + classDoc.simpleTypeName()) def packageName = classDoc.qualifiedTypeName() - ('.' + classDoc.name()) def desc = k + ' in ' switch (k) { case 'Method': case 'Constructor': entries[e.name().toLowerCase()+'_'+classLower] = """
      ${e.name()}(${paramsOf(e, classDoc, true)}) - ${desc}${classDoc.name()}
      ${e.firstSentenceCommentText()}
      """ break case 'Field': case 'Property': case 'Enum Constant': entries[e.name().toLowerCase()+'_'+classLower] = """
      ${e.name()} - ${desc}${classDoc.name()}
      ${e.firstSentenceCommentText()}
      """ break } } } } } %>

      ${letter}

      <% entries.each{ k, v -> %>${v}<% } %>
      <% } %>

      ${props['footer']?:""}


      groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/inherit.gif0000644001501200150120000000007111627206700032444 0ustar miguelmiguelGIF89a, DrjԐ;߀Q@N;././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary0000644001501200150120000000721211627206700033603 0ustar miguelmiguel <% def title = "Overview" + (props.windowTitle ? " (${props.windowTitle})" : "") %> ${title}
      <% if (props.header) { %>${props.header}<% } %>

      ${props.docTitle ?: ''}

      ${rootDoc.summary()}

      <% def s = rootDoc.summary().trim() def d = rootDoc.description().trim() if (d && d != s) { %> See:
                Description

      <% } %> <% for (packageDoc in rootDoc.specifiedPackages()) { %> <% } %>
      Packages
      ${packageDoc.nameWithDots()} ${packageDoc.summary() ?: ''}

      <% if (d && d != s) { %>  

      ${rootDoc.description()}


      <% } %>

      ${props['footer']?:""}


      groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/0000755001501200150120000000000011707612046030623 5ustar miguelmiguel././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocStructuredData.xmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocStruct0000644001501200150120000000257611627206700033515 0ustar miguelmiguel ${classDoc.containingPackage().nameWithDots()} ${classDoc.superclass()?.name()} <% for (interfaceDoc in classDoc.interfaces()) { %> ${interfaceDoc.name()} <% } %> ${classDoc.commentText()} <% for (constructor in classDoc.constructors()) { %> <% for (parameter in constructor.parameters()) { %> <% } %> ${constructor.commentText()} <% } %> <% for (method in classDoc.methods()) { %> <% for (parameter in method.parameters()) { %> <% } %> ${method.commentText()} <% } %> ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.htmlgroovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.h0000644001501200150120000006331011707612046033333 0ustar miguelmiguel <% def title = classDoc.name() + (props.docTitle ? " (${props.docTitle})" : "") def isVisible = { it.isPublic() || (it.isProtected() && props.protectedScope == 'true') || (!it.isProtected() && !it.isPrivate() && props.packageScope == 'true') || props.privateScope == 'true' } def isVisibleExt = { t -> java.lang.reflect.Modifier.isPublic(t.modifiers) || java.lang.reflect.Modifier.isProtected(t.modifiers) } def visibleFields = classDoc.fields().findAll(isVisible) def visibleProperties = classDoc.properties() // props visible be defn def visibleMethods = classDoc.methods().findAll(isVisible) def visibleConstructors = classDoc.constructors().findAll(isVisible) def visibleNested = classDoc.innerClasses().findAll(isVisible) boolean hasFields = !classDoc.isAnnotationType() && visibleFields boolean hasProperties = !classDoc.isAnnotationType() && visibleProperties boolean hasElements = classDoc.isAnnotationType() && visibleFields boolean methodSummaryShown = visibleMethods boolean fieldSummaryShown = hasFields boolean hasEnumConstants = classDoc.enumConstants().findAll(isVisible) def dolink = { t, boolean b -> boolean isArray = false if (!t || t instanceof String) { return classDoc.getDocUrl(t, b) } if (t instanceof org.codehaus.groovy.tools.groovydoc.ArrayClassDocWrapper) { t = t.delegate isArray = true } if (t instanceof org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc) { if (t.fullPathName == 'def') return classDoc.getDocUrl("java.lang.Object def", b) return "" + (b ? t.qualifiedTypeName() : t.name()) + "" + (isArray ? "[]" : "") } return classDoc.getDocUrl(t.qualifiedTypeName(), b) + (isArray ? "[]" : "") } def linkfull = { t -> dolink(t, true) } def linkable = { t -> dolink(t, false) } def modifiersWithIgnore = { t, boolean ignorePublic -> (t.isPrivate()?"private ":"") + (t.isPublic() && !ignorePublic?"public ":"") + (t.isProtected()?"protected ":"") + (t.isStatic()?"static ":"") + (t.isFinal()?"final ":"") + (t.respondsTo('isAbstract') && t.isAbstract()?"abstract ":"") } def modifiers = { t -> modifiersWithIgnore(t, classDoc.isGroovy()) } def modifiersBrief = { t -> (t.isPrivate()?"private ":"") + (t.isProtected()?"protected ":"") + (t.isStatic()?"static ":"") } def annotations = { t, sepChar -> t.annotations() ? t.annotations()*.description().join(sepChar) + sepChar : '' } def elementTypes = [ "required":"true", "optional":"false" ] def isRequired = { f, v -> def req = f.constantValueExpression() == null; req.toString() == v } def upcase = { n -> n[0].toUpperCase() + n[1..-1] } def paramsOf = { n, boolean brief -> n.parameters().collect{ param -> (brief?'':annotations(param, ' ')) + linkable(param.isTypeAvailable()?param.type():param.typeName()) + (param.vararg()?'... ':' ') + param.name() + (param.defaultValue() ? " = " + param.defaultValue():"") }.join(", ") } def nameFromParams = { n -> n.name() + '(' + n.parameters().collect{ param -> param.isTypeAvailable()?param.type().qualifiedTypeName():param.typeName() }.join(', ') + ')' } def nameFromJavaParams = { n -> n.name + '(' + n.parameterTypes.collect{ param -> param.name }.join(', ') + ')' } %> ${title}
      <% if (props.header) { %>${props.header}<% } %>

      <% def pkg = classDoc.containingPackage().nameWithDots() if (pkg != "DefaultPackage") { %> ${pkg}
      <% } %> ${classDoc.isGroovy() ? "[Groovy]" : "[Java]"} ${classDoc.typeDescription} ${classDoc.name()}

      <% def parents = classDoc.isInterface() ? classDoc.parentInterfaces : classDoc.parentClasses if (parents.size() >= 2) { %>
      <%
          parents.eachWithIndex { p, i ->
              %>${(i > 0 ? "  " * i + "  " * (i - 1) + "" : "") + ( i == parents.size() - 1 ? p.qualifiedTypeName() : linkfull(p))}\n<%
          }
          %>
      <% } if (classDoc.isInterface()) { Set interfaces = classDoc.parentInterfaces interfaces -= classDoc if (interfaces) { %>
      All Superinterfaces:
      ${interfaces.collect{ linkable(it) }.join(', ')}
      <% } } else { // TODO follow up the tree collecting interfaces seen? def interfaces = classDoc.interfaces() if (interfaces) { %>
      All Implemented Interfaces:
      ${interfaces.collect{ linkable(it) }.join(', ')}
      <% } } %>
      ${annotations(classDoc, '\n') + modifiers(classDoc) + classDoc.typeSourceDescription + ' ' + classDoc.name()}
      <% if (classDoc.isInterface() && classDoc.interfaces()) {
      %>extends ${classDoc.interfaces().collect{ linkable(it) }.join(', ')}
      <% } else if (classDoc.superclass()) {
      %>extends ${linkable(classDoc.superclass())}
      <% } %>
      
      <% if (classDoc.commentText()) { %>

      ${classDoc.commentText()}


      <% } %> <% if (visibleNested) { %> <% for (c in visibleNested) { %> <% } %>
      Nested Class Summary
      ${modifiersBrief(c) + c.typeSourceDescription} ${linkable(c)}

      ${c.firstSentenceCommentText()}

        <% } %> <% if (hasEnumConstants) { %> <% for (ec in classDoc.enumConstants().findAll(isVisible)) { %> <% } %>
      Enum Constant Summary
      ${ec.name()}

      ${ec.firstSentenceCommentText()}

        <% } %> <% if (hasFields) { %> <% for (field in visibleFields) { %> <% } %>
      Field Summary
      ${modifiersBrief(field) + linkable(field.type())} ${field.name()}

      ${field.firstSentenceCommentText()}

        <% } classes = [] if (classDoc.isInterface()) { classes.addAll(classDoc.interfaces().toList()) } else { if (classDoc.superclass()) classes += classDoc.superclass() else classes += new org.codehaus.groovy.tools.groovydoc.ExternalGroovyClassDoc(Object.class) } visited = [classDoc] as Set while (classes) { Set nextLevel = [] classes.each { c -> if (c.isInterface()) nextLevel.addAll(c.interfaces().toList()) else if (c.superclass() && c.qualifiedTypeName() != 'java.lang.Object') nextLevel += c.superclass() nextLevel -= visited visited += nextLevel def list = [] if (c instanceof org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc) { list = c.fields().findAll(isVisible).collect { field -> "${field.name()}" } } else { list = c.externalClass().fields.findAll{ isVisibleExt(it) }.collect { field -> // "${field.name()}" field.name } } if (list) { if (!fieldSummaryShown) { fieldSummaryShown = true %>
      Field Summary
       <% } %>
      Fields inherited from ${c.typeSourceDescription} ${linkable(c)}
      ${list.join(', ')}
       <% } } classes = nextLevel } %> <% if (hasProperties) { %> <% for (prop in visibleProperties) { %> <% } %>
      Property Summary
      ${modifiersBrief(prop) + linkable(prop.type())} ${prop.name()}

      ${prop.firstSentenceCommentText()}

        <% } %> <% if (hasElements) { %> <% elementTypes.each { k, v -> %> <% if (visibleFields.any{ isRequired(it, v) }) { %> <% for (element in visibleFields) { %> <% if (isRequired(element, v)) { %> <% } %> <% } %>
      ${upcase(k)} Element Summary
      ${modifiersBrief(element) + element.type().typeName()} ${element.name()}

      ${element.firstSentenceCommentText()}

      <% } %>   <% } %> <% } %> <% if (visibleConstructors) { %> <% for (constructor in visibleConstructors) { %> <% } %>
      Constructor Summary
      ${modifiersBrief(constructor)}${constructor.name()}(${paramsOf(constructor, true)})

      ${constructor.firstSentenceCommentText()}

        <% } %> <% if (visibleMethods) { %> <% for (method in visibleMethods) { %> <% } %>
      Method Summary
      ${modifiersBrief(method)}${linkable(method.returnType())} ${method.name()}(${paramsOf(method, true)})

      ${method.firstSentenceCommentText()}

        <% } Set classes = [] if (classDoc.isInterface()) { classes.addAll(classDoc.interfaces().toList()) } else { if (classDoc.superclass()) classes += classDoc.superclass() else classes += new org.codehaus.groovy.tools.groovydoc.ExternalGroovyClassDoc(Object.class) } Set visited = [classDoc] as Set while (classes) { Set nextLevel = [] classes.each { c -> if (c.isInterface()) nextLevel.addAll(c.interfaces().toList()) else if (c.superclass() && c.qualifiedTypeName() != 'java.lang.Object') nextLevel += c.superclass() nextLevel -= visited visited += nextLevel def list = [] if (c instanceof org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc) { list = c.methods().findAll(isVisible).collect { method -> "${method.name()}" } } else { list = c.externalClass().methods.findAll{ isVisibleExt(it) }.collect { method -> linkable(c.externalClass().name + "#" + nameFromJavaParams(method) + " " + method.name) } } if (list) { if (!methodSummaryShown) { methodSummaryShown = true %>
      Method Summary
       <% } %>
      Methods inherited from ${c.typeSourceDescription} ${linkable(c)}
      ${list.join(', ')}
       <% } } classes = nextLevel } %>

      <% if (hasEnumConstants) { %>
      Enum Constant Detail
      <% for (ec in classDoc.enumConstants()) { %>

      ${ec.name()}

      ${modifiers(ec) + '' + classDoc.name() + ''} ${ec.name()}
      ${ec.commentText()}


      <% } %>   <% } %> <% if (hasFields) { %>
      Field Detail
      <% for (field in visibleFields) { %>

      ${field.name()}

      ${annotations(field, '\n') + modifiersWithIgnore(field, false) + linkable(field.type())} ${field.name()}
      ${field.commentText()}


      <% } %>   <% } %> <% if (hasProperties) { %>
      Property Detail
      <% for (prop in visibleProperties) { %>

      ${prop.name()}

      ${annotations(prop, '\n') + modifiers(prop) + linkable(prop.type())} ${prop.name()}
      ${prop.commentText()}


      <% } %>   <% } %> <% if (hasElements) { %>
      Element Detail
      <% for (element in visibleFields) { %>

      ${element.name()}

      ${modifiers(element) + linkable(element.type())} ${element.name()}
      ${element.commentText()}


      <% } %>   <% } %> <% if (visibleConstructors) { %>
      Constructor Detail
      <% for (constructor in visibleConstructors) { %>

      ${constructor.name()}

      ${annotations(constructor, '\n') + modifiers(constructor)}${constructor.name()}(${paramsOf(constructor, false)})
      ${constructor.commentText()}


      <% } %>   <% } %> <% if (visibleMethods) { %>
      Method Detail
      <% for (method in visibleMethods) { %>

      ${method.name()}

      ${annotations(method, '\n') + modifiers(method)}${linkable(method.returnType())} ${method.name()}(${paramsOf(method, false)})
      ${method.commentText()}


      <% } %>   <% } %>

      ${props['footer']?:""}


      groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyFieldDoc.java0000644001501200150120000000331611627206700030066 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyFieldDoc; import org.codehaus.groovy.groovydoc.GroovyType; import org.codehaus.groovy.groovydoc.GroovyClassDoc; public class SimpleGroovyFieldDoc extends SimpleGroovyMemberDoc implements GroovyFieldDoc { private GroovyType type; private String constantValueExpression; public SimpleGroovyFieldDoc(String name, GroovyClassDoc belongsToClass) { super(name, belongsToClass); } public Object constantValue() {/*todo*/return null;} public void setConstantValueExpression(String constantValueExpression) { this.constantValueExpression = constantValueExpression; } public String constantValueExpression() { return constantValueExpression; } public boolean isTransient() {/*todo*/return false;} public boolean isVolatile() {/*todo*/return false;} // public GroovySerialFieldTag[] serialFieldTags() {/*todo*/return null;} public GroovyType type() { return type; } public void setType(GroovyType type) { this.type = type; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyPackageDoc.java0000644001501200150120000001141711627206700030377 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class SimpleGroovyPackageDoc extends SimpleGroovyDoc implements GroovyPackageDoc { private static final char FS = '/'; final Map classDocs; private String description = ""; private String summary = ""; public SimpleGroovyPackageDoc(String name) { super(name); classDocs = new TreeMap(); } public GroovyClassDoc[] allClasses() { return classDocs.values().toArray(new GroovyClassDoc[classDocs.values().size()]); } public void setDescription(String description) { this.description = description; } public void setSummary(String summary) { this.summary = summary; } public void putAll(Map classes) { // 2 way relationship for visible classes: // add reference to classes inside this package // add reference to this package inside classes for (Map.Entry docEntry : classes.entrySet()) { final GroovyClassDoc classDoc = docEntry.getValue(); classDocs.put(docEntry.getKey(), classDoc); SimpleGroovyProgramElementDoc programElement = (SimpleGroovyProgramElementDoc) classDoc; programElement.setContainingPackage(this); } } public String nameWithDots() { return name().replace(FS, '.'); } public GroovyClassDoc[] allClasses(boolean arg0) { List classDocValues = new ArrayList(classDocs.values()); return classDocValues.toArray(new GroovyClassDoc[classDocValues.size()]); } public GroovyClassDoc[] enums() { List result = new ArrayList(classDocs.values().size()); for (GroovyClassDoc doc : classDocs.values()) { if (doc.isEnum()) { result.add(doc); } } return result.toArray(new GroovyClassDoc[result.size()]); } public GroovyClassDoc[] errors() { List result = new ArrayList(classDocs.values().size()); for (GroovyClassDoc doc : classDocs.values()) { if (doc.isError()) { result.add(doc); } } return result.toArray(new GroovyClassDoc[result.size()]); } public GroovyClassDoc[] exceptions() { List result = new ArrayList(classDocs.values().size()); for (GroovyClassDoc doc : classDocs.values()) { if (doc.isException()) { result.add(doc); } } return result.toArray(new GroovyClassDoc[result.size()]); } public GroovyClassDoc findClass(String arg0) {/*todo*/ return null; } public GroovyClassDoc[] interfaces() { List result = new ArrayList(classDocs.values().size()); for (GroovyClassDoc doc : classDocs.values()) { if (doc.isInterface()) { result.add(doc); } } return result.toArray(new GroovyClassDoc[result.size()]); } public GroovyClassDoc[] ordinaryClasses() { List result = new ArrayList(classDocs.values().size()); for (GroovyClassDoc doc : classDocs.values()) { if (doc.isOrdinaryClass()) { result.add(doc); } } return result.toArray(new GroovyClassDoc[result.size()]); } public String description() { return description; } public String summary() { return summary; } public String getRelativeRootPath() { StringTokenizer tokenizer = new StringTokenizer(name(), "" + FS); StringBuffer sb = new StringBuffer(); while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); sb.append("../"); } return sb.toString(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java0000644001501200150120000001030211707612046026602 0ustar miguelmiguel/* * Copyright 2007-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import antlr.RecognitionException; import antlr.TokenStreamException; import org.codehaus.groovy.groovydoc.GroovyRootDoc; import org.codehaus.groovy.tools.shell.util.Logger; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @author Jeremy Rayner */ public class GroovyDocTool { private final Logger log = Logger.create(GroovyDocTool.class); private final GroovyRootDocBuilder rootDocBuilder; private final GroovyDocTemplateEngine templateEngine; private Properties properties; /** * Constructor for use by people who only want to interact with the Groovy Doclet Tree (rootDoc) * * @param sourcepaths where the sources to be added can be found */ public GroovyDocTool(String[] sourcepaths) { this(null, sourcepaths, null); } public GroovyDocTool(ResourceManager resourceManager, String[] sourcepaths, String classTemplate) { this(resourceManager, sourcepaths, new String[]{}, new String[]{}, new String[]{classTemplate}, new ArrayList(), new Properties()); } public GroovyDocTool(ResourceManager resourceManager, String[] sourcepaths, String[] docTemplates, String[] packageTemplates, String[] classTemplates, List links, Properties properties) { rootDocBuilder = new GroovyRootDocBuilder(this, sourcepaths, links, properties); this.properties = properties; if (resourceManager == null) { templateEngine = null; } else { templateEngine = new GroovyDocTemplateEngine(this, resourceManager, docTemplates, packageTemplates, classTemplates, properties); } } public void add(List filenames) throws RecognitionException, TokenStreamException, IOException { if (templateEngine != null) { // only print out if we are being used for template generation log.debug("Loading source files for " + filenames); } rootDocBuilder.buildTree(filenames); } public GroovyRootDoc getRootDoc() { return rootDocBuilder.getRootDoc(); } public void renderToOutput(OutputTool output, String destdir) throws Exception { // expect just one scope to be set on the way in but now also set higher levels of visibility if ("true".equals(properties.getProperty("privateScope"))) properties.setProperty("packageScope", "true"); if ("true".equals(properties.getProperty("packageScope"))) properties.setProperty("protectedScope", "true"); if ("true".equals(properties.getProperty("protectedScope"))) properties.setProperty("publicScope", "true"); if (templateEngine != null) { GroovyDocWriter writer = new GroovyDocWriter(this, output, templateEngine, properties); GroovyRootDoc rootDoc = rootDocBuilder.getRootDoc(); writer.writeRoot(rootDoc, destdir); writer.writePackages(rootDoc, destdir); writer.writeClasses(rootDoc, destdir); } else { throw new UnsupportedOperationException("No template engine was found"); } } String getPath(String filename) { String path = new File(filename).getParent(); // path length of 1 indicates that probably is 'default package' i.e. "/" if (path == null || path.length() == 1) { path = "DefaultPackage"; // "DefaultPackage" for 'default package' path, rather than null... } return path; } String getFile(String filename) { return new File(filename).getName(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/Main.groovy0000644001501200150120000002341111645141222025320 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc import org.codehaus.groovy.tools.shell.util.Logger import org.codehaus.groovy.tools.shell.util.MessageSource import org.codehaus.groovy.tools.shell.IO import org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo import groovy.io.FileType /** * Main CLI entry-point for groovydoc. * * @author Paul King */ class Main { private static final MessageSource messages = new MessageSource(Main) private static File styleSheetFile; private static File overviewFile private static File destDir private static String windowTitle private static String docTitle private static String header private static String footer private static Boolean author private static Boolean noScripts private static Boolean noMainForScripts private static Boolean privateScope private static Boolean packageScope private static Boolean publicScope private static Boolean protectedScope private static Boolean debug = false private static String[] sourcepath private static List sourceFilesToDoc private static List remainingArgs private static List exclusions static void main(final String[] args) { IO io = new IO() Logger.io = io def cli = new CliBuilder(usage : 'groovydoc [options] [packagenames] [sourcefiles]', writer: io.out, posix:false) cli.help(longOpt: 'help', messages['cli.option.help.description']) cli._(longOpt: 'version', messages['cli.option.version.description']) cli.verbose(messages['cli.option.verbose.description']) cli.quiet(messages['cli.option.quiet.description']) // TODO is debug needed? cli._(longOpt: 'debug', messages['cli.option.debug.description']) cli.classpath(messages['cli.option.classpath.description']) cli.cp(longOpt: 'classpath', messages['cli.option.cp.description']) cli.d(longOpt: 'destdir', args:1, argName: 'dir', messages['cli.option.destdir.description']) cli.author(messages['cli.option.author.description']) cli.noscripts(messages['cli.option.noscripts.description']) cli.nomainforscripts(messages['cli.option.nomainforscripts.description']) cli.overview(args:1, argName: 'file', messages['cli.option.overview.description']) cli.public(messages['cli.option.public.description']) cli.protected(messages['cli.option.protected.description']) cli.package(messages['cli.option.package.description']) cli.private(messages['cli.option.private.description']) cli.windowtitle(args:1, argName: 'text', messages['cli.option.windowtitle.description']) cli.doctitle(args:1, argName: 'html', messages['cli.option.doctitle.description']) cli.header(args:1, argName: 'html', messages['cli.option.header.description']) cli.footer(args:1, argName: 'html', messages['cli.option.footer.description']) cli.exclude(args:1, argName: 'pkglist', messages['cli.option.exclude.description']) cli.stylesheetfile(args:1, argName: 'path', messages['cli.option.stylesheetfile.description']) cli.sourcepath(args:1, argName: 'pathlist', messages['cli.option.sourcepath.description']) def options = cli.parse(args) if (options.help) { cli.usage() return } if (options.version) { io.out.println(messages.format('cli.info.version', GroovySystem.version)) return } if (options.stylesheetfile) { styleSheetFile = new File(options.stylesheetfile) } if (options.overview) { overviewFile = new File(options.overview) } destDir = new File(options.d ?: '.') if (options.exclude) { exclusions = options.exclude.tokenize(':') } if (options.sourcepath) { def list = [] options.sourcepaths.each { list.addAll(it.tokenize(File.pathSeparator)) } sourcepath = list.toArray() } author = Boolean.valueOf(options.author) ?: false noScripts = Boolean.valueOf(options.noscripts) ?: false noMainForScripts = Boolean.valueOf(options.nomainforscripts) ?: false packageScope = Boolean.valueOf(options.package) ?: false privateScope = Boolean.valueOf(options.private) ?: false protectedScope = Boolean.valueOf(options.protected) ?: false publicScope = Boolean.valueOf(options.public) ?: false int scopeCount = 0 if (packageScope) scopeCount++ if (privateScope) scopeCount++ if (protectedScope) scopeCount++ if (publicScope) scopeCount++ if (scopeCount == 0) { protectedScope = true } else if (scopeCount > 1) { System.err.println "groovydoc: Error - More than one of -public, -private, -package, or -protected specified." cli.usage() return } windowTitle = options.windowtitle ?: '' docTitle = options.doctitle ?: '' header = options.header ?: '' footer = options.footer ?: '' if (options.Ds) { def values = options.Ds values.each { setSystemProperty(it as String) } } if (options.verbose) { io.verbosity = IO.Verbosity.VERBOSE } if (options.debug) { io.verbosity = IO.Verbosity.DEBUG debug = true } if (options.quiet) { io.verbosity = IO.Verbosity.QUIET } remainingArgs = options.arguments() if (!remainingArgs) { System.err.println "groovydoc: Error - No packages or classes specified." cli.usage() return } execute() } static void execute() { Properties properties = new Properties() properties.put("windowTitle", windowTitle) properties.put("docTitle", docTitle) properties.put("footer", footer) properties.put("header", header) properties.put("privateScope", privateScope.toString()) properties.put("protectedScope", protectedScope.toString()) properties.put("publicScope", publicScope.toString()) properties.put("packageScope", packageScope.toString()) properties.put("author", author.toString()) properties.put("processScripts", (!noScripts).toString()) properties.put("includeMainForScripts", (!noMainForScripts).toString()) properties.put("overviewFile", overviewFile?.absolutePath ?: "") def links = new ArrayList(); collectSourceFileNames(remainingArgs, sourcepath, exclusions) GroovyDocTool htmlTool = new GroovyDocTool( new ClasspathResourceManager(), // we're gonna get the default templates out of the dist jar file sourcepath, GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES, GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES, GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES, links, properties ) htmlTool.add(sourceFilesToDoc) FileOutputTool output = new FileOutputTool() htmlTool.renderToOutput(output, destDir.canonicalPath) // try to override the default stylesheet with custom specified one if needed if (styleSheetFile != null) { try { new File(destDir, "stylesheet.css").text = styleSheetFile.text } catch (IOException e) { println "Warning: Unable to copy specified stylesheet '" + styleSheetFile.absolutePath + "'. Using default stylesheet instead. Due to: " + e.message } } } static collectSourceFileNames(List remainingArgs, String[] sourceDirs, List exclusions) { sourceFilesToDoc = [] remainingArgs.each { String pkgOrFile -> if (pkgOrFile in exclusions) return File srcFile = new File(pkgOrFile) if (srcFile.exists() && srcFile.isFile()) { sourceFilesToDoc << pkgOrFile return } sourceDirs.each { dirStr -> def dir = new File(dirStr) def pkgOrFileSlashes = pkgOrFile.replace(".", "/") def candidate = new File(dir, pkgOrFile); if (candidate.exists() && candidate.isFile()) { // assume it is some kind of file sourceFilesToDoc << pkgOrFile } candidate = new File(dir, pkgOrFileSlashes); if (candidate.exists() && candidate.isDirectory()) { // TODO handle other extensions too, make configurable candidate.eachFileMatch(FileType.FILES, ~/.*\.(?:groovy|java)/) { File f -> sourceFilesToDoc << pkgOrFileSlashes + "/" + f.getName() } } } } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/ExternalGroovyClassDoc.java0000644001501200150120000001507011627206700030441 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; import java.util.ArrayList; import java.util.List; /** * Represents a class not in the codebase being processed. */ public class ExternalGroovyClassDoc implements GroovyClassDoc { private Class externalClass; private final List annotationRefs; public ExternalGroovyClassDoc(Class externalClass) { this.externalClass = externalClass; annotationRefs = new ArrayList(); } public boolean isPrimitive() { return externalClass.isPrimitive(); } public GroovyAnnotationRef[] annotations() { return annotationRefs.toArray(new GroovyAnnotationRef[annotationRefs.size()]); } public String qualifiedTypeName() { return externalClass.getName(); } public GroovyClassDoc superclass() { Class aClass = externalClass.getSuperclass(); if (aClass != null) return new ExternalGroovyClassDoc(aClass); return new ExternalGroovyClassDoc(Object.class); } public Class externalClass() { return externalClass; } public String getTypeSourceDescription() { return externalClass.isInterface() ? "interface" : "class"; } public String simpleTypeName() { return qualifiedTypeName(); // TODO fix } public String typeName() { return qualifiedTypeName(); // TODO fix } @Override public int hashCode() { return qualifiedTypeName().hashCode(); } @Override public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (!(other instanceof ExternalGroovyClassDoc)) return false; return qualifiedTypeName().equals(((ExternalGroovyClassDoc)other).qualifiedTypeName()); } // TODO implement below if/when needed public GroovyType superclassType() { return null; } public GroovyConstructorDoc[] constructors() { return new GroovyConstructorDoc[0]; } public GroovyConstructorDoc[] constructors(boolean filter) { return new GroovyConstructorDoc[0]; } public boolean definesSerializableFields() { return false; } public GroovyFieldDoc[] enumConstants() { return new GroovyFieldDoc[0]; } public GroovyFieldDoc[] fields() { return new GroovyFieldDoc[0]; } public GroovyFieldDoc[] properties() { return new GroovyFieldDoc[0]; } public GroovyFieldDoc[] fields(boolean filter) { return new GroovyFieldDoc[0]; } public GroovyClassDoc findClass(String className) { return null; } public GroovyClassDoc[] importedClasses() { return new GroovyClassDoc[0]; } public GroovyPackageDoc[] importedPackages() { return new GroovyPackageDoc[0]; } public GroovyClassDoc[] innerClasses() { return new GroovyClassDoc[0]; } public GroovyClassDoc[] innerClasses(boolean filter) { return new GroovyClassDoc[0]; } public GroovyClassDoc[] interfaces() { return new GroovyClassDoc[0]; } public GroovyType[] interfaceTypes() { return new GroovyType[0]; } public boolean isAbstract() { return false; } public boolean isExternalizable() { return false; } public boolean isSerializable() { return false; } public GroovyMethodDoc[] methods() { return new GroovyMethodDoc[0]; } public GroovyMethodDoc[] methods(boolean filter) { return new GroovyMethodDoc[0]; } public GroovyFieldDoc[] serializableFields() { return new GroovyFieldDoc[0]; } public GroovyMethodDoc[] serializationMethods() { return new GroovyMethodDoc[0]; } public boolean subclassOf(GroovyClassDoc gcd) { return false; } public String getFullPathName() { return null; } public String getRelativeRootPath() { return null; } public GroovyClassDoc containingClass() { return null; } public GroovyPackageDoc containingPackage() { return null; } public boolean isFinal() { return false; } public boolean isPackagePrivate() { return false; } public boolean isPrivate() { return false; } public boolean isProtected() { return false; } public boolean isPublic() { return false; } public boolean isStatic() { return false; } public String modifiers() { return null; } public int modifierSpecifier() { return 0; } public String qualifiedName() { return null; } public String commentText() { return null; } public String getRawCommentText() { return null; } public boolean isAnnotationType() { return false; } public boolean isAnnotationTypeElement() { return false; } public boolean isClass() { return false; } public boolean isConstructor() { return false; } public boolean isDeprecated() { return false; } public boolean isEnum() { return false; } public boolean isEnumConstant() { return false; } public boolean isError() { return false; } public boolean isException() { return false; } public boolean isField() { return false; } public boolean isIncluded() { return false; } public boolean isInterface() { return false; } public boolean isMethod() { return false; } public boolean isOrdinaryClass() { return false; } public String name() { return externalClass.getSimpleName(); } public void setRawCommentText(String arg0) { } public String firstSentenceCommentText() { return null; } public int compareTo(Object o) { return 0; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMemberDoc.java0000644001501200150120000000330311627206700030246 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; public class SimpleGroovyMemberDoc extends SimpleGroovyAbstractableElementDoc implements GroovyMemberDoc { protected GroovyClassDoc belongsToClass; public SimpleGroovyMemberDoc(String name, GroovyClassDoc belongsToClass) { super(name); this.belongsToClass = belongsToClass; } public boolean isSynthetic() {/*todo*/ return false; } public String firstSentenceCommentText() { if (super.firstSentenceCommentText() == null) { SimpleGroovyClassDoc classDoc = (SimpleGroovyClassDoc) belongsToClass; setFirstSentenceCommentText(classDoc.replaceTags(calculateFirstSentence(getRawCommentText()))); } return super.firstSentenceCommentText(); } public String commentText() { if (super.commentText() == null) { SimpleGroovyClassDoc classDoc = (SimpleGroovyClassDoc) belongsToClass; setCommentText(classDoc.replaceTags(getRawCommentText())); } return super.commentText(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java0000644001501200150120000003367511713766062030146 0ustar miguelmiguel/* * Copyright 2003-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; import org.codehaus.groovy.antlr.AntlrASTProcessor; import org.codehaus.groovy.antlr.SourceBuffer; import org.codehaus.groovy.antlr.UnicodeEscapingReader; import org.codehaus.groovy.antlr.java.Groovifier; import org.codehaus.groovy.antlr.java.Java2GroovyConverter; import org.codehaus.groovy.antlr.java.JavaLexer; import org.codehaus.groovy.antlr.java.JavaRecognizer; import org.codehaus.groovy.antlr.parser.GroovyLexer; import org.codehaus.groovy.antlr.parser.GroovyRecognizer; import org.codehaus.groovy.antlr.treewalker.PreOrderTraversal; import org.codehaus.groovy.antlr.treewalker.SourceCodeTraversal; import org.codehaus.groovy.antlr.treewalker.Visitor; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyRootDoc; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.tools.shell.util.Logger; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.*; import java.util.regex.Pattern; import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.LINK_REGEX; import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.TAG_REGEX; import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.CODE_REGEX; /* * todo: order methods alphabetically (implement compareTo enough?) */ public class GroovyRootDocBuilder { private final Logger log = Logger.create(GroovyRootDocBuilder.class); private static final char FS = '/'; private List links; private final GroovyDocTool tool; private final String[] sourcepaths; private final SimpleGroovyRootDoc rootDoc; private final Properties properties; public GroovyRootDocBuilder(GroovyDocTool tool, String[] sourcepaths, List links, Properties properties) { this.tool = tool; this.sourcepaths = sourcepaths; this.links = links; this.rootDoc = new SimpleGroovyRootDoc("root"); this.properties = properties; } // parsing public Map getClassDocsFromSingleSource(String packagePath, String file, String src) throws RecognitionException, TokenStreamException { if (file.indexOf(".java") > 0) { // simple (for now) decision on java or groovy // java return parseJava(packagePath, file, src); } if (file.indexOf(".sourcefile") > 0) { // java (special name used for testing) return parseJava(packagePath, file, src); } // not java, try groovy instead :-) return parseGroovy(packagePath, file, src); } private Map parseJava(String packagePath, String file, String src) throws RecognitionException, TokenStreamException { SourceBuffer sourceBuffer = new SourceBuffer(); JavaRecognizer parser = getJavaParser(src, sourceBuffer); String[] tokenNames = parser.getTokenNames(); try { parser.compilationUnit(); } catch (OutOfMemoryError e) { log.error("Out of memory while processing: " + packagePath + "/" + file); throw e; } AST ast = parser.getAST(); // modify the Java AST into a Groovy AST (just token types) Visitor java2groovyConverter = new Java2GroovyConverter(tokenNames); AntlrASTProcessor java2groovyTraverser = new PreOrderTraversal(java2groovyConverter); java2groovyTraverser.process(ast); // now mutate (groovify) the ast into groovy Visitor groovifier = new Groovifier(tokenNames, false); AntlrASTProcessor groovifierTraverser = new PreOrderTraversal(groovifier); groovifierTraverser.process(ast); // now do the business Visitor visitor = new SimpleGroovyClassDocAssembler(packagePath, file, sourceBuffer, links, properties, false); AntlrASTProcessor traverser = new SourceCodeTraversal(visitor); traverser.process(ast); return ((SimpleGroovyClassDocAssembler) visitor).getGroovyClassDocs(); } private Map parseGroovy(String packagePath, String file, String src) throws RecognitionException, TokenStreamException { SourceBuffer sourceBuffer = new SourceBuffer(); GroovyRecognizer parser = getGroovyParser(src, sourceBuffer); try { parser.compilationUnit(); } catch (OutOfMemoryError e) { log.error("Out of memory while processing: " + packagePath + "/" + file); throw e; } AST ast = parser.getAST(); // now do the business Visitor visitor = new SimpleGroovyClassDocAssembler(packagePath, file, sourceBuffer, links, properties, true); AntlrASTProcessor traverser = new SourceCodeTraversal(visitor); traverser.process(ast); return ((SimpleGroovyClassDocAssembler) visitor).getGroovyClassDocs(); } private JavaRecognizer getJavaParser(String input, SourceBuffer sourceBuffer) { UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new StringReader(input), sourceBuffer); JavaLexer lexer = new JavaLexer(unicodeReader); unicodeReader.setLexer(lexer); JavaRecognizer parser = JavaRecognizer.make(lexer); parser.setSourceBuffer(sourceBuffer); return parser; } private GroovyRecognizer getGroovyParser(String input, SourceBuffer sourceBuffer) { UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new StringReader(input), sourceBuffer); GroovyLexer lexer = new GroovyLexer(unicodeReader); unicodeReader.setLexer(lexer); GroovyRecognizer parser = GroovyRecognizer.make(lexer); parser.setSourceBuffer(sourceBuffer); return parser; } public void buildTree(List filenames) throws IOException, RecognitionException, TokenStreamException { setOverview(); List sourcepathFiles = new ArrayList(); if (sourcepaths != null) { for (String sourcepath : sourcepaths) { sourcepathFiles.add(new File(sourcepath).getAbsoluteFile()); } } for (String filename : filenames) { File srcFile = new File(filename); if (srcFile.exists()) { processFile(filename, srcFile, true); continue; } for (File spath : sourcepathFiles) { srcFile = new File(spath, filename); if (srcFile.exists()) { processFile(filename, srcFile, false); break; } } } } private void setOverview() { String path = properties.getProperty("overviewFile"); if (path != null && path.length() > 0) { try { String content = DefaultGroovyMethods.getText(new File(path)); calcThenSetOverviewDescription(content); } catch (IOException e) { System.err.println("Unable to load overview file: " + e.getMessage()); } } } private void processFile(String filename, File srcFile, boolean isAbsolute) throws IOException { String src = DefaultGroovyMethods.getText(srcFile); String packagePath = isAbsolute ? "DefaultPackage" : tool.getPath(filename).replace('\\', FS); String file = tool.getFile(filename); SimpleGroovyPackageDoc packageDoc = null; if (!isAbsolute) { packageDoc = (SimpleGroovyPackageDoc) rootDoc.packageNamed(packagePath); } // todo: this might not work correctly for absolute paths if (filename.endsWith("package.html") || filename.endsWith("package-info.java") || filename.endsWith("package-info.groovy")) { if (packageDoc == null) { packageDoc = new SimpleGroovyPackageDoc(packagePath); } processPackageInfo(src, filename, packageDoc); rootDoc.put(packagePath, packageDoc); return; } try { Map classDocs = getClassDocsFromSingleSource(packagePath, file, src); rootDoc.putAllClasses(classDocs); if (isAbsolute) { Iterator> iterator = classDocs.entrySet().iterator(); if (iterator.hasNext()) { final Map.Entry docEntry = iterator.next(); String fullPath = docEntry.getValue().getFullPathName(); int slash = fullPath.lastIndexOf(FS); if (slash > 0) packagePath = fullPath.substring(0, slash); packageDoc = (SimpleGroovyPackageDoc) rootDoc.packageNamed(packagePath); } } if (packageDoc == null) { packageDoc = new SimpleGroovyPackageDoc(packagePath); } packageDoc.putAll(classDocs); rootDoc.put(packagePath, packageDoc); } catch (RecognitionException e) { log.error("ignored due to RecognitionException: " + filename + " [" + e.getMessage() + "]"); log.debug("ignored due to RecognitionException: " + filename + " [" + e.getMessage() + "]", e); } catch (TokenStreamException e) { log.error("ignored due to TokenStreamException: " + filename + " [" + e.getMessage() + "]"); log.debug("ignored due to TokenStreamException: " + filename + " [" + e.getMessage() + "]", e); } } /* package private */ void processPackageInfo(String src, String filename, SimpleGroovyPackageDoc packageDoc) { String relPath = packageDoc.getRelativeRootPath(); String description = calcThenSetPackageDescription(src, filename, relPath); packageDoc.setDescription(description); // get same description but with paths relative to root String altDescription = calcThenSetPackageDescription(src, filename, ""); calcThenSetSummary(altDescription, packageDoc); } private String calcThenSetPackageDescription(String src, String filename, String relPath) { String description; if (filename.endsWith(".html")) { description = scrubOffExcessiveTags(src); description = pruneTagFromFront(description, "p"); description = pruneTagFromEnd(description, "/p"); } else { description = trimPackageAndComments(src); } description = replaceTags(description, relPath); return description; } // TODO remove dup with SimpleGroovyClassDoc private String replaceTags(String orig, String relPath) { String result = orig.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex // {@link processing hack} result = replaceAllTags(result, "", "", LINK_REGEX, relPath); // {@code processing hack} result = replaceAllTags(result, "", "", CODE_REGEX, relPath); // hack to reformat other groovydoc block tags (@see, @return, @param, @throws, @author, @since) into html result = replaceAllTags(result + "@endMarker", "
      $1:
      ", "
      ", TAG_REGEX, relPath); // remove @endMarker result = result.substring(0, result.length() - 10); return SimpleGroovyClassDoc.decodeSpecialSymbols(result); } private String replaceAllTags(String self, String s1, String s2, Pattern regex, String relPath) { return SimpleGroovyClassDoc.replaceAllTags(self, s1, s2, regex, links, relPath, rootDoc, null); } private void calcThenSetSummary(String src, SimpleGroovyPackageDoc packageDoc) { packageDoc.setSummary(SimpleGroovyDoc.calculateFirstSentence(src)); } private void calcThenSetOverviewDescription(String src) { String description = scrubOffExcessiveTags(src); rootDoc.setDescription(description); } private String trimPackageAndComments(String src) { return src.replaceFirst("(?sm)^package.*", "") .replaceFirst("(?sm)/.*\\*\\*(.*)\\*/", "$1") .replaceAll("(?m)^\\s*\\*", ""); } private String scrubOffExcessiveTags(String src) { String description = pruneTagFromFront(src, "html"); description = pruneTagFromFront(description, "/head"); description = pruneTagFromFront(description, "body"); description = pruneTagFromEnd(description, "/html"); return pruneTagFromEnd(description, "/body"); } private String pruneTagFromFront(String description, String tag) { int index = Math.max(indexOfTag(description, tag.toLowerCase()), indexOfTag(description, tag.toUpperCase())); if (index < 0) return description; return description.substring(index); } private String pruneTagFromEnd(String description, String tag) { int index = Math.max(description.lastIndexOf("<" + tag.toLowerCase() + ">"), description.lastIndexOf("<" + tag.toUpperCase() + ">")); if (index < 0) return description; return description.substring(0, index); } private int indexOfTag(String text, String tag) { int pos = text.indexOf("<" + tag + ">"); if (pos > 0) pos += tag.length() + 2; return pos; } public GroovyRootDoc getRootDoc() { rootDoc.resolve(); return rootDoc; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.java0000644001501200150120000001664211707612046027133 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import org.codehaus.groovy.groovydoc.GroovyDoc; import org.codehaus.groovy.groovydoc.GroovyTag; import java.text.BreakIterator; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleGroovyDoc implements GroovyDoc, GroovyTokenTypes { private static final Pattern TAG2_PATTERN = Pattern.compile("(?s)([a-z]+)\\s+(.*)"); private static final Pattern TAG3_PATTERN = Pattern.compile("(?s)([a-z]+)\\s+(\\S*)\\s+(.*)"); private String name; private String commentText = null; private String rawCommentText = ""; private String firstSentenceCommentText = null; private int definitionType; private boolean deprecated; private boolean isScript; private GroovyTag[] tags; public SimpleGroovyDoc(String name) { this.name = name; definitionType = CLASS_DEF; } public String name() { return name; } public String toString() { return "" + getClass() + "(" + name + ")"; } protected void setCommentText(String commentText) { this.commentText = commentText; } protected void setFirstSentenceCommentText(String firstSentenceCommentText) { this.firstSentenceCommentText = firstSentenceCommentText; } public String commentText() { return commentText; } public String firstSentenceCommentText() { return firstSentenceCommentText; } public String getRawCommentText() { return rawCommentText; } public void setRawCommentText(String rawCommentText) { this.rawCommentText = rawCommentText; calculateTags(rawCommentText); } public void setScript(boolean script) { isScript = script; } private void calculateTags(String rawCommentText) { String trimmed = rawCommentText.replaceFirst("(?s).*?\\*\\s*@", "@"); if (trimmed.equals(rawCommentText)) return; String cleaned = trimmed.replaceAll("(?m)^\\s*\\*\\s*([^*]*)$", "$1").trim(); String[] split = cleaned.split("(?m)^@"); List result = new ArrayList(); for (String s : split) { String tagname = null; if (s.startsWith("param") || s.startsWith("throws")) { Matcher m = TAG3_PATTERN.matcher(s); if (m.find()) { tagname = m.group(1); result.add(new SimpleGroovyTag(tagname, m.group(2), m.group(3))); } } else { Matcher m = TAG2_PATTERN.matcher(s); if (m.find()) { tagname = m.group(1); result.add(new SimpleGroovyTag(tagname, null, m.group(2))); } } if ("deprecated".equals(tagname)) { setDeprecated(true); } } tags = result.toArray(new GroovyTag[result.size()]); } public static String calculateFirstSentence(String raw) { // remove all the * from beginning of lines String text = raw.replaceAll("(?m)^\\s*\\*", "").trim(); // assume a

      paragraph tag signifies end of sentence text = text.replaceFirst("(?ms)

      .*", "").trim(); // assume completely blank line signifies end of sentence text = text.replaceFirst("(?ms)\\n\\s*\\n.*", "").trim(); // assume @tag signifies end of sentence text = text.replaceFirst("(?ms)\\n\\s*@(see|param|throws|return|author|since|exception|version|deprecated|todo)\\s.*", "").trim(); // Comment Summary using first sentence (Locale sensitive) BreakIterator boundary = BreakIterator.getSentenceInstance(Locale.getDefault()); // todo - allow locale to be passed in boundary.setText(text); int start = boundary.first(); int end = boundary.next(); if (start > -1 && end > -1) { // need to abbreviate this comment for the summary text = text.substring(start, end); } return text; } public boolean isClass() { return definitionType == CLASS_DEF && !isScript; } public boolean isScript() { return definitionType == CLASS_DEF && isScript; } public boolean isInterface() { return definitionType == INTERFACE_DEF; } public boolean isAnnotationType() { return definitionType == ANNOTATION_DEF; } public boolean isEnum() { return definitionType == ENUM_DEF; } public String getTypeDescription() { if (isInterface()) return "Interface"; if (isAnnotationType()) return "Annotation Type"; if (isEnum()) return "Enum"; return "Class"; } public String getTypeSourceDescription() { if (isInterface()) return "interface"; if (isAnnotationType()) return "@interface"; if (isEnum()) return "enum"; return "class"; } public void setTokenType(int t) { definitionType = t; } public int tokenType() { return definitionType; } // Methods from Comparable public int compareTo(Object that) { if (that instanceof GroovyDoc) { return name.compareTo(((GroovyDoc) that).name()); } else { throw new ClassCastException(String.format("Cannot compare object of type %s.", that.getClass())); } } // Methods from GroovyDoc // public GroovyTag[] firstSentenceTags() {/*todo*/return null;} // public GroovyTag[] inlineTags() {/*todo*/return null;} public boolean isAnnotationTypeElement() {/*todo*/ return false; } public boolean isConstructor() {/*todo*/ return false; } public boolean isEnumConstant() {/*todo*/ return false; } public boolean isDeprecated() { return deprecated; } public boolean isError() {/*todo*/ return false; } public boolean isException() {/*todo*/ return false; } public boolean isField() {/*todo*/ return false; } public boolean isIncluded() {/*todo*/ return false; } public boolean isMethod() {/*todo*/ return false; } public boolean isOrdinaryClass() {/*todo*/ return false; } // public GroovySourcePosition position() {/*todo*/return null;} // public GroovySeeTag[] seeTags() {/*todo*/return null;} public GroovyTag[] tags() { return tags; } // public GroovyTag[] tags(String arg0) {/*todo*/return null;} public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/ArrayClassDocWrapper.java0000644001501200150120000001540511707612046030075 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyAnnotationRef; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyConstructorDoc; import org.codehaus.groovy.groovydoc.GroovyFieldDoc; import org.codehaus.groovy.groovydoc.GroovyMethodDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import org.codehaus.groovy.groovydoc.GroovyType; public class ArrayClassDocWrapper implements GroovyClassDoc { private final GroovyClassDoc delegate; public ArrayClassDocWrapper(GroovyClassDoc delegate) { this.delegate = delegate; } public GroovyClassDoc getDelegate() { return delegate; } public GroovyConstructorDoc[] constructors() { return delegate.constructors(); } public GroovyConstructorDoc[] constructors(boolean filter) { return delegate.constructors(filter); } public boolean definesSerializableFields() { return delegate.definesSerializableFields(); } public GroovyFieldDoc[] enumConstants() { return delegate.enumConstants(); } public GroovyFieldDoc[] fields() { return delegate.fields(); } public GroovyFieldDoc[] properties() { return delegate.properties(); } public GroovyFieldDoc[] fields(boolean filter) { return delegate.fields(filter); } public GroovyClassDoc findClass(String className) { return delegate.findClass(className); } public GroovyClassDoc[] importedClasses() { return delegate.importedClasses(); } public GroovyPackageDoc[] importedPackages() { return delegate.importedPackages(); } public GroovyClassDoc[] innerClasses() { return delegate.innerClasses(); } public GroovyClassDoc[] innerClasses(boolean filter) { return delegate.innerClasses(filter); } public GroovyClassDoc[] interfaces() { return delegate.interfaces(); } public GroovyType[] interfaceTypes() { return delegate.interfaceTypes(); } public boolean isAbstract() { return delegate.isAbstract(); } public boolean isExternalizable() { return delegate.isExternalizable(); } public boolean isSerializable() { return delegate.isSerializable(); } public GroovyMethodDoc[] methods() { return delegate.methods(); } public GroovyMethodDoc[] methods(boolean filter) { return delegate.methods(filter); } public GroovyFieldDoc[] serializableFields() { return delegate.serializableFields(); } public GroovyMethodDoc[] serializationMethods() { return delegate.serializationMethods(); } public boolean subclassOf(GroovyClassDoc gcd) { return delegate.subclassOf(gcd); } public GroovyClassDoc superclass() { return delegate.superclass(); } public GroovyType superclassType() { return delegate.superclassType(); } public String getFullPathName() { return delegate.getFullPathName(); } public String getRelativeRootPath() { return delegate.getRelativeRootPath(); } public boolean isPrimitive() { return delegate.isPrimitive(); } public String qualifiedTypeName() { return delegate.qualifiedTypeName(); } public String simpleTypeName() { return delegate.simpleTypeName(); } public String typeName() { return delegate.typeName(); } public String toString() { return delegate.toString(); } public GroovyAnnotationRef[] annotations() { return delegate.annotations(); } public GroovyClassDoc containingClass() { return delegate.containingClass(); } public GroovyPackageDoc containingPackage() { return delegate.containingPackage(); } public boolean isFinal() { return delegate.isFinal(); } public boolean isPackagePrivate() { return delegate.isPackagePrivate(); } public boolean isPrivate() { return delegate.isPrivate(); } public boolean isProtected() { return delegate.isProtected(); } public boolean isPublic() { return delegate.isPublic(); } public boolean isStatic() { return delegate.isStatic(); } public String modifiers() { return delegate.modifiers(); } public int modifierSpecifier() { return delegate.modifierSpecifier(); } public String qualifiedName() { return delegate.qualifiedName(); } public String commentText() { return delegate.commentText(); } public String getRawCommentText() { return delegate.getRawCommentText(); } public boolean isAnnotationType() { return delegate.isAnnotationType(); } public boolean isAnnotationTypeElement() { return delegate.isAnnotationTypeElement(); } public boolean isClass() { return delegate.isClass(); } public boolean isConstructor() { return delegate.isConstructor(); } public boolean isDeprecated() { return delegate.isDeprecated(); } public boolean isEnum() { return delegate.isEnum(); } public boolean isEnumConstant() { return delegate.isEnumConstant(); } public boolean isError() { return delegate.isError(); } public boolean isException() { return delegate.isException(); } public boolean isField() { return delegate.isField(); } public boolean isIncluded() { return delegate.isIncluded(); } public boolean isInterface() { return delegate.isInterface(); } public boolean isMethod() { return delegate.isMethod(); } public boolean isOrdinaryClass() { return delegate.isOrdinaryClass(); } public String name() { return delegate.name(); } public void setRawCommentText(String arg0) { delegate.setRawCommentText(arg0); } public String firstSentenceCommentText() { return delegate.firstSentenceCommentText(); } public int compareTo(Object o) { return delegate.compareTo(o); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyMethodDoc.java0000644001501200150120000000310011627206700030252 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; public class SimpleGroovyMethodDoc extends SimpleGroovyExecutableMemberDoc implements GroovyMethodDoc { private GroovyType returnType; public SimpleGroovyMethodDoc(String name, GroovyClassDoc belongsToClass) { super(name, belongsToClass); } public GroovyType returnType() { return returnType; } // TODO need returnType.qualifiedTypeName() here public void setReturnType(GroovyType returnType) { this.returnType = returnType; } public boolean isAbstract() {/*todo*/ return false; } public GroovyClassDoc overriddenClass() {/*todo*/ return null; } public GroovyMethodDoc overriddenMethod() {/*todo*/ return null; } public GroovyType overriddenType() {/*todo*/ return null; } public boolean overrides(GroovyMethodDoc arg0) {/*todo*/ return false; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/Main.properties0000644001501200150120000000462011627206700026173 0ustar miguelmiguel# # Copyright 2003-2010 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # CLI messages # cli.option.help.description=Display this help message cli.option.version.description=Display the version cli.option.verbose.description=Enable verbose output cli.option.quiet.description=Suppress superfluous output cli.option.debug.description=Enable debug output cli.option.cp.description=Aliases for '-classpath' cli.option.classpath.description=Specify where to find the class files - must be first argument cli.option.stylesheetfile.description=File to change style of the generated documentation cli.option.doctitle.description=Include title for the overview page cli.option.windowtitle.description=Browser window title for the documentation cli.option.header.description=Include header text for each page cli.option.footer.description=Include footer text for each page cli.option.author.description=Include @author paragraphs (currently not used) cli.option.noscripts.description=Don't process Groovy Scripts cli.option.nomainforscripts.description=Don't include the implicit 'public static void main' method for scripts cli.option.public.description=Show only public classes and members cli.option.protected.description=Show protected/public classes and members (default) cli.option.package.description=Show package/protected/public classes and members cli.option.private.description=Show all classes and members cli.option.overview.description=Read overview documentation from HTML file cli.option.destdir.description=Destination directory for output files cli.option.sourcepath.description=Specify where to find source files (dirs separated by platform path separator) cli.option.exclude.description=Specify a list of packages to exclude (separated by colons for all operating systems) cli.info.version=@|green GroovyDoc|@ {0}groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/FileSystemResourceManager.java0000644001501200150120000000236611627206700031130 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import java.io.File; import java.io.IOException; import java.io.Reader; import org.codehaus.groovy.runtime.DefaultGroovyMethods; public class FileSystemResourceManager implements ResourceManager { private String basedir; private static final String FS = "/"; public FileSystemResourceManager() { basedir = ""; } public FileSystemResourceManager(String basedir) { this.basedir = basedir + FS; } public Reader getReader(String resourceName) throws IOException { return DefaultGroovyMethods.newReader(new File(basedir + resourceName)); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/GroovyDocTemplateEngine.java0000644001501200150120000001616611627206700030601 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import groovy.text.GStringTemplateEngine; import groovy.text.Template; import groovy.text.TemplateEngine; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import org.codehaus.groovy.groovydoc.GroovyRootDoc; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * Process Groovydoc templates. */ public class GroovyDocTemplateEngine { private TemplateEngine engine; private GroovyDocTool tool; // TODO use it or lose it private ResourceManager resourceManager; private Properties properties; private Map docTemplates; // cache private List docTemplatePaths; // once per documentation set private Map packageTemplates; // cache private List packageTemplatePaths; // once per package private Map classTemplates; // cache private List classTemplatePaths; // once per class public GroovyDocTemplateEngine(GroovyDocTool tool, ResourceManager resourceManager, String classTemplate) { this(tool, resourceManager, new String[]{}, new String[]{}, new String[]{classTemplate}, new Properties()); } public GroovyDocTemplateEngine(GroovyDocTool tool, ResourceManager resourceManager, String[] docTemplates, String[] packageTemplates, String[] classTemplates, Properties properties) { this.tool = tool; this.resourceManager = resourceManager; this.properties = properties; this.docTemplatePaths = Arrays.asList(docTemplates); this.packageTemplatePaths = Arrays.asList(packageTemplates); this.classTemplatePaths = Arrays.asList(classTemplates); this.docTemplates = new HashMap(); this.packageTemplates = new HashMap(); this.classTemplates = new HashMap(); engine = new GStringTemplateEngine(); } String applyClassTemplates(GroovyClassDoc classDoc) { String templatePath = classTemplatePaths.get(0); // todo (iterate) String templateWithBindingApplied = ""; try { Template t = classTemplates.get(templatePath); if (t == null) { t = engine.createTemplate(resourceManager.getReader(templatePath)); classTemplates.put(templatePath, t); } Map binding = new HashMap(); binding.put("classDoc", classDoc); binding.put("props", properties); templateWithBindingApplied = t.make(binding).toString(); } catch (Exception e) { e.printStackTrace(); } return templateWithBindingApplied; } String applyPackageTemplate(String template, GroovyPackageDoc packageDoc) { String templateWithBindingApplied = ""; try { Template t = packageTemplates.get(template); if (t == null) { t = engine.createTemplate(resourceManager.getReader(template)); packageTemplates.put(template, t); } Map binding = new HashMap(); binding.put("packageDoc", packageDoc); binding.put("props", properties); templateWithBindingApplied = t.make(binding).toString(); } catch (Exception e) { e.printStackTrace(); } return templateWithBindingApplied; } String applyRootDocTemplate(String template, GroovyRootDoc rootDoc) { String templateWithBindingApplied = ""; try { Template t = docTemplates.get(template); if (t == null) { t = engine.createTemplate(resourceManager.getReader(template)); docTemplates.put(template, t); } Map binding = new HashMap(); binding.put("rootDoc", rootDoc); binding.put("props", properties); templateWithBindingApplied = t.make(binding).toString(); } catch (Exception e) { e.printStackTrace(); } return templateWithBindingApplied; } Iterator classTemplatesIterator() { return classTemplatePaths.iterator(); } Iterator packageTemplatesIterator() { return packageTemplatePaths.iterator(); } Iterator docTemplatesIterator() { return docTemplatePaths.iterator(); } /* String applyClassTemplatesWithVelocity(GroovyClassDoc classDoc) { // Iterator templates = classTemplates.iterator(); // while (templates.hasNext) String templatePath = (String) classTemplates.get(0); // todo (iterate) String templateWithBindingApplied = ""; try { // Template t = new GStringTemplateEngine().createTemplate(template); VelocityTemplateEngine t = new VelocityTemplateEngine(new File(".").getAbsolutePath()); Map binding = new HashMap(); binding.put("classDoc", classDoc); // templateWithBindingApplied = t.make(binding).toString(); templateWithBindingApplied = t.apply(templatePath,binding); } catch (Exception e) { e.printStackTrace(); } return templateWithBindingApplied; } */ public void copyBinaryResource(String template, String destFileName) { if (resourceManager instanceof ClasspathResourceManager) { OutputStream outputStream = null; try { InputStream inputStream = ((ClasspathResourceManager) resourceManager).getInputStream(template); outputStream = new FileOutputStream(destFileName); DefaultGroovyMethods.leftShift(outputStream, inputStream); } catch (IOException e) { System.err.println("Resource " + template + " skipped due to: " + e.getMessage()); } catch (NullPointerException e) { System.err.println("Resource " + template + " not found so skipped"); } finally { DefaultGroovyMethods.closeQuietly(outputStream); } } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/LinkArgument.java0000644001501200150120000000317011627206700026433 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; /** * Represents a link pair (href, packages). * The packages are comma separated. */ public class LinkArgument { private String href = ""; private String packages = ""; /** * Get the packages attribute. * * @return the packages attribute. */ public String getPackages() { return packages; } /** * Set the packages attribute. * * @param packages the comma separated package prefixs corresponding to this link */ public void setPackages(String packages) { this.packages = packages; } /** * Get the href attribute. * * @return the href attribute. */ public String getHref() { return href; } /** * Set the href attribute. * * @param hr a String value representing the URL to use for this link */ public void setHref(String hr) { href = hr; } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/groovydoc/SimpleGroovyConstructorDoc.java0000644001501200150120000000166511627206700031375 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.*; public class SimpleGroovyConstructorDoc extends SimpleGroovyExecutableMemberDoc implements GroovyConstructorDoc { public SimpleGroovyConstructorDoc(String name, GroovyClassDoc belongsToClass) { super(name, belongsToClass); } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/ast/0000755001501200150120000000000011707612046021746 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/ast/TransformTestHelper.groovy0000644001501200150120000001001611707612046027166 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.ast import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.control.CompilerConfiguration import java.security.CodeSource import org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.classgen.GeneratorContext import org.codehaus.groovy.ast.ClassNode /* * This TestHarness exists so that a global transform can be run without * using the Jar services mechanism, which requires building a jar. * * To use this simply create an instance of TransformTestHelper with * an ASTTransformation and CompilePhase, then invoke parse(File) or * parse(String). * * This test harness is not exactly the same as executing a global transformation * but can greatly aide in debugging and testing a transform. You should still * test your global transformation when packaged as a jar service before * releasing it. * * @author Hamlet D'Arcy */ class TransformTestHelper { private ASTTransformation transform private CompilePhase phase /** * Creates the test helper. * @param transform * the transform to run when compiling the file later * @param phase * the phase to run the transform in */ def TransformTestHelper(ASTTransformation transform, CompilePhase phase) { this.transform = transform this.phase = phase } /** * Compiles the File into a Class applying the transform specified in the constructor. * @input input * must be a groovy source file */ public Class parse(File input) { TestHarnessClassLoader loader = new TestHarnessClassLoader(transform, phase) return loader.parseClass(input) } /** * Compiles the String into a Class applying the transform specified in the constructor. * @input input * must be a valid groovy source string */ public Class parse(String input) { TestHarnessClassLoader loader = new TestHarnessClassLoader(transform, phase) return loader.parseClass(input) } } /** * ClassLoader exists so that TestHarnessOperation can be wired into the compile. * * @author Hamlet D'Arcy */ private class TestHarnessClassLoader extends GroovyClassLoader { private ASTTransformation transform private CompilePhase phase TestHarnessClassLoader(ASTTransformation transform, CompilePhase phase) { this.transform = transform this.phase = phase } protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource codeSource) { CompilationUnit cu = super.createCompilationUnit(config, codeSource) cu.addPhaseOperation(new TestHarnessOperation(transform), phase.getPhaseNumber()) return cu } } /** * Operation exists so that an AstTransformation can be run against the SourceUnit. * * @author Hamlet D'Arcy */ private class TestHarnessOperation extends PrimaryClassNodeOperation { private ASTTransformation transform def TestHarnessOperation(transform) { this.transform = transform; } public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { transform.visit(null, source) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/LoaderConfiguration.java0000644001501200150120000003200611707612046025761 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class used to configure a RootLoader from a stream or by using * it's methods. *

      * The stream can be for example a FileInputStream from a file with * the following format: *

      *

       * # comment
       * main is classname
       * load path
       * load file
       * load pathWith${property}
       * load pathWith!{required.property}
       * load path/*.jar
       * load path/**/*.jar
       * 
      *
        *
      • All lines starting with "#" are ignored.
      • *
      • The "main is" part may only be once in the file. The String * afterwards is the name of a class with a main method.
      • *
      • The "load" command will add the given file or path to the * classpath in this configuration object. If the path does not * exist, the path will be ignored. *
      • *
      • properties referenced using !{x} are required.
      • *
      • properties referenced using ${x} are not required. If the * property does not exist the whole load instruction line will * be ignored.
      • *
      • * is used to match zero or more characters in a file.
      • *
      • ** is used to match zero or more directories.
      • *
      • Loading paths with load ./*.jar or load *.jar are not supported.
      • *
      *

      * Defining the main class is required unless setRequireMain(boolean) is * called with false, before reading the configuration. * You can use the wildcard "*" to filter the path, but only for files, not * directories. To match directories use "**". The ${propertyname} is replaced by the value of the system's * property name. You can use user.home here for example. If the property does * not exist, an empty string will be used. If the path or file after the load * command does not exist, the path will be ignored. * * @author Jochen Theodorou * @version $Revision$ * @see RootLoader */ public class LoaderConfiguration { private static final String MAIN_PREFIX = "main is", LOAD_PREFIX = "load", PROP_PREFIX = "property"; private List classPath = new ArrayList(); private String main; private boolean requireMain; private static final char WILDCARD = '*'; private static final String ALL_WILDCARD = "" + WILDCARD + WILDCARD; private static final String MATCH_FILE_NAME = "\\\\E[^/]+?\\\\Q"; private static final String MATCH_ALL = "\\\\E.+?\\\\Q"; /** * creates a new loader configuration */ public LoaderConfiguration() { this.requireMain = true; } /** * configures this loader with a stream * * @param is stream used to read the configuration * @throws IOException if reading or parsing the contents of the stream fails */ public void configure(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); int lineNumber = 0; while (true) { String line = reader.readLine(); if (line == null) break; line = line.trim(); lineNumber++; if (line.startsWith("#") || line.length() == 0) continue; if (line.startsWith(LOAD_PREFIX)) { String loadPath = line.substring(LOAD_PREFIX.length()).trim(); loadPath = assignProperties(loadPath); loadFilteredPath(loadPath); } else if (line.startsWith(MAIN_PREFIX)) { if (main != null) throw new IOException("duplicate definition of main in line " + lineNumber + " : " + line); main = line.substring(MAIN_PREFIX.length()).trim(); } else if (line.startsWith(PROP_PREFIX)) { String params = line.substring(PROP_PREFIX.length()).trim(); int index = params.indexOf('='); if (index == -1) { throw new IOException("unexpected property format - expecting name=value" + lineNumber + " : " + line); } String propName = params.substring(0, index); String propValue= assignProperties(params.substring(index+1)); System.setProperty(propName, propValue); } else { throw new IOException("unexpected line in " + lineNumber + " : " + line); } } if (requireMain && main == null) throw new IOException("missing main class definition in config file"); } /* * Expands the properties inside the given string to it's values. */ private String assignProperties(String str) { int propertyIndexStart = 0, propertyIndexEnd = 0; boolean requireProperty = false; String result = ""; while (propertyIndexStart < str.length()) { { int i1 = str.indexOf("${", propertyIndexStart); int i2 = str.indexOf("!{", propertyIndexStart); if (i1 == -1) { propertyIndexStart = i2; } else if (i2 == -1) { propertyIndexStart = i1; } else { propertyIndexStart = Math.min(i1, i2); } requireProperty = propertyIndexStart == i2; } if (propertyIndexStart == -1) break; result += str.substring(propertyIndexEnd, propertyIndexStart); propertyIndexEnd = str.indexOf("}", propertyIndexStart); if (propertyIndexEnd == -1) break; String propertyKey = str.substring(propertyIndexStart + 2, propertyIndexEnd); String propertyValue = System.getProperty(propertyKey); // assume properties contain paths if (propertyValue == null) { if (requireProperty) { throw new IllegalArgumentException("Variable " + propertyKey + " in groovy-starter.conf references a non-existent System property! Try passing the property to the VM using -D" + propertyKey + "=myValue in JAVA_OPTS"); } else { return null; } } propertyValue = getSlashyPath(propertyValue); propertyValue = correctDoubleSlash(propertyValue,propertyIndexEnd,str); result += propertyValue; propertyIndexEnd++; propertyIndexStart = propertyIndexEnd; } if (propertyIndexStart == -1 || propertyIndexStart >= str.length()) { result += str.substring(propertyIndexEnd); } else if (propertyIndexEnd == -1) { result += str.substring(propertyIndexStart); } return result; } private String correctDoubleSlash(String propertyValue, int propertyIndexEnd, String str) { int index = propertyIndexEnd+1; if ( index0) { propertyValue = propertyValue.substring(0,propertyValue.length()-1); } return propertyValue; } /* * Load a possibly filtered path. Filters are defined * by using the * wildcard like in any shell. */ private void loadFilteredPath(String filter) { if (filter == null) return; filter = getSlashyPath(filter); int starIndex = filter.indexOf(WILDCARD); if (starIndex == -1) { addFile(new File(filter)); return; } boolean recursive = filter.indexOf(ALL_WILDCARD) != -1; if (filter.lastIndexOf('/') package org.codehaus.groovy.tools.*

      Compiler entry points and miscellaneous development tools.

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/0000755001501200150120000000000011715031256022240 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaStubCompilationUnit.java0000644001501200150120000001111411715031256027657 0ustar miguelmiguel/* * Copyright (C) 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import groovy.lang.GroovyClassLoader; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.classgen.VariableScopeVisitor; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.control.SourceUnit; import java.io.File; import java.io.FileNotFoundException; import java.net.URL; import java.util.Iterator; import java.util.Map; /** * Compilation unit to only generate stubs. * * @author Jason Dillon * @author Guillaume Laforge */ public class JavaStubCompilationUnit extends CompilationUnit { private static final String DOT_GROOVY = ".groovy"; private final JavaStubGenerator stubGenerator; private int stubCount; public JavaStubCompilationUnit(final CompilerConfiguration config, final GroovyClassLoader gcl, File destDir) { super(config, null, gcl); assert config != null; Map options = config.getJointCompilationOptions(); if (destDir == null) { destDir = (File) options.get("stubDir"); } boolean useJava5 = config.getTargetBytecode().equals(CompilerConfiguration.POST_JDK5); stubGenerator = new JavaStubGenerator(destDir, false, useJava5); addPhaseOperation(new PrimaryClassNodeOperation() { @Override public void call(SourceUnit source, GeneratorContext context, ClassNode node) throws CompilationFailedException { VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(node); new JavaAwareResolveVisitor(JavaStubCompilationUnit.this).startResolving(node,source); } },Phases.CONVERSION); addPhaseOperation(new PrimaryClassNodeOperation() { @Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException { try { stubGenerator.generateClass(node); stubCount++; } catch (FileNotFoundException e) { source.addException(e); } } },Phases.CONVERSION); } public JavaStubCompilationUnit(final CompilerConfiguration config, final GroovyClassLoader gcl) { this(config, gcl, null); } public int getStubCount() { return stubCount; } @Override public void compile() throws CompilationFailedException { stubCount = 0; super.compile(Phases.CONVERSION); } @Override public void configure(final CompilerConfiguration config) { super.configure(config); // GroovyClassLoader should be able to find classes compiled from java sources File targetDir = config.getTargetDirectory(); if (targetDir != null) { final String classOutput = targetDir.getAbsolutePath(); getClassLoader().addClasspath(classOutput); } } @Override public SourceUnit addSource(final File file) { if (hasAcceptedFileExtension(file.getName())) { return super.addSource(file); } return null; } @Override public SourceUnit addSource(URL url) { if (hasAcceptedFileExtension(url.getPath())) { return super.addSource(url); } return null; } private boolean hasAcceptedFileExtension(String name) { String lowerCasedName = name.toLowerCase(); for (String extension : configuration.getScriptExtensions()) { if (lowerCasedName.endsWith(extension)) return true; } return false; } @Deprecated public void addSourceFile(final File file) { addSource(file); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaCompilerFactory.java0000644001501200150120000000147211627206700027013 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import org.codehaus.groovy.control.CompilerConfiguration; public interface JavaCompilerFactory { JavaCompiler createCompiler(CompilerConfiguration config); } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaAwareResolveVisitor.java0000644001501200150120000000236611627206700027673 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.ResolveVisitor; public class JavaAwareResolveVisitor extends ResolveVisitor { public JavaAwareResolveVisitor(CompilationUnit cu) { super(cu); } protected void visitClassCodeContainer(Statement code) { // do nothing here, leave it to the normal resolving } protected void addError(String msg, ASTNode expr) { // do nothing here, leave it to the normal resolving } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaCompiler.java0000644001501200150120000000154111627206700025460 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import java.util.List; import org.codehaus.groovy.control.CompilationUnit; /** * @author Alex.Tkachman */ public interface JavaCompiler { void compile(List files, CompilationUnit cu); } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/package.html0000644001501200150120000000024411627206700024521 0ustar miguelmiguel package org.codehaus.groovy.tools.javac.*

      Classes related to the joint compiler.

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavacCompilerFactory.java0000644001501200150120000000162211627206700027153 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import org.codehaus.groovy.control.CompilerConfiguration; public class JavacCompilerFactory implements JavaCompilerFactory { public JavaCompiler createCompiler(CompilerConfiguration config) { return new JavacJavaCompiler(config); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java0000644001501200150120000007217111715030632026476 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.ResolveVisitor; import org.codehaus.groovy.tools.Utilities; import org.objectweb.asm.Opcodes; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class JavaStubGenerator { private boolean java5 = false; private boolean requireSuperResolved = false; private File outputPath; private List toCompile = new ArrayList(); private ArrayList propertyMethods = new ArrayList(); private Map propertyMethodsWithSigs = new HashMap(); private ArrayList constructors = new ArrayList(); private ModuleNode currentModule; public JavaStubGenerator(final File outputPath, final boolean requireSuperResolved, final boolean java5) { this.outputPath = outputPath; this.requireSuperResolved = requireSuperResolved; this.java5 = java5; outputPath.mkdirs(); } public JavaStubGenerator(final File outputPath) { this(outputPath, false, false); } private void mkdirs(File parent, String relativeFile) { int index = relativeFile.lastIndexOf('/'); if (index == -1) return; File dir = new File(parent, relativeFile.substring(0, index)); dir.mkdirs(); } public void generateClass(ClassNode classNode) throws FileNotFoundException { // Only attempt to render our self if our super-class is resolved, else wait for it if (requireSuperResolved && !classNode.getSuperClass().isResolved()) { return; } // owner should take care for us if (classNode instanceof InnerClassNode) return; // don't generate stubs for private classes, as they are only visible in the same file if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return; String fileName = classNode.getName().replace('.', '/'); mkdirs(outputPath, fileName); toCompile.add(fileName); File file = new File(outputPath, fileName + ".java"); FileOutputStream fos = new FileOutputStream(file); PrintWriter out = new PrintWriter(fos); try { String packageName = classNode.getPackageName(); if (packageName != null) { out.println("package " + packageName + ";\n"); } printImports(out, classNode); printClassContents(out, classNode); } finally { try { out.close(); } catch (Exception e) { // ignore } try { fos.close(); } catch (IOException e) { // ignore } } } private void printClassContents(PrintWriter out, ClassNode classNode) throws FileNotFoundException { if (classNode instanceof InnerClassNode && ((InnerClassNode) classNode).isAnonymous()) { // if it is an anonymous inner class, don't generate the stub code for it. return; } try { Verifier verifier = new Verifier() { public void addCovariantMethods(ClassNode cn) {} protected void addTimeStamp(ClassNode node) {} protected void addInitialization(ClassNode node) {} protected void addPropertyMethod(MethodNode method) { doAddMethod(method); } protected void addReturnIfNeeded(MethodNode node) {} protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { doAddMethod(new MethodNode(name, modifiers, returnType, parameters, exceptions, code)); } protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) { if (code instanceof ExpressionStatement) {//GROOVY-4508 Statement temp = code; code = new BlockStatement(); ((BlockStatement) code).addStatement(temp); } ConstructorNode ctrNode = new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code); ctrNode.setDeclaringClass(node); constructors.add(ctrNode); } protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) { final Parameter[] parameters = method.getParameters(); final Expression[] saved = new Expression[parameters.length]; for (int i = 0; i < parameters.length; i++) { if (parameters[i].hasInitialExpression()) saved[i] = parameters[i].getInitialExpression(); } super.addDefaultParameters(action, method); for (int i = 0; i < parameters.length; i++) { if (saved[i] != null) parameters[i].setInitialExpression(saved[i]); } } private void doAddMethod(MethodNode method) { String sig = method.getTypeDescriptor(); if (propertyMethodsWithSigs.containsKey(sig)) return; propertyMethods.add(method); propertyMethodsWithSigs.put(sig, method); } @Override protected void addDefaultConstructor(ClassNode node) { // not required for stub generation } }; verifier.visitClass(classNode); currentModule = classNode.getModule(); boolean isInterface = classNode.isInterface(); boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) != 0; boolean isAnnotationDefinition = classNode.isAnnotationDefinition(); printAnnotations(out, classNode); printModifiers(out, classNode.getModifiers() & ~(isInterface ? Opcodes.ACC_ABSTRACT : 0) & ~(isEnum ? Opcodes.ACC_FINAL : 0)); if (isInterface) { if (isAnnotationDefinition) { out.print("@"); } out.print("interface "); } else if (isEnum) { out.print("enum "); } else { out.print("class "); } String className = classNode.getNameWithoutPackage(); if (classNode instanceof InnerClassNode) className = className.substring(className.lastIndexOf("$") + 1); out.println(className); printGenericsBounds(out, classNode, true); ClassNode superClass = classNode.getUnresolvedSuperClass(false); if (!isInterface && !isEnum) { out.print(" extends "); printType(out, superClass); } ClassNode[] interfaces = classNode.getInterfaces(); if (interfaces != null && interfaces.length > 0 && !isAnnotationDefinition) { if (isInterface) { out.println(" extends"); } else { out.println(" implements"); } for (int i = 0; i < interfaces.length - 1; ++i) { out.print(" "); printType(out, interfaces[i]); out.print(","); } out.print(" "); printType(out, interfaces[interfaces.length - 1]); } out.println(" {"); printFields(out, classNode); printMethods(out, classNode, isEnum); for (Iterator inner = classNode.getInnerClasses(); inner.hasNext(); ) { // GROOVY-4004: Clear the methods from the outer class so that they don't get duplicated in inner ones propertyMethods.clear(); propertyMethodsWithSigs.clear(); constructors.clear(); printClassContents(out, inner.next()); } out.println("}"); } finally { propertyMethods.clear(); propertyMethodsWithSigs.clear(); constructors.clear(); currentModule = null; } } private void printMethods(PrintWriter out, ClassNode classNode, boolean isEnum) { if (!isEnum) printConstructors(out, classNode); @SuppressWarnings("unchecked") List methods = (List) propertyMethods.clone(); methods.addAll(classNode.getMethods()); for (MethodNode method : methods) { if (isEnum && method.isSynthetic()) { // skip values() method and valueOf(String) String name = method.getName(); Parameter[] params = method.getParameters(); if (name.equals("values") && params.length == 0) continue; if (name.equals("valueOf") && params.length == 1 && params[0].getType().equals(ClassHelper.STRING_TYPE)) { continue; } } printMethod(out, classNode, method); } } private void printConstructors(PrintWriter out, ClassNode classNode) { @SuppressWarnings("unchecked") List constrs = (List) constructors.clone(); if (constrs != null) { constrs.addAll(classNode.getDeclaredConstructors()); for (ConstructorNode constr : constrs) { printConstructor(out, classNode, constr); } } } private void printFields(PrintWriter out, ClassNode classNode) { boolean isInterface = classNode.isInterface(); List fields = classNode.getFields(); if (fields == null) return; List enumFields = new ArrayList(fields.size()); List normalFields = new ArrayList(fields.size()); for (FieldNode field : fields) { boolean isSynthetic = (field.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0; if (field.isEnum()) { enumFields.add(field); } else if (!isSynthetic) { normalFields.add(field); } } printEnumFields(out, enumFields); for (FieldNode normalField : normalFields) { printField(out, normalField, isInterface); } } private void printEnumFields(PrintWriter out, List fields) { if (fields.size() == 0) return; boolean first = true; for (FieldNode field : fields) { if (!first) { out.print(", "); } else { first = false; } out.print(field.getName()); } out.println(";"); } private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) { if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return; printAnnotations(out, fieldNode); if (!isInterface) { printModifiers(out, fieldNode.getModifiers()); } ClassNode type = fieldNode.getType(); printType(out, type); out.print(" "); out.print(fieldNode.getName()); if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) { out.print(" = "); Expression valueExpr = fieldNode.getInitialValueExpression(); if (valueExpr instanceof ConstantExpression) { valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr); } if (valueExpr instanceof ConstantExpression && fieldNode.isStatic() && fieldNode.isFinal() && ClassHelper.isStaticConstantInitializerType(valueExpr.getType()) && valueExpr.getType().equals(fieldNode.getType())) { // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles correctly if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) { out.print("\""+valueExpr.getText().replaceAll("\\\"", "\\\\\"")+"\""); } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) { out.print("'"+valueExpr.getText()+"'"); } else { ClassNode constantType = valueExpr.getType(); out.print('('); printType(out, type); out.print(") "); out.print(valueExpr.getText()); if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L'); } } else if (ClassHelper.isPrimitiveType(type)) { String val = type == ClassHelper.boolean_TYPE ? "false" : "0"; out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")"); } else { out.print("null"); } } out.println(";"); } private ConstructorCallExpression getConstructorCallExpression(ConstructorNode constructorNode) { Statement code = constructorNode.getCode(); if (!(code instanceof BlockStatement)) return null; BlockStatement block = (BlockStatement) code; List stats = block.getStatements(); if (stats == null || stats.size() == 0) return null; Statement stat = (Statement) stats.get(0); if (!(stat instanceof ExpressionStatement)) return null; Expression expr = ((ExpressionStatement) stat).getExpression(); if (!(expr instanceof ConstructorCallExpression)) return null; return (ConstructorCallExpression) expr; } private void printConstructor(PrintWriter out, ClassNode clazz, ConstructorNode constructorNode) { printAnnotations(out, constructorNode); // printModifiers(out, constructorNode.getModifiers()); out.print("public "); // temporary hack String className = clazz.getNameWithoutPackage(); if (clazz instanceof InnerClassNode) className = className.substring(className.lastIndexOf("$") + 1); out.println(className); printParams(out, constructorNode); ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode); if (constrCall == null || !constrCall.isSpecialCall()) { out.println(" {}"); } else { out.println(" {"); printSpecialConstructorArgs(out, constructorNode, constrCall); out.println("}"); } } private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) { ClassNode type = node.getDeclaringClass(); ClassNode superType = type.getSuperClass(); for (ConstructorNode c : superType.getDeclaredConstructors()) { // Only look at things we can actually call if (c.isPublic() || c.isProtected()) { return c.getParameters(); } } // fall back for parameterless constructor if (superType.isPrimaryClassNode()) { return Parameter.EMPTY_ARRAY; } return null; } private void printSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) { // Select a constructor from our class, or super-class which is legal to call, // then write out an invoke w/nulls using casts to avoid ambiguous crapo Parameter[] params = selectAccessibleConstructorFromSuper(node); if (params != null) { out.print("super ("); for (int i = 0; i < params.length; i++) { printDefaultValue(out, params[i].getType()); if (i + 1 < params.length) { out.print(", "); } } out.println(");"); return; } // Otherwise try the older method based on the constructor's call expression Expression arguments = constrCall.getArguments(); if (constrCall.isSuperCall()) { out.print("super("); } else { out.print("this("); } // Else try to render some arguments if (arguments instanceof ArgumentListExpression) { ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments; List args = argumentListExpression.getExpressions(); for (Expression arg : args) { if (arg instanceof ConstantExpression) { ConstantExpression expression = (ConstantExpression) arg; Object o = expression.getValue(); if (o instanceof String) { out.print("(String)null"); } else { out.print(expression.getText()); } } else { ClassNode type = getConstructorArgumentType(arg, node); printDefaultValue(out, type); } if (arg != args.get(args.size() - 1)) { out.print(", "); } } } out.println(");"); } private ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) { if (!(arg instanceof VariableExpression)) return arg.getType(); VariableExpression vexp = (VariableExpression) arg; String name = vexp.getName(); for (Parameter param : node.getParameters()) { if (param.getName().equals(name)) { return param.getType(); } } return vexp.getType(); } private void printMethod(PrintWriter out, ClassNode clazz, MethodNode methodNode) { if (methodNode.getName().equals("")) return; if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return; if (methodNode.isSynthetic() && methodNode.getName().equals("$getStaticMetaClass")) return; printAnnotations(out, methodNode); if (!clazz.isInterface()) printModifiers(out, methodNode.getModifiers()); printGenericsBounds(out, methodNode.getGenericsTypes()); out.print(" "); printType(out, methodNode.getReturnType()); out.print(" "); out.print(methodNode.getName()); printParams(out, methodNode); ClassNode[] exceptions = methodNode.getExceptions(); for (int i = 0; i < exceptions.length; i++) { ClassNode exception = exceptions[i]; if (i == 0) { out.print("throws "); } else { out.print(", "); } printType(out, exception); } if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) { out.println(";"); } else { out.print(" { "); ClassNode retType = methodNode.getReturnType(); printReturn(out, retType); out.println("}"); } } private void printReturn(PrintWriter out, ClassNode retType) { String retName = retType.getName(); if (!retName.equals("void")) { out.print("return "); printDefaultValue(out, retType); out.print(";"); } } private void printDefaultValue(PrintWriter out, ClassNode type) { if (type.redirect() != ClassHelper.OBJECT_TYPE && type.redirect() != ClassHelper.boolean_TYPE) { out.print("("); printType(out, type); out.print(")"); } if (ClassHelper.isPrimitiveType(type)) { if (type == ClassHelper.boolean_TYPE) { out.print("false"); } else { out.print("0"); } } else { out.print("null"); } } private void printType(PrintWriter out, ClassNode type) { if (type.isArray()) { printType(out, type.getComponentType()); out.print("[]"); } else if (java5 && type.isGenericsPlaceHolder()) { out.print(type.getGenericsTypes()[0].getName()); } else { printGenericsBounds(out, type, false); } } private void printTypeName(PrintWriter out, ClassNode type) { if (ClassHelper.isPrimitiveType(type)) { if (type == ClassHelper.boolean_TYPE) { out.print("boolean"); } else if (type == ClassHelper.char_TYPE) { out.print("char"); } else if (type == ClassHelper.int_TYPE) { out.print("int"); } else if (type == ClassHelper.short_TYPE) { out.print("short"); } else if (type == ClassHelper.long_TYPE) { out.print("long"); } else if (type == ClassHelper.float_TYPE) { out.print("float"); } else if (type == ClassHelper.double_TYPE) { out.print("double"); } else if (type == ClassHelper.byte_TYPE) { out.print("byte"); } else { out.print("void"); } } else { String name = type.getName(); // check for an alias ClassNode alias = currentModule.getImportType(name); if (alias != null) name = alias.getName(); out.print(name.replace('$', '.')); } } private void printGenericsBounds(PrintWriter out, ClassNode type, boolean skipName) { if (!skipName) printTypeName(out, type); if (!java5) return; if (!ClassHelper.isCachedType(type)) { printGenericsBounds(out, type.getGenericsTypes()); } } private void printGenericsBounds(PrintWriter out, GenericsType[] genericsTypes) { if (genericsTypes == null || genericsTypes.length == 0) return; out.print('<'); for (int i = 0; i < genericsTypes.length; i++) { if (i != 0) out.print(", "); out.print(genericsTypes[i].toString().replace("$",".")); } out.print('>'); } private void printParams(PrintWriter out, MethodNode methodNode) { out.print("("); Parameter[] parameters = methodNode.getParameters(); if (parameters != null && parameters.length != 0) { int lastIndex = parameters.length - 1; boolean vararg = parameters[lastIndex].getType().isArray(); for (int i = 0; i != parameters.length; ++i) { if (i == lastIndex && vararg) { printType(out, parameters[i].getType().getComponentType()); out.print("..."); } else { printType(out, parameters[i].getType()); } out.print(" "); out.print(parameters[i].getName()); if (i + 1 < parameters.length) { out.print(", "); } } } out.print(")"); } private void printAnnotations(PrintWriter out, AnnotatedNode annotated) { if (!java5) return; for (AnnotationNode annotation : annotated.getAnnotations()) { printAnnotation(out, annotation); } } private void printAnnotation(PrintWriter out, AnnotationNode annotation) { out.print("@" + annotation.getClassNode().getName() + "("); boolean first = true; Map members = annotation.getMembers(); for (String key : members.keySet()) { if (first) first = false; else out.print(", "); out.print(key + "=" + getAnnotationValue(members.get(key))); } out.print(") "); } private String getAnnotationValue(Object memberValue) { String val = "null"; if (memberValue instanceof ListExpression) { StringBuilder sb = new StringBuilder("{"); boolean first = true; ListExpression le = (ListExpression) memberValue; for (Expression e : le.getExpressions()) { if (first) first = false; else sb.append(","); sb.append(getAnnotationValue(e)); } sb.append("}"); val = sb.toString(); } else if (memberValue instanceof ConstantExpression) { ConstantExpression ce = (ConstantExpression) memberValue; Object constValue = ce.getValue(); if (constValue instanceof AnnotationNode) { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); printAnnotation(out, (AnnotationNode) constValue); val = writer.toString(); } else if (constValue instanceof Number || constValue instanceof Boolean) val = constValue.toString(); else val = "\"" + escapeStringAnnotationValue(constValue.toString()) + "\""; } else if (memberValue instanceof PropertyExpression || memberValue instanceof VariableExpression) { // assume must be static class field or enum value or class that Java can resolve val = ((Expression) memberValue).getText(); } else if (memberValue instanceof ClosureExpression) { // annotation closure; replaced with this specific class literal to cover the // case where annotation type uses Class for the closure's type val = "groovy.lang.Closure.class"; } else if (memberValue instanceof ClassExpression) { val = ((Expression) memberValue).getText() + ".class"; } return val; } private void printModifiers(PrintWriter out, int modifiers) { if ((modifiers & Opcodes.ACC_PUBLIC) != 0) out.print("public "); if ((modifiers & Opcodes.ACC_PROTECTED) != 0) out.print("protected "); if ((modifiers & Opcodes.ACC_PRIVATE) != 0) out.print("private "); if ((modifiers & Opcodes.ACC_STATIC) != 0) out.print("static "); if ((modifiers & Opcodes.ACC_SYNCHRONIZED) != 0) out.print("synchronized "); if ((modifiers & Opcodes.ACC_FINAL) != 0) out.print("final "); if ((modifiers & Opcodes.ACC_ABSTRACT) != 0) out.print("abstract "); } private void printImports(PrintWriter out, ClassNode classNode) { List imports = new ArrayList(); ModuleNode moduleNode = classNode.getModule(); for (ImportNode importNode : moduleNode.getStarImports()) { imports.add(importNode.getPackageName()); } for (ImportNode imp : moduleNode.getImports()) { if (imp.getAlias() == null) imports.add(imp.getType().getName()); } imports.addAll(Arrays.asList(ResolveVisitor.DEFAULT_IMPORTS)); for (String imp : imports) { String s = new StringBuilder() .append("import ") .append(imp) .append((imp.charAt(imp.length() - 1) == '.') ? "*;" : ";") .toString() .replace('$', '.'); out.println(s); } out.println(); } public void clean() { for (String path : toCompile) { new File(outputPath, path + ".java").delete(); } } private static String escapeStringAnnotationValue(String value) { return value.replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\""); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavaAwareCompilationUnit.java0000644001501200150120000001255111713765676030031 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import groovy.lang.GroovyClassLoader; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.io.File; import java.io.FileNotFoundException; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.classgen.VariableScopeVisitor; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.control.SourceUnit; /** * Created by IntelliJ IDEA. * User: Alex.Tkachman * Date: May 31, 2007 Time: 6:48:28 PM */ public class JavaAwareCompilationUnit extends CompilationUnit { private List javaSources; private JavaStubGenerator stubGenerator; private JavaCompilerFactory compilerFactory = new JavacCompilerFactory(); private File generationGoal; private boolean keepStubs; public JavaAwareCompilationUnit(CompilerConfiguration configuration) { this(configuration,null); } public JavaAwareCompilationUnit(CompilerConfiguration configuration, GroovyClassLoader groovyClassLoader) { super(configuration,null,groovyClassLoader); javaSources = new LinkedList(); Map options = configuration.getJointCompilationOptions(); generationGoal = (File) options.get("stubDir"); boolean useJava5 = configuration.getTargetBytecode().equals(CompilerConfiguration.POST_JDK5); stubGenerator = new JavaStubGenerator(generationGoal,false,useJava5); keepStubs = Boolean.TRUE.equals(options.get("keepStubs")); addPhaseOperation(new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode node) throws CompilationFailedException { if (javaSources.size() != 0) { VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(node); new JavaAwareResolveVisitor(JavaAwareCompilationUnit.this).startResolving(node,source); } } },Phases.CONVERSION); addPhaseOperation(new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { try { if (javaSources.size() != 0) stubGenerator.generateClass(classNode); } catch (FileNotFoundException fnfe) { source.addException(fnfe); } } },Phases.CONVERSION); } public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); // compile Java and clean up if (phase == Phases.SEMANTIC_ANALYSIS && javaSources.size() > 0) { for (ModuleNode module : getAST().getModules()) { module.setImportsResolved(false); } try { JavaCompiler compiler = compilerFactory.createCompiler(getConfiguration()); compiler.compile(javaSources, this); } finally { if (!keepStubs) stubGenerator.clean(); javaSources.clear(); } } } public void configure(CompilerConfiguration configuration) { super.configure(configuration); // GroovyClassLoader should be able to find classes compiled from java // sources File targetDir = configuration.getTargetDirectory(); if (targetDir != null) { final String classOutput = targetDir.getAbsolutePath(); getClassLoader().addClasspath(classOutput); } } private void addJavaSource(File file) { String path = file.getAbsolutePath(); for (String source : javaSources) { if (path.equals(source)) return; } javaSources.add(path); } public void addSources(String[] paths) { for (String path : paths) { File file = new File(path); if (file.getName().endsWith(".java")) addJavaSource(file); else addSource(file); } } public void addSources(File[] files) { for (File file : files) { if (file.getName().endsWith(".java")) addJavaSource(file); else addSource(file); } } public JavaCompilerFactory getCompilerFactory() { return compilerFactory; } public void setCompilerFactory(JavaCompilerFactory compilerFactory) { this.compilerFactory = compilerFactory; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/javac/JavacJavaCompiler.java0000644001501200150120000001703511627206700026432 0ustar miguelmiguel/* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.javac; import groovy.lang.GroovyClassLoader; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.net.URLClassLoader; import java.net.URL; import java.net.URISyntaxException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.runtime.DefaultGroovyMethods; public class JavacJavaCompiler implements JavaCompiler { private CompilerConfiguration config; public JavacJavaCompiler(CompilerConfiguration config) { this.config = config; } public void compile(List files, CompilationUnit cu) { String[] javacParameters = makeParameters(files, cu.getClassLoader()); StringWriter javacOutput = null; int javacReturnValue = 0; try { Class javac = findJavac(cu); Method method = null; try { method = javac.getMethod("compile", new Class[]{String[].class, PrintWriter.class}); javacOutput = new StringWriter(); PrintWriter writer = new PrintWriter(javacOutput); Object ret = method.invoke(null, javacParameters, writer); javacReturnValue = (Integer) ret; } catch (NoSuchMethodException e) { } if (method == null) { method = javac.getMethod("compile", new Class[]{String[].class}); Object ret = method.invoke(null, new Object[]{javacParameters}); javacReturnValue = (Integer) ret; } cu.getConfiguration().getOutput(); } catch (InvocationTargetException ite) { cu.getErrorCollector().addFatalError(new ExceptionMessage((Exception) ite.getCause(), true, cu)); } catch (Exception e) { cu.getErrorCollector().addFatalError(new ExceptionMessage(e, true, cu)); } if (javacReturnValue != 0) { switch (javacReturnValue) { case 1: addJavacError("Compile error during compilation with javac.", cu, javacOutput); break; case 2: addJavacError("Invalid commandline usage for javac.", cu, javacOutput); break; case 3: addJavacError("System error during compilation with javac.", cu, javacOutput); break; case 4: addJavacError("Abnormal termination of javac.", cu, javacOutput); break; default: addJavacError("unexpected return value by javac.", cu, javacOutput); break; } } else { // print warnings if any System.out.print(javacOutput); } } private void addJavacError(String header, CompilationUnit cu, StringWriter msg) { if (msg != null) { header = header + "\n" + msg.getBuffer().toString(); } else { header = header + "\nThis javac version does not support compile(String[],PrintWriter), " + "so no further details of the error are available. The message error text " + "should be found on System.err.\n"; } cu.getErrorCollector().addFatalError(new SimpleMessage(header, cu)); } private String[] makeParameters(List files, GroovyClassLoader parentClassLoader) { Map options = config.getJointCompilationOptions(); LinkedList paras = new LinkedList(); File target = config.getTargetDirectory(); if (target == null) target = new File("."); // defaults paras.add("-d"); paras.add(target.getAbsolutePath()); paras.add("-sourcepath"); paras.add(((File) options.get("stubDir")).getAbsolutePath()); // add flags String[] flags = (String[]) options.get("flags"); if (flags != null) { for (String flag : flags) { paras.add('-' + flag); } } boolean hadClasspath = false; // add namedValues String[] namedValues = (String[]) options.get("namedValues"); if (namedValues != null) { for (int i = 0; i < namedValues.length; i += 2) { String name = namedValues[i]; if (name.equals("classpath")) hadClasspath = true; paras.add('-' + name); paras.add(namedValues[i + 1]); } } // append classpath if not already defined if (!hadClasspath) { // add all classpaths that compilation unit sees StringBuffer resultPath = new StringBuffer(DefaultGroovyMethods.join(config.getClasspath(), File.pathSeparator)); ClassLoader cl = parentClassLoader; while (cl != null) { if (cl instanceof URLClassLoader) { for (URL u : ((URLClassLoader) cl).getURLs()) { try { resultPath.append(File.pathSeparator); resultPath.append(new File(u.toURI()).getPath()); } catch (URISyntaxException e) { // ignore it } } } cl = cl.getParent(); } paras.add("-classpath"); paras.add(resultPath.toString()); } // files to compile paras.addAll(files); return paras.toArray(new String[paras.size()]); } private Class findJavac(CompilationUnit cu) throws ClassNotFoundException { String main = "com.sun.tools.javac.Main"; try { return Class.forName(main); } catch (ClassNotFoundException e) {} try { ClassLoader cl = this.getClass().getClassLoader(); return cl.loadClass(main); } catch (ClassNotFoundException e) {} try { return ClassLoader.getSystemClassLoader().loadClass(main); } catch (ClassNotFoundException e) {} try { return cu.getClassLoader().getParent().loadClass(main); } catch (ClassNotFoundException e3) {} // couldn't find compiler - try to find tools.jar // based on java.home setting String javaHome = System.getProperty("java.home"); if (javaHome.toLowerCase(Locale.US).endsWith("jre")) { javaHome = javaHome.substring(0, javaHome.length() - 4); } File toolsJar = new File((javaHome + "/lib/tools.jar")); if (toolsJar.exists()) { GroovyClassLoader loader = cu.getClassLoader(); loader.addClasspath(toolsJar.getAbsolutePath()); return loader.loadClass(main); } throw new ClassNotFoundException("unable to locate the java compiler com.sun.tools.javac.Main, please change your classloader settings"); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/DgmConverter.java0000644001501200150120000002433311715031256024423 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import org.codehaus.groovy.classgen.asm.BytecodeHelper; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.GeneratedMetaMethod; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.DateGroovyMethods; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.EncodingGroovyMethods; import org.codehaus.groovy.runtime.ProcessGroovyMethods; import org.codehaus.groovy.runtime.SqlGroovyMethods; import org.codehaus.groovy.runtime.SwingGroovyMethods; import org.codehaus.groovy.runtime.XmlGroovyMethods; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class DgmConverter implements Opcodes { private static final Class[] CLASSES = new Class[]{ DefaultGroovyMethods.class, SwingGroovyMethods.class, SqlGroovyMethods.class, XmlGroovyMethods.class, EncodingGroovyMethods.class, DateGroovyMethods.class, ProcessGroovyMethods.class }; public static void main(String[] args) throws IOException, ClassNotFoundException { boolean info = args.length == 1 && args[0].equals("--info"); List cachedMethodsList = new ArrayList(); for (Class aClass : CLASSES) { Collections.addAll(cachedMethodsList, ReflectionCache.getCachedClass(aClass).getMethods()); } final CachedMethod[] cachedMethods = cachedMethodsList.toArray(new CachedMethod[cachedMethodsList.size()]); List records = new ArrayList(); int cur = 0; for (CachedMethod method : cachedMethods) { if (!method.isStatic() || !method.isPublic()) continue; if (method.getCachedMethod().getAnnotation(Deprecated.class) != null) continue; if (method.getParameterTypes().length == 0) continue; final Class returnType = method.getReturnType(); final String className = "org/codehaus/groovy/runtime/dgm$" + cur++; GeneratedMetaMethod.DgmMethodRecord record = new GeneratedMetaMethod.DgmMethodRecord(); records.add(record); record.methodName = method.getName(); record.returnType = method.getReturnType(); record.parameters = method.getNativeParameterTypes(); record.className = className; ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(V1_3, ACC_PUBLIC, className, null, "org/codehaus/groovy/reflection/GeneratedMetaMethod", null); createConstructor(cw); final String methodDescriptor = BytecodeHelper.getMethodDescriptor(returnType, method.getNativeParameterTypes()); createInvokeMethod(method, cw, returnType, methodDescriptor); createDoMethodInvokeMethod(method, cw, className, returnType, methodDescriptor); createIsValidMethodMethod(method, cw, className); cw.visitEnd(); final byte[] bytes = cw.toByteArray(); final FileOutputStream fileOutputStream = new FileOutputStream("target/classes/" + className + ".class"); fileOutputStream.write(bytes); fileOutputStream.flush(); fileOutputStream.close(); } GeneratedMetaMethod.DgmMethodRecord.saveDgmInfo(records, "target/classes/META-INF/dgminfo"); if (info) System.out.println("Saved " + cur + " dgm records to: target/classes/META-INF/dgminfo"); } private static void createConstructor(ClassWriter cw) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "", "(Ljava/lang/String;Lorg/codehaus/groovy/reflection/CachedClass;Ljava/lang/Class;[Ljava/lang/Class;)V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ALOAD, 3); mv.visitVarInsn(ALOAD, 4); mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/reflection/GeneratedMetaMethod", "", "(Ljava/lang/String;Lorg/codehaus/groovy/reflection/CachedClass;Ljava/lang/Class;[Ljava/lang/Class;)V"); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private static void createIsValidMethodMethod(CachedMethod method, ClassWriter cw, String className) { MethodVisitor mv; if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) { // 1 param meta method mv = cw.visitMethod(ACC_PUBLIC, "isValidMethod", "([Ljava/lang/Class;)Z", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); Label l0 = new Label(); mv.visitJumpInsn(IFNULL, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;"); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "isAssignableFrom", "(Ljava/lang/Class;)Z"); Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); mv.visitLabel(l0); mv.visitInsn(ICONST_1); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); mv.visitInsn(IRETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } private static void createDoMethodInvokeMethod(CachedMethod method, ClassWriter cw, String className, Class returnType, String methodDescriptor) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "doMethodInvoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null); mv.visitCode(); if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) { mv.visitVarInsn(ALOAD, 1); BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass()); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;"); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "coerceArgument", "(Ljava/lang/Object;)Ljava/lang/Object;"); // cast argument to parameter class, inclusive unboxing // for methods with primitive types Class type = method.getParameterTypes()[1].getTheClass(); BytecodeHelper.doCast(mv, type); } else { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, className, "coerceArgumentsToClasses", "([Ljava/lang/Object;)[Ljava/lang/Object;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 1); BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass()); loadParameters(method, 2, mv); } mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(method.getDeclaringClass().getTheClass()), method.getName(), methodDescriptor); BytecodeHelper.box(mv, returnType); if (method.getReturnType() == void.class) { mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private static void createInvokeMethod(CachedMethod method, ClassWriter cw, Class returnType, String methodDescriptor) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); BytecodeHelper.doCast(mv, method.getParameterTypes()[0].getTheClass()); loadParameters(method, 2, mv); mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(method.getDeclaringClass().getTheClass()), method.getName(), methodDescriptor); BytecodeHelper.box(mv, returnType); if (method.getReturnType() == void.class) { mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } protected static void loadParameters(CachedMethod method, int argumentIndex, MethodVisitor mv) { CachedClass[] parameters = method.getParameterTypes(); int size = parameters.length - 1; for (int i = 0; i < size; i++) { // unpack argument from Object[] mv.visitVarInsn(ALOAD, argumentIndex); BytecodeHelper.pushConstant(mv, i); mv.visitInsn(AALOAD); // cast argument to parameter class, inclusive unboxing // for methods with primitive types Class type = parameters[i + 1].getTheClass(); BytecodeHelper.doCast(mv, type); } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/xml/0000755001501200150120000000000011627206700021754 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/xml/package.html0000644001501200150120000000027111627206700024235 0ustar miguelmiguel package org.codehaus.groovy.tools.xml.*

      XML utilities such as for converting XML into Groovy scripts.

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/xml/DomToGroovy.java0000644001501200150120000003205711627206700025056 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.xml; import groovy.util.IndentPrinter; import org.w3c.dom.*; import org.codehaus.groovy.syntax.Types; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.InputStream; import java.io.FileReader; import java.io.BufferedReader; import java.util.HashMap; import java.util.Map; import java.util.Collection; /** * A SAX handler for turning XML into Groovy scripts * * @author James Strachan * @author paulk */ public class DomToGroovy { protected IndentPrinter out; protected boolean inMixed = false; protected String qt = "'"; protected Collection keywords = Types.getKeywords(); public DomToGroovy(PrintWriter out) { this(new IndentPrinter(out)); } // TODO allow string quoting delimiter to be specified, e.g. ' vs " public DomToGroovy(IndentPrinter out) { this.out = out; } public void print(Document document) { printChildren(document, new HashMap()); } public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: DomToGroovy infilename [outfilename]"); System.exit(1); } Document document = null; try { document = parse(args[0]); } catch (Exception e) { System.out.println("Unable to parse input file '" + args[0] + "': " + e.getMessage()); System.exit(1); } PrintWriter writer = null; if (args.length < 2) { writer = new PrintWriter(System.out); } else { try { writer = new PrintWriter(new FileWriter(new File(args[1]))); } catch (IOException e) { System.out.println("Unable to create output file '" + args[1] + "': " + e.getMessage()); System.exit(1); } } DomToGroovy converter = new DomToGroovy(writer); converter.out.incrementIndent(); writer.println("#!/bin/groovy"); writer.println(); writer.println("// generated from " + args[0]); writer.println("System.out << new groovy.xml.StreamingMarkupBuilder().bind {"); converter.print(document); writer.println("}"); writer.close(); } // Implementation methods //------------------------------------------------------------------------- protected static Document parse(final String fileName) throws Exception { return parse(new File(fileName)); } public static Document parse(final File file) throws Exception { return parse(new BufferedReader(new FileReader(file))); } public static Document parse(final Reader input) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(input)); } public static Document parse(final InputStream input) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(input)); } protected void print(Node node, Map namespaces, boolean endWithComma) { switch (node.getNodeType()) { case Node.ELEMENT_NODE : printElement((Element) node, namespaces, endWithComma); break; case Node.PROCESSING_INSTRUCTION_NODE : printPI((ProcessingInstruction) node, endWithComma); break; case Node.TEXT_NODE : printText((Text) node, endWithComma); break; case Node.COMMENT_NODE : printComment((Comment) node, endWithComma); break; } } protected void printElement(Element element, Map namespaces, boolean endWithComma) { namespaces = defineNamespaces(element, namespaces); element.normalize(); printIndent(); String prefix = element.getPrefix(); boolean hasPrefix = prefix != null && prefix.length() > 0; String localName = getLocalName(element); boolean isKeyword = checkEscaping(localName); if (isKeyword || hasPrefix) print(qt); if (hasPrefix) { print(prefix); print("."); } print(localName); if (isKeyword || hasPrefix) print(qt); print("("); boolean hasAttributes = printAttributes(element); NodeList list = element.getChildNodes(); int length = list.getLength(); if (length == 0) { printEnd(")", endWithComma); } else { Node node = list.item(0); if (length == 1 && node instanceof Text) { Text textNode = (Text) node; String text = getTextNodeData(textNode); if (hasAttributes) print(", "); printQuoted(text); printEnd(")", endWithComma); } else if (mixedContent(list)) { println(") {"); out.incrementIndent(); boolean oldInMixed = inMixed; inMixed = true; for (node = element.getFirstChild(); node != null; node = node.getNextSibling()) { print(node, namespaces, false); } inMixed = oldInMixed; out.decrementIndent(); printIndent(); printEnd("}", endWithComma); } else { println(") {"); out.incrementIndent(); printChildren(element, namespaces); out.decrementIndent(); printIndent(); printEnd("}", endWithComma); } } } protected void printQuoted(String text) { if (text.indexOf("\n") != -1) { print("'''"); print(text); print("'''"); } else { print(qt); print(escapeQuote(text)); print(qt); } } protected void printPI(ProcessingInstruction instruction, boolean endWithComma) { printIndent(); print("mkp.pi(" + qt); print(instruction.getTarget()); print(qt + ", " + qt); print(instruction.getData()); printEnd(qt + ");", endWithComma); } protected void printComment(Comment comment, boolean endWithComma) { String text = comment.getData().trim(); if (text.length() >0) { printIndent(); print("/* "); print(text); printEnd(" */", endWithComma); } } protected void printText(Text node, boolean endWithComma) { String text = getTextNodeData(node); if (text.length() > 0) { printIndent(); if (inMixed) print("mkp.yield "); printQuoted(text); printEnd("", endWithComma); } } protected String escapeQuote(String text) { return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt); } protected Map defineNamespaces(Element element, Map namespaces) { Map answer = null; String prefix = element.getPrefix(); if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { answer = new HashMap(namespaces); defineNamespace(answer, prefix, element.getNamespaceURI()); } NamedNodeMap attributes = element.getAttributes(); int length = attributes.getLength(); for (int i = 0; i < length; i++) { Attr attribute = (Attr) attributes.item(i); prefix = attribute.getPrefix(); if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { if (answer == null) { answer = new HashMap(namespaces); } defineNamespace(answer, prefix, attribute.getNamespaceURI()); } } return (answer != null) ? answer : namespaces; } protected void defineNamespace(Map namespaces, String prefix, String uri) { namespaces.put(prefix, uri); if (!prefix.equals("xmlns") && !prefix.equals("xml")) { printIndent(); print("mkp.declareNamespace("); print(prefix); print(":" + qt); print(uri); println(qt + ")"); } } protected boolean printAttributes(Element element) { boolean hasAttribute = false; NamedNodeMap attributes = element.getAttributes(); int length = attributes.getLength(); if (length > 0) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { printAttributeWithPrefix((Attr) attributes.item(i), buffer); } for (int i = 0; i < length; i++) { hasAttribute = printAttributeWithoutPrefix((Attr) attributes.item(i), hasAttribute); } if (buffer.length() > 0) { if (hasAttribute) { print(", "); } print(buffer.toString()); hasAttribute = true; } } return hasAttribute; } protected void printAttributeWithPrefix(Attr attribute, StringBuffer buffer) { String prefix = attribute.getPrefix(); if (prefix != null && prefix.length() > 0 && !prefix.equals("xmlns")) { if (buffer.length() > 0) { buffer.append(", "); } buffer.append(qt); buffer.append(prefix); buffer.append(":"); buffer.append(getLocalName(attribute)); buffer.append(qt + ":" + qt); buffer.append(escapeQuote(getAttributeValue(attribute))); buffer.append(qt); } } protected String getAttributeValue(Attr attribute) { return attribute.getValue(); } protected boolean printAttributeWithoutPrefix(Attr attribute, boolean hasAttribute) { String prefix = attribute.getPrefix(); if (prefix == null || prefix.length() == 0) { if (!hasAttribute) { hasAttribute = true; } else { print(", "); } String localName = getLocalName(attribute); boolean needsEscaping = checkEscaping(localName); if (needsEscaping) print(qt); print(localName); if (needsEscaping) print(qt); print(":"); printQuoted(getAttributeValue(attribute)); } return hasAttribute; } protected boolean checkEscaping(String localName) { return keywords.contains(localName) || localName.contains("-") || localName.contains(":") || localName.contains("."); } protected String getTextNodeData(Text node) { return node.getData().trim(); } protected boolean mixedContent(NodeList list) { boolean hasText = false; boolean hasElement = false; for (int i = 0, size = list.getLength(); i < size; i++) { Node node = list.item(i); if (node instanceof Element) { hasElement = true; } else if (node instanceof Text) { String text = getTextNodeData((Text) node); if (text.length() > 0) { hasText = true; } } } return hasText && hasElement; } protected void printChildren(Node parent, Map namespaces) { for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) { print(node, namespaces, false); } } protected String getLocalName(Node node) { String answer = node.getLocalName(); if (answer == null) { answer = node.getNodeName(); } return answer.trim(); } protected void printEnd(String text, boolean endWithComma) { if (endWithComma) { print(text); println(","); } else { println(text); } } protected void println(String text) { out.println(text); } protected void print(String text) { out.print(text); } protected void printIndent() { out.printIndent(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/Compiler.java0000644001501200150120000000555611627206700023604 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.io.File; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.SourceUnit; /** * A convenience front end for getting standard compilations done. * All compile() routines generate classes to the filesystem. * * @author Chris Poirier * * @version $Id$ */ public class Compiler { // TODO: delete this constant? public static final Compiler DEFAULT = new Compiler(); private CompilerConfiguration configuration = null; // Optional configuration data /** * Initializes the Compiler with default configuration. */ public Compiler() { configuration = null; } /** * Initializes the Compiler with the specified configuration. */ public Compiler( CompilerConfiguration configuration ) { this.configuration = configuration; } /** * Compiles a single File. */ public void compile( File file ) throws CompilationFailedException { CompilationUnit unit = new CompilationUnit( configuration ); unit.addSource( file ); unit.compile(); } /** * Compiles a series of Files. */ public void compile( File[] files ) throws CompilationFailedException { CompilationUnit unit = new CompilationUnit( configuration ); unit.addSources( files ); unit.compile(); } /** * Compiles a series of Files from file names. */ public void compile( String[] files ) throws CompilationFailedException { CompilationUnit unit = new CompilationUnit( configuration ); unit.addSources( files ); unit.compile(); } /** * Compiles a string of code. */ public void compile( String name, String code ) throws CompilationFailedException { CompilationUnit unit = new CompilationUnit( configuration ); unit.addSource( new SourceUnit(name, code, configuration, unit.getClassLoader(), unit.getErrorCollector()) ); unit.compile(); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/GroovyClass.java0000644001501200150120000000210211627206700024265 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; public class GroovyClass { public static final GroovyClass[] EMPTY_ARRAY = new GroovyClass[ 0 ]; private String name; private byte[] bytes; public GroovyClass(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } public String getName() { return this.name; } public byte[] getBytes() { return this.bytes; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/0000755001501200150120000000000011713765676022305 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Groovysh.properties0000644001501200150120000000151611627206700026224 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # # # Informational and error messages # info.error=ERROR: {0} info.fatal=FATAL: {0} # # Misc messages # startup_banner.0=@|green Groovy Shell|@ ({0}, JVM: {1}) startup_banner.1=Type '@|bold help|@' or '@|bold \\h|@' for help. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandAlias.properties0000644001501200150120000000121611627206700026731 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # info.alias_to=Alias to: @|bold {0}|@ groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/IO.java0000644001501200150120000001142011707612046023436 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import org.codehaus.groovy.tools.shell.util.Preferences; import org.fusesource.jansi.AnsiRenderWriter; /** * Container for input/output handles. * * @version $Id$ * @author Jason Dillon */ public class IO { /** Raw input stream. */ public final InputStream inputStream; /** Raw output stream. */ public final OutputStream outputStream; /** Raw error output stream. */ public final OutputStream errorStream; /** Prefered input reader. */ public final Reader in; /** Prefered output writer. */ public final PrintWriter out; /** Prefered error output writer. */ public final PrintWriter err; /** * Construct a new IO container. */ public IO(final InputStream inputStream, final OutputStream outputStream, final OutputStream errorStream) { assert inputStream != null; assert outputStream != null; assert errorStream != null; this.inputStream = inputStream; this.outputStream = outputStream; this.errorStream = errorStream; this.in = new InputStreamReader(inputStream); this.out = new AnsiRenderWriter(outputStream, true); this.err = new AnsiRenderWriter(errorStream, true); } /** * Construct a new IO container using system streams. */ public IO() { this(System.in, System.out, System.err); } /** * Set the verbosity level. * * @param verbosity */ public void setVerbosity(final Verbosity verbosity) { assert verbosity != null; Preferences.verbosity = verbosity; } /** * Returns the verbosity level. */ public Verbosity getVerbosity() { return Preferences.verbosity; } /** * Check if the verbosity level is set to {@link Verbosity#QUIET}. */ public boolean isQuiet() { return getVerbosity() == Verbosity.QUIET; } /** * Check if the verbosity level is set to {@link Verbosity#INFO}. */ public boolean isInfo() { return getVerbosity() == Verbosity.INFO; } /** * Check if the verbosity level is set to {@link Verbosity#VERBOSE}. */ public boolean isVerbose() { return getVerbosity() == Verbosity.VERBOSE; } /** * Check if the verbosity level is set to {@link Verbosity#DEBUG}. * *

      For general usage, when debug output is required, it is better * to use the logging facility instead. */ public boolean isDebug() { return getVerbosity() == Verbosity.DEBUG; } /** * Flush both output streams. */ public void flush() throws IOException { out.flush(); err.flush(); } /** * Close all streams. */ public void close() throws IOException { in.close(); out.close(); err.close(); } // // Verbosity // public static final class Verbosity { public static final Verbosity QUIET = new Verbosity("QUIET"); public static final Verbosity INFO = new Verbosity("INFO"); public static final Verbosity VERBOSE = new Verbosity("VERBOSE"); public static final Verbosity DEBUG = new Verbosity("DEBUG"); public final String name; private Verbosity(final String name) { this.name = name; } public String toString() { return name; } public static Verbosity forName(final String name) { assert name != null; if (QUIET.name.equalsIgnoreCase(name)) { return QUIET; } if (INFO.name.equalsIgnoreCase(name)) { return INFO; } if (VERBOSE.name.equalsIgnoreCase(name)) { return VERBOSE; } if (DEBUG.name.equalsIgnoreCase(name)) { return DEBUG; } throw new IllegalArgumentException("Invalid verbosity name: " + name); } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/ComplexCommandSupport.groovy0000644001501200150120000000520111627206700030033 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.SimpleCompletor /** * Support for more complex commands. * * @version $Id$ * @author Jason Dillon */ abstract class ComplexCommandSupport extends CommandSupport { protected List/**/ functions protected String defaultFunction ComplexCommandSupport(final Shell shell, final String name, final String shortcut) { super(shell, name, shortcut) } protected List createCompletors() { def c = new SimpleCompletor() functions.each { c.add(it) } return [ c, null ] } Object execute(List args) { assert args != null if (args.size() == 0) { if (defaultFunction) { args = [ defaultFunction ] } else { fail("Command '$name' requires at least one argument") } } return executeFunction(args) } protected executeFunction(List args) { assert args != null assert functions def fname = args[0] if (args.size() > 1) { args = args[1..-1] } else { args = [] } if (fname in functions) { def func = loadFunction(fname) log.debug("Invoking function '$fname' w/args: $args") return func.call(args) } else { fail("Unknown function name: $fname") } } protected Closure loadFunction(final String name) { assert name try { return this."do_${name}" } catch (MissingPropertyException e) { fail("Failed to load delgate function: $e") } } def do_all = { functions.each { fname -> if (fname != 'all') { executeFunction([ fname ]) } } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandException.java0000644001501200150120000000233011713765676026403 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell; /** * Thrown to indicate a problem with command execution. * * @version $Id$ * @author Jason Dillon */ public class CommandException extends Exception { private final Command command; public CommandException(final Command command, String msg) { super(msg); this.command = command; } public CommandException(final Command command, String msg, Throwable cause) { super(msg, cause); this.command = command; } public Command getCommand() { return command; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Interpreter.groovy0000644001501200150120000000543211627206700026041 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.Logger import org.codehaus.groovy.runtime.MethodClosure import java.lang.reflect.Method /** * Helper to interpret a source buffer. * * @version $Id$ * @author Jason Dillon */ class Interpreter { static final String SCRIPT_FILENAME = 'groovysh_evaluate' private final Logger log = Logger.create(this.class) private final GroovyShell shell Interpreter(final ClassLoader classLoader, final Binding binding) { assert classLoader assert binding shell = new GroovyShell(classLoader, binding) } Binding getContext() { return shell.getContext() } GroovyClassLoader getClassLoader() { return shell.getClassLoader() } def evaluate(final List buffer) { assert buffer def source = buffer.join(Parser.NEWLINE) def result Class type try { Script script = shell.parse(source, SCRIPT_FILENAME) type = script.getClass() log.debug("Compiled script: $script") if (type.declaredMethods.any { it.name == 'main' }) { result = script.run() } // Need to use String.valueOf() here to avoid icky exceptions causes by GString coercion log.debug("Evaluation result: ${String.valueOf(result)} (${result?.getClass()})") // Keep only the methods that have been defined in the script type.declaredMethods.each { Method m -> if (!(m.name in [ 'main', 'run' ] || m.name.startsWith('super$') || m.name.startsWith('class$') || m.name.startsWith('$'))) { log.debug("Saving method definition: $m") context["${m.name}"] = new MethodClosure(type.newInstance(), m.name) } } } finally { def cache = classLoader.classCache // Remove the script class generated cache.remove(type?.name) // Remove the inline closures from the cache as well cache.remove('$_run_closure') } return result } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/ReflectionCompletor.groovy0000644001501200150120000001036111713765676027534 0ustar miguelmiguelpackage org.codehaus.groovy.tools.shell import jline.Completor import org.codehaus.groovy.runtime.InvokerHelper /** * Implements the Completor interface to provide competions for * GroovyShell by using reflection on global variables. * * @author Marty Saxton */ class ReflectionCompletor implements Completor { private Shell shell; ReflectionCompletor(Shell shell) { this.shell = shell } int complete(String buffer, int cursor, List candidates) { int identifierStart = findIdentifierStart(buffer, cursor) String identifierPrefix = identifierStart != -1 ? buffer.substring(identifierStart, cursor) : "" int lastDot = buffer.lastIndexOf('.') // if there are no dots, and there is a valid identifier prefix if (lastDot == -1 ) { if (identifierStart != -1) { List myCandidates = findMatchingVariables(identifierPrefix) if (myCandidates.size() > 0) { candidates.addAll(myCandidates) return identifierStart } } } else { // there are 1 or more dots // if ends in a dot, or if there is a valid identifier prefix if (lastDot == cursor-1 || identifierStart != -1){ // evaluate the part before the dot to get an instance String instanceRefExpression = buffer.substring(0, lastDot) def instance = shell.interp.evaluate([instanceRefExpression]) if (instance != null) { // look for public methods/fields that match the prefix List myCandidates = getPublicFieldsAndMethods(instance, identifierPrefix) if (myCandidates.size() > 0) { candidates.addAll(myCandidates) return lastDot+1 } } } } // no candidates return -1 } /** * Parse a buffer to determine the start index of the groovy identifier * @param buffer the buffer to parse * @param endingAt the end index with the buffer * @return the start index of the identifier, or -1 if the buffer * does not contain a valid identifier that ends at endingAt */ int findIdentifierStart(String buffer, int endingAt) { // if the string is empty then there is no expression if (endingAt == 0) return -1 // if the last character is not valid then there is no expression char lastChar = buffer.charAt(endingAt-1) if (!Character.isJavaIdentifierPart(lastChar)) return -1 // scan backwards until the beginning of the expression is found int startIndex = endingAt-1 while (startIndex > 0 && Character.isJavaIdentifierPart(buffer.charAt(startIndex-1))) --startIndex return startIndex } /** * Build a list of public fields and methods for an object * that match a given prefix. * @param instance the object * @param prefix the prefix that must be matched * @return the list of public methods and fields that begin with the prefix */ List getPublicFieldsAndMethods(Object instance, String prefix) { def rv = [] instance.class.fields.each { if (it.name.startsWith(prefix)) rv << it.name } instance.class.methods.each { if (it.name.startsWith(prefix)) rv << it.name + (it.parameterTypes.length == 0 ? "()" : "(") } InvokerHelper.getMetaClass(instance).metaMethods.each { if (it.name.startsWith(prefix)) rv << it.name + (it.parameterTypes.length == 0 ? "()" : "(") } return rv.sort().unique() } /** * Build a list of variables defined in the shell that * match a given prefix. * @param prefix the prefix to match * @return the list of variables that match the prefix */ List findMatchingVariables(String prefix) { def matches = [] for (String varName in shell.interp.context.variables.keySet()) if (varName.startsWith(prefix)) matches << varName return matches } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/package.html0000644001501200150120000000143611627206700024550 0ustar miguelmiguel

      Provides support for the Groovy Shell (aka. groovysh).

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Command.java0000644001501200150120000000227311713765676024532 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell; import jline.Completor; import java.util.List; /** * Provides the interface required for command extensions. * * @version $Id$ * @author Jason Dillon */ public interface Command { public String getName(); public String getShortcut(); public Completor getCompletor(); public String getDescription(); public String getUsage(); public String getHelp(); public List/**/ getAliases(); public Object execute(List args); public boolean getHidden(); } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/0000755001501200150120000000000011714271434024067 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/InspectCommand.groovy0000644001501200150120000000660211627206700030243 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import groovy.inspect.swingui.ObjectBrowser import java.awt.HeadlessException import javax.swing.UIManager import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.SimpleCompletor /** * The 'inspect' command. * * @version $Id$ * @author Jason Dillon */ class InspectCommand extends CommandSupport { InspectCommand(final Shell shell) { super(shell, 'inspect', '\\n') } def lafInitialized = false def headless protected List createCompletors() { return [ new InspectCommandCompletor(binding), null ] } Object execute(final List args) { assert args != null log.debug("Inspecting w/args: $args") if (args.size() > 1) { fail(messages.format('error.unexpected_args', args.join(' '))) } def subject if (args.size() == 1) { subject = binding.variables[args[0]] } else { subject = binding.variables['_'] } if (!subject) { io.out.println('Subject is null; nothing to inspect') // TODO: i18n } else { // Only set LAF once. if (!lafInitialized) { lafInitialized = true try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) // The setLAF doesn't throw a HeadlessException on Mac. // So try really creating a frame. new java.awt.Frame().dispose() headless = false } catch (HeadlessException he) { headless = true } } if (headless) { io.err.println("@|red ERROR:|@ Running in AWT Headless mode, 'inspect' is not available.") return } if (io.verbose) { io.out.println("Launching object browser to inspect: $subject") // TODO: i18n } ObjectBrowser.inspect(subject) } } } /** * Completor for the 'inspect' command. * * @version $Id$ * @author Jason Dillon */ class InspectCommandCompletor extends SimpleCompletor { private final Binding binding InspectCommandCompletor(final Binding binding) { assert binding this.binding = binding } SortedSet getCandidates() { def set = new TreeSet() binding.variables.keySet().each { set << it } return set } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ClearCommand.groovy0000644001501200150120000000231411627206700027660 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'clear' command. * * @version $Id$ * @author Jason Dillon */ class ClearCommand extends CommandSupport { ClearCommand(final Shell shell) { super(shell, 'clear', '\\c') } Object execute(final List args) { assertNoArguments(args) buffer.clear() if (io.verbose) { io.out.println('Buffer cleared') // TODO: i18n } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ExitCommand.groovy0000644001501200150120000000257711627206700027556 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.ExitNotification /** * The 'exit' command. * * @version $Id$ * @author Jason Dillon */ class ExitCommand extends CommandSupport { ExitCommand(final Shell shell) { super(shell, 'exit', '\\x') alias('quit', '\\q') } Object execute(final List args) { assertNoArguments(args) // // TODO: Maybe support a single arg for the code? // if (io.verbose) { io.out.println(messages['info.bye']) } throw new ExitNotification(0) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/InspectCommand.properties0000644001501200150120000000150011627206700031102 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Inspect a variable or the last result with the GUI object browser command.usage=[] command.help=Opens the GUI object browser to inspect a variable or the result of the last evaluation. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/RegisterCommand.groovy0000644001501200150120000000433111627206700030417 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.Command /** * The 'register' command. * * @version $Id$ * @author Chris K Wensel */ class RegisterCommand extends CommandSupport { RegisterCommand(final Shell shell) { super(shell, "register", "\\rc") } public Object execute(List args) { assert args != null if (args.size() < 1) { fail("Command 'register' requires at least 1 arguments") // TODO: i18n } String classname = args.get(0) Class type = getClassLoader().loadClass(classname) Command command = null; if (args.size() == 1) { // use default name command = type.newInstance(shell) } else if (args.size() == 2) { // pass name to ctor command = type.newInstance(shell, args.get(1), null) } else if (args.size() == 3) { // pass name, alias to ctor command = type.newInstance(shell, args.get(1), args.get(2)) } def oldcommand = registry[command.name] // let's prevent collisions if (oldcommand) { fail("Can not rebind command: ${command.name}") // TODO: i18n } if (log.debugEnabled) { log.debug("Created command '${command.name}': $command") } command = shell << command if (shell.runner) { shell.runner.completor << command } } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ClearCommand.properties0000644001501200150120000000147011714271434030534 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Clear the buffer and reset the prompt counter. command.usage= command.help=Clears the current buffer, resetting the prompt counter to 000. Can be used to recover from compilation errors. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/LoadCommand.groovy0000644001501200150120000000407511627206700027517 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import jline.FileNameCompletor import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'load' command. * * @version $Id$ * @author Jason Dillon */ class LoadCommand extends CommandSupport { LoadCommand(final Shell shell) { super(shell, 'load', '\\l') alias('.', '\\.') } protected List createCompletors() { return [ new FileNameCompletor() ] } Object execute(final List args) { assert args != null if (args.size() == 0) { fail("Command 'load' requires at least one argument") // TODO: i18n } for (source in args) { URL url log.debug("Attempting to load: $url") try { url = new URL("$source") } catch (MalformedURLException e) { def file = new File("$source") if (!file.exists()) { fail("File not found: $file") // TODO: i18n } url = file.toURI().toURL() } load(url) } } void load(final URL url) { assert url != null if (io.verbose) { io.out.println("Loading: $url") } url.eachLine { shell << it } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/DisplayCommand.groovy0000644001501200150120000000237711627206700030250 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'display' command. * * @version $Id$ * @author Jason Dillon */ class DisplayCommand extends CommandSupport { DisplayCommand(final Shell shell) { super(shell, 'display', '\\d') } Object execute(final List args) { assertNoArguments(args) if (buffer.isEmpty()) { io.out.println('Buffer is empty') // TODO: i18n } else { shell.displayBuffer(buffer) } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/SetCommand.groovy0000644001501200150120000000460711627206700027374 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.SimpleCompletor import org.codehaus.groovy.tools.shell.util.Preferences /** * The 'set' command, used to set preferences. * * @version $Id$ * @author Jason Dillon */ class SetCommand extends CommandSupport { SetCommand(final Shell shell) { super(shell, 'set', '\\=') } protected List createCompletors() { def loader = { def list = [] def keys = Preferences.keys() keys.each { list << it } return list } return [ new SimpleCompletor(loader), null ] } Object execute(final List args) { assert args != null if (args.size() == 0) { def keys = Preferences.keys() if (keys.size() == 0) { io.out.println('No preferences are set') return } else { io.out.println('Preferences:') keys.each { def value = Preferences.get(it, null) println(" $it=$value") } } return } if (args.size() > 2) { fail("Command '$name' requires arguments: []") } def name = args[0] def value if (args.size() == 1) { value = true } else { value = args[1] } log.debug("Setting preference: $name=$value") Preferences.put(name, String.valueOf(value)) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/EditCommand.properties0000644001501200150120000000131111627206700030362 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Edit the current buffer command.usage= command.help=Edit the current buffer. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/HistoryCommand.groovy0000644001501200150120000000634011627206700030276 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.ComplexCommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.SimpleCompletor /** * The 'history' command. * * @version $Id$ * @author Jason Dillon */ class HistoryCommand extends ComplexCommandSupport { HistoryCommand(final Shell shell) { super(shell, 'history', '\\H') this.functions = [ 'show', 'clear', 'flush', 'recall' ] this.defaultFunction = 'show' } protected List createCompletors() { def loader = { def list = [] functions.each { list << it } return list } return [ new SimpleCompletor(loader), null ] } Object execute(List args) { if (!history) { fail("Shell does not appear to be interactive; Can not query history") } super.execute(args) // Don't return anything return null } def do_show = { history.historyList.eachWithIndex { item, i -> i = i.toString().padLeft(3, ' ') io.out.println(" @|bold $i|@ $item") } } def do_clear = { history.clear() if (io.verbose) { io.out.println('History cleared') } } def do_flush = { history.flushBuffer() if (io.verbose) { io.out.println('History flushed') } } def do_recall = { args -> def line if (args.size() != 1) { fail("History recall requires a single history identifer") } def id = args[0] // // FIXME: This won't work as desired because the history shifts when we run recall and could internally shift more from alias redirection // try { id = Integer.parseInt(id) if (shell.historyFull) { // if history was full before execution of the command, then the recall command itself // has been added to history before it actually gets executed // so we need to shift by one id-- }; line = id<0?shell.evictedLine:history.historyList[id] } catch (Exception e) { fail("Invalid history identifier: $id", e) } log.debug("Recalling history item #$id: $line") return shell.execute(line) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ShadowCommand.groovy0000644001501200150120000000273011627206700030061 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.ComplexCommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.Preferences /** * The 'shadow' command. * * @version $Id$ * @author Jason Dillon */ class ShadowCommand extends ComplexCommandSupport { ShadowCommand(final Shell shell) { super(shell, 'shadow', '\\&') this.hidden = true this.functions = [ 'debug', 'verbose', 'info', 'this' ] } def do_debug = { Preferences.verbosity = IO.Verbosity.DEBUG } def do_verbose = { Preferences.verbosity = IO.Verbosity.VERBOSE } def do_info = { Preferences.verbosity = IO.Verbosity.INFO } def do_this = { return this } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/RecordCommand.properties0000644001501200150120000000140011627206700030712 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Record the current session to a file command.usage=[start []|stop|status] command.help=Record the current session to a file. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/SaveCommand.groovy0000644001501200150120000000371411627206700027535 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import jline.FileNameCompletor import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'save' command. * * @version $Id$ * @author Jason Dillon */ class SaveCommand extends CommandSupport { SaveCommand(final Shell shell) { super(shell, 'save', '\\s') } protected List createCompletors() { return [ new FileNameCompletor(), null ] } Object execute(final List args) { assert args != null if (args.size() != 1) { fail("Command 'save' requires a single file argument") // TODO: i18n } if (buffer.isEmpty()) { io.out.println('Buffer is empty') // TODO: i18n return } // // TODO: Support special '-' file to simply dump text to io.out // def file = new File("${args[0]}") if (io.verbose) { io.out.println("Saving current buffer to file: $file") // TODO: i18n } def dir = file.parentFile if (dir && !dir.exists()) { log.debug("Creating parent directory path: $dir") dir.mkdirs() } file.write(buffer.join(NEWLINE)) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ExitCommand.properties0000644001501200150120000000130711627206700030413 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Exit the shell command.usage= command.help=Exit the shell. info.bye=Bye! groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ShadowCommand.properties0000644001501200150120000000131011627206700030721 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Uber foo, muck & fluff command.usage= command.help=Uber foo, muck & fluff. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/PurgeCommand.properties0000644001501200150120000000142711627206700030567 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Purge variables, classes, imports or preferences command.usage=()+ command.help=Purges objects from the shell. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ShowCommand.groovy0000644001501200150120000000612311627206700027554 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.runtime.MethodClosure import org.codehaus.groovy.tools.shell.ComplexCommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.Preferences /** * The 'show' command. * * @version $Id$ * @author Jason Dillon */ class ShowCommand extends ComplexCommandSupport { ShowCommand(final Shell shell) { super(shell, 'show', '\\S') this.functions = [ 'variables', 'classes', 'imports', 'preferences', 'all' ] } def do_variables = { if (variables.isEmpty()) { io.out.println('No variables defined') // TODO: i18n } else { io.out.println('Variables:') // TODO: i18n variables.each { key, value -> // Special handling for defined methods, just show the sig if (value instanceof MethodClosure) { // // TODO: Would be nice to show the argument types it will accept... // value = "method ${value.method}()" } // Need to use String.valueOf() here to avoid icky exceptions causes by GString coercion io.out.println(" $key = ${String.valueOf(value)}") } } } def do_classes = { def classes = classLoader.loadedClasses if (classes.size() == 0) { io.out.println("No classes have been loaded") // TODO: i18n } else { io.out.println('Classes:') // TODO: i18n classes.each { io.out.println(" $it") } } } def do_imports = { if (imports.isEmpty()) { io.out.println("No custom imports have been defined") // TODO: i18n } else { io.out.println("Custom imports:") // TODO: i18n imports.each { io.out.println(" $it") } } } def do_preferences = { def keys = Preferences.keys() if (keys.size() == 0) { io.out.println('No preferences are set') return } else { io.out.println('Preferences:') keys.each { def value = Preferences.get(it, null) println(" $it=$value") } } return } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/EditCommand.groovy0000644001501200150120000000423611707612046027527 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.Preferences /** * The 'edit' command. * * @version $Id$ * @author Jason Dillon */ class EditCommand extends CommandSupport { EditCommand(final Shell shell) { super(shell, 'edit', '\\e') } private String getEditorCommand() { def editor = Preferences.editor; log.debug("Using editor: $editor") if (!editor) { fail("Unable to determine which editor to use; check \$EDITOR") // TODO: i18n } return editor } Object execute(final List args) { assertNoArguments(args) def file = File.createTempFile('groovysh-buffer', '.groovy') file.deleteOnExit() try { // Write the current buffer to a tmp file file.write(buffer.join(NEWLINE)) // Try to launch the editor def cmd = "$editorCommand $file" log.debug("Executing: $cmd") def p = cmd.execute() // Wait for it to finish log.debug("Waiting for process: $p") p.waitFor() log.debug("Editor contents: ${file.text}") // Load the new lines... file.eachLine { shell << it } } finally { file.delete() } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/RegisterCommand.properties0000644001501200150120000000142311627206700031265 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Registers a new command with the shell command.usage= [] [alias] command.help=Registers the given @|BOLD classname|@ as a new command.groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/DisplayCommand.properties0000644001501200150120000000134011627206700031104 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Display the current buffer command.usage= command.help=Display the contents of the current buffer. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/SaveCommand.properties0000644001501200150120000000135711627206700030405 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Save the current buffer to a file command.usage= command.help=Saves the buffer's contents to @|BOLD file|@. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/HelpCommand.properties0000644001501200150120000000140111627206700030365 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Display this help message command.usage=[] command.help=Display the list of commands or the help text for @|BOLD command|@. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/HistoryCommand.properties0000644001501200150120000000142111627206700031140 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Display, manage and recall edit-line history command.usage=[show|clear|flush|recall ] command.help=Display, manage and recall edit-line history. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/RecordCommand.groovy0000644001501200150120000000626011707612046030057 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.ComplexCommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'record' command. * * @version $Id$ * @author Jason Dillon */ class RecordCommand extends ComplexCommandSupport { RecordCommand(final Shell shell) { super(shell, 'record', '\\r') this.functions = [ 'start', 'stop', 'status' ] this.defaultFunction = 'status' addShutdownHook { if (recording) { do_stop() } } } private File file private PrintWriter writer boolean isRecording() { return file != null } def recordInput(final String line) { assert line != null if (recording) { writer.println(line) writer.flush() } } def recordResult(final Object result) { // result maybe null if (recording) { // Using String.valueOf() to prevent crazy exceptions writer.println("// RESULT: ${String.valueOf(result)}") writer.flush() } } def recordError(final Throwable cause) { assert cause != null if (recording) { writer.println("// ERROR: $cause") cause.stackTrace.each { writer.println("// $it") } writer.flush() } } def do_start = { args -> if (recording) { fail("Already recording to: $file") } if (args.size() != 1) { file = File.createTempFile('groovysh-', '.txt') } else { file = new File(args[0] as String) } if(file.parentFile) file.parentFile.mkdirs() writer = file.newPrintWriter() writer.println("// OPENED: " + new Date()) writer.flush() io.out.println("Recording session to: $file") return file } def do_stop = { if (!recording) { fail("Not recording") } writer.println("// CLOSED: " + new Date()) writer.flush() writer.close() writer = null io.out.println("Recording stopped; session saved as: $file (${file.length()} bytes)") def tmp = file file = null return tmp } def do_status = { if (!recording) { io.out.println("Not recording") return null } io.out.println("Recording to file: $file (${file.length()} bytes)") return file } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/HelpCommand.groovy0000644001501200150120000001032411627206700027522 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Command import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.CommandRegistry import org.codehaus.groovy.tools.shell.util.SimpleCompletor /** * The 'help' command. * * @version $Id$ * @author Jason Dillon */ class HelpCommand extends CommandSupport { HelpCommand(final Shell shell) { super(shell, 'help', '\\h') alias('?', '\\?') } protected List createCompletors() { return [ new HelpCommandCompletor(registry), null ] } Object execute(final List args) { assert args != null if (args.size() > 1) { fail(messages.format('error.unexpected_args', args.join(' '))) } if (args.size() == 1) { help(args[0]) } else { list() } } private void help(final String name) { assert name Command command = registry[name] if (!command) { fail("No such command: $name") // TODO: i18n } io.out.println() io.out.println("usage: @|bold ${command.name}|@ $command.usage") // TODO: i18n io.out.println() io.out.println(command.help) io.out.println() } private void list() { // Figure out the max command name and shortcut length dynamically int maxName = 0 int maxShortcut for (command in registry) { if (command.hidden) { continue } if (command.name.size() > maxName) { maxName = command.name.size() } if (command.shortcut.size() > maxShortcut) { maxShortcut = command.shortcut.size() } } io.out.println() io.out.println('For information about @|green Groovy|@, visit:') // TODO: i18n io.out.println(' @|cyan http://groovy.codehaus.org|@ ') // FIXME: parsing freaks out if end tok is at the last char... io.out.println() // List the commands we know about io.out.println('Available commands:') // TODO: i18n for (command in registry) { if (command.hidden) { continue } def n = command.name.padRight(maxName, ' ') def s = command.shortcut.padRight(maxShortcut, ' ') // // TODO: Wrap description if needed // def d = command.description io.out.println(" @|bold ${n}|@ (@|bold ${s}|@) $d") } io.out.println() io.out.println('For help on a specific command type:') // TODO: i18n io.out.println(' help @|bold command|@ ') io.out.println() } } /** * Completor for the 'help' command. * * @version $Id$ * @author Jason Dillon */ class HelpCommandCompletor extends SimpleCompletor { private final CommandRegistry registry HelpCommandCompletor(final CommandRegistry registry) { assert registry this.registry = registry } SortedSet getCandidates() { def set = new TreeSet() for (command in registry) { if (command.hidden) { continue } set << command.name set << command.shortcut } return set } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/SetCommand.properties0000644001501200150120000000133611627206700030237 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Set (or list) preferences command.usage=[ []] command.help=Set or list preferences. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/AliasCommand.groovy0000644001501200150120000000565011627206700027671 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell /** * The 'alias' command. * * @version $Id$ * @author Jason Dillon */ class AliasCommand extends CommandSupport { AliasCommand(final Shell shell) { super(shell, 'alias', '\\a') } Object execute(final List args) { assert args != null if (args.size() < 2) { fail("Command 'alias' requires at least 2 arguments") // TODO: i18n } String name = args[0] List target = args[1..-1] def command = registry[name] if (command) { if (command instanceof AliasTargetProxyCommand) { log.debug("Rebinding alias: $name") registry.remove(command) } else { fail("Can not rebind non-user aliased command: ${command.name}") // TODO: i18n } } log.debug("Creating alias '$name' to: $target") // Register the command command = shell << new AliasTargetProxyCommand(shell, name, target) // // TODO: Should this be here... or should this be in the Shell's impl? // // Try to install the completor if (shell.runner) { shell.runner.completor << command } } } class AliasTargetProxyCommand extends CommandSupport { private static int counter = 0 final List args AliasTargetProxyCommand(final Shell shell, final String name, final List args) { super(shell, name, '\\a' + counter++) assert args this.args = args } String getDescription() { return "User defined alias to: @|bold ${args.join(' ')}|@" } String getUsage() { return '' } String getHelp() { return description } Object execute(List args) { args = this.args + args log.debug("Executing with args: $args") // // FIXME: Should go back through shell.execute() to allow aliases to groovy snips too // return shell.executeCommand(args.join(' ')) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/LoadCommand.properties0000644001501200150120000000137311627206700030364 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Load a file or URL into the buffer command.usage=()+ command.help=Load one or more files (or urls) into the buffer. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ImportCommand.groovy0000644001501200150120000000571311627206700030112 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import jline.ArgumentCompletor import jline.NullCompletor import org.codehaus.groovy.control.CompilationFailedException import org.codehaus.groovy.tools.shell.CommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.SimpleCompletor import org.codehaus.groovy.tools.shell.util.ClassNameCompletor /** * The 'import' command. * * @version $Id$ * @author Jason Dillon */ class ImportCommand extends CommandSupport { ImportCommand(final Shell shell) { super(shell, 'import', '\\i') } protected List createCompletors() { return [ new ImportCommandCompletor(shell.interp.classLoader), null ] } Object execute(final List args) { assert args != null if (args.isEmpty()) { fail("Command 'import' requires one or more arguments") // TODO: i18n } def buff = [ 'import ' + args.join(' ') ] buff << 'def dummp = false' def type try { type = classLoader.parseClass(buff.join(NEWLINE)) // No need to keep duplicates, but order may be important so remove the previous def, since // the last defined import will win anyways if (imports.remove(buff[0])) { log.debug("Removed duplicate import from list") } log.debug("Adding import: ${buff[0]}") imports << buff[0] } catch (CompilationFailedException e) { def msg = "Invalid import definition: '${buff[0]}'; reason: $e.message" // TODO: i18n log.debug(msg, e) fail(msg) } finally { // Remove the class generated while testing the import syntax classLoader.classCache.remove(type?.name) } } } /** * Completor for the 'import' command. * * @version $Id$ * @author Jason Dillon */ class ImportCommandCompletor extends ArgumentCompletor { ImportCommandCompletor(final GroovyClassLoader classLoader) { super([ new ClassNameCompletor(classLoader), new SimpleCompletor('as'), new NullCompletor() ]) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ImportCommand.properties0000644001501200150120000000144111627206700030753 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Import a class into the namespace command.usage=[static] [as ] command.help=Add a custom import which will be included for all shell evaluations. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/AliasCommand.properties0000644001501200150120000000127211627206700030534 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Create an alias command.usage= command.help=Create an alias. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/ShowCommand.properties0000644001501200150120000000143211627206700030421 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # command.description=Show variables, classes or imports command.usage=[] command.help=Show variables, classes, imports or preferences. groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands/PurgeCommand.groovy0000644001501200150120000000451211627206700027716 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.commands import org.codehaus.groovy.tools.shell.ComplexCommandSupport import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.util.Preferences /** * The 'purge' command. * * @version $Id$ * @author Jason Dillon */ class PurgeCommand extends ComplexCommandSupport { PurgeCommand(final Shell shell) { super(shell, 'purge', '\\p') this.functions = [ 'variables', 'classes', 'imports', 'preferences', 'all' ] } def do_variables = { if (variables.isEmpty()) { io.out.println('No variables defined') // TODO: i18n } else { variables.clear() if (io.verbose) { io.out.println("Custom variables purged") // TODO: i18n } } } def do_classes = { if (classLoader.loadedClasses.size() == 0) { io.out.println("No classes have been loaded") // TODO: i18n } else { classLoader.clearCache() if (io.verbose) { io.out.println('Loaded classes purged') // TODO: i18n } } } def do_imports = { if (imports.isEmpty()) { io.out.println("No custom imports have been defined") // TODO: i18n } else { imports.clear() if (io.verbose) { io.out.println("Custom imports purged") // TODO: i18n } } } def do_preferences = { Preferences.clear() if (io.verbose) { io.out.println("Preferences purged") // TODO: i18n } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Main.groovy0000644001501200150120000001435311645141222024421 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.HelpFormatter import org.codehaus.groovy.tools.shell.util.Logger import org.codehaus.groovy.tools.shell.util.MessageSource import org.codehaus.groovy.tools.shell.util.NoExitSecurityManager import java.util.concurrent.Callable import org.fusesource.jansi.Ansi import org.fusesource.jansi.AnsiConsole import jline.Terminal /** * Main CLI entry-point for groovysh. * * @version $Id$ * @author Jason Dillon */ class Main { static { // Install the system adapters AnsiConsole.systemInstall() // Register jline ansi detector Ansi.setDetector(new AnsiDetector()) } private static final MessageSource messages = new MessageSource(Main.class) static void main(final String[] args) { IO io = new IO() Logger.io = io def cli = new CliBuilder(usage : 'groovysh [options] [...]', formatter: new HelpFormatter(), writer: io.out) cli.classpath(messages['cli.option.classpath.description']) cli.cp(longOpt: 'classpath', messages['cli.option.cp.description']) cli.h(longOpt: 'help', messages['cli.option.help.description']) cli.V(longOpt: 'version', messages['cli.option.version.description']) cli.v(longOpt: 'verbose', messages['cli.option.verbose.description']) cli.q(longOpt: 'quiet', messages['cli.option.quiet.description']) cli.d(longOpt: 'debug', messages['cli.option.debug.description']) cli.C(longOpt: 'color', args: 1, argName: 'FLAG', optionalArg: true, messages['cli.option.color.description']) cli.D(longOpt: 'define', args: 1, argName: 'NAME=VALUE', messages['cli.option.define.description']) cli.T(longOpt: 'terminal', args: 1, argName: 'TYPE', messages['cli.option.terminal.description']) def options = cli.parse(args) if (options.h) { cli.usage() System.exit(0) } if (options.V) { io.out.println(messages.format('cli.info.version', GroovySystem.version)) System.exit(0) } if (options.hasOption('T')) { def type = options.getOptionValue('T') setTerminalType(type) } if (options.hasOption('D')) { def values = options.getOptionValues('D') values.each { setSystemProperty(it as String) } } if (options.v) { io.verbosity = IO.Verbosity.VERBOSE } if (options.d) { io.verbosity = IO.Verbosity.DEBUG } if (options.q) { io.verbosity = IO.Verbosity.QUIET } if (options.hasOption('C')) { def value = options.getOptionValue('C') setColor(value) } def code // Add a hook to display some status when shutting down... addShutdownHook { // // FIXME: We need to configure JLine to catch CTRL-C for us... Use gshell-io's InputPipe // if (code == null) { // Give the user a warning when the JVM shutdown abnormally, normal shutdown // will set an exit code through the proper channels io.err.println() io.err.println('@|red WARNING:|@ Abnormal JVM shutdown detected') } io.flush() } // Boot up the shell... :-) Groovysh shell = new Groovysh(io) SecurityManager psm = System.getSecurityManager() System.setSecurityManager(new NoExitSecurityManager()) try { code = shell.run(options.arguments() as String[]) } finally { System.setSecurityManager(psm) } // Force the JVM to exit at this point, since shell could have created threads or // popped up Swing components that will cause the JVM to linger after we have been // asked to shutdown System.exit(code) } static void setTerminalType(String type) { assert type != null type = type.toLowerCase(); switch (type) { case 'auto': type = null; break; case 'unix': type = 'jline.UnixTerminal' break case 'win': case 'windows': type = 'jline.WindowsTerminal' break case 'false': case 'off': case 'none': type = 'jline.UnsupportedTerminal' // Disable ANSI, for some reason UnsupportedTerminal reports ANSI as enabled, when it shouldn't Ansi.enabled = false break; } if (type != null) { System.setProperty('jline.terminal', type) } } static void setColor(value) { if (value == null) { value = true // --color is the same as --color=true } else { value = Boolean.valueOf(value).booleanValue(); // For JDK 1.4 compat } Ansi.enabled = value } static void setSystemProperty(final String nameValue) { String name String value if (nameValue.indexOf('=') > 0) { def tmp = nameValue.split('=', 2) name = tmp[0] value = tmp[1] } else { name = nameValue value = Boolean.TRUE.toString() } System.setProperty(name, value) } } class AnsiDetector implements Callable { public Boolean call() throws Exception { return Terminal.getTerminal().isANSISupported() } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Groovysh.groovy0000644001501200150120000003341511713765676025402 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import jline.Terminal import jline.History import org.codehaus.groovy.tools.shell.util.MessageSource import org.codehaus.groovy.tools.shell.util.XmlCommandRegistrar import org.codehaus.groovy.runtime.StackTraceUtils import org.codehaus.groovy.tools.shell.util.Preferences import org.fusesource.jansi.AnsiRenderer import org.fusesource.jansi.Ansi import org.fusesource.jansi.AnsiConsole /** * An interactive shell for evaluating Groovy code from the command-line (aka. groovysh). * * @version $Id$ * @author Jason Dillon */ class Groovysh extends Shell { static { // Install the system adapters AnsiConsole.systemInstall() // Register jline ansi detector Ansi.setDetector(new AnsiDetector()) } private static final MessageSource messages = new MessageSource(Groovysh.class) final BufferManager buffers = new BufferManager() final Parser parser final Interpreter interp final List imports = [] InteractiveShellRunner runner History history boolean historyFull // used as a workaround for GROOVY-2177 String evictedLine // remembers the command which will get evicted if history is full Groovysh(final ClassLoader classLoader, final Binding binding, final IO io, final Closure registrar) { super(io) assert classLoader assert binding assert registrar parser = new Parser() interp = new Interpreter(classLoader, binding) registrar.call(this) } private static Closure createDefaultRegistrar() { return { shell -> def r = new XmlCommandRegistrar(shell, classLoader) r.register(getClass().getResource('commands.xml')) } } Groovysh(final ClassLoader classLoader, final Binding binding, final IO io) { this(classLoader, binding, io, createDefaultRegistrar()) } Groovysh(final Binding binding, final IO io) { this(Thread.currentThread().contextClassLoader, binding, io) } Groovysh(final IO io) { this(new Binding(), io) } Groovysh() { this(new IO()) } // // Execution // /** * Execute a single line, where the line may be a command or Groovy code (complete or incomplete). */ Object execute(final String line) { assert line != null // Ignore empty lines if (line.trim().size() == 0) { return null } maybeRecordInput(line) def result // First try normal command execution if (isExecutable(line)) { result = executeCommand(line) // For commands, only set the last result when its non-null/true if (result) { lastResult = result } return result } // Otherwise treat the line as Groovy def current = [] current += buffers.current() // Append the line to the current buffer current << line // Attempt to parse the current buffer def status = parser.parse(imports + current) switch (status.code) { case ParseCode.COMPLETE: log.debug("Evaluating buffer...") if (io.verbose) { displayBuffer(current) } // Evaluate the current buffer w/imports and dummy statement def buff = imports + [ 'true' ] + current lastResult = result = interp.evaluate(buff) buffers.clearSelected() break case ParseCode.INCOMPLETE: // Save the current buffer so user can build up complex multi-line code blocks buffers.updateSelected(current) break case ParseCode.ERROR: throw status.cause default: // Should never happen throw new Error("Invalid parse status: $status.code") } return result } protected Object executeCommand(final String line) { return super.execute(line) } /** * Display the given buffer. */ private void displayBuffer(final List buffer) { assert buffer buffer.eachWithIndex { line, index -> def lineNum = formatLineNumber(index) io.out.println(" ${lineNum}@|bold >|@ $line") } } // // Prompt // private AnsiRenderer prompt = new AnsiRenderer() /* Builds the command prompt name in 1 of 3 ways: 1. Checks the groovysh.prompt property passed into groovysh script. -Dgroovysh.prompt="hello" 2. Checks an environment variable called GROOVYSH_PROMPT. export GROOVYSH_PROMPT 3. If no value is defined returns the default groovy shell prompt. The code will always assume you want the line number in the prompt. To implement differently overhead the render prompt variable. */ private String buildPrompt(){ def lineNum = formatLineNumber(buffers.current().size()) def formattedPrompt = "@|bold groovy:|@${lineNum}@|bold >|@ " def GROOVYSHELL_PROPERTY = System.getProperty("groovysh.prompt") def GROOVYSHELL_ENV = System.getenv("GROOVYSH_PROMPT") if (GROOVYSHELL_PROPERTY) return "@|bold ${GROOVYSHELL_PROPERTY}:|@${lineNum}@|bold >|@ " if (GROOVYSHELL_ENV) return "@|bold ${GROOVYSHELL_ENV}:|@${lineNum}@|bold >|@ " return formattedPrompt } public String renderPrompt() { return prompt.render( buildPrompt() ) } /** * Format the given number suitable for rendering as a line number column. */ private String formatLineNumber(final int num) { assert num >= 0 // Make a %03d-like string for the line number return num.toString().padLeft(3, '0') } // // User Profile Scripts // File getUserStateDirectory() { def userHome = new File(System.getProperty('user.home')) def dir = new File(userHome, '.groovy') return dir.canonicalFile } private void loadUserScript(final String filename) { assert filename def file = new File(userStateDirectory, filename) if (file.exists()) { def command = registry['load'] if (command) { log.debug("Loading user-script: $file") // Disable the result hook for profile scripts def previousHook = resultHook resultHook = { result -> /* nothing */} try { command.load(file.toURI().toURL()) } finally { // Restore the result hook resultHook = previousHook } } else { log.error("Unable to load user-script, missing 'load' command") } } } // // Recording // private void maybeRecordInput(final String line) { def record = registry['record'] if (record != null) { record.recordInput(line) } } private void maybeRecordResult(final Object result) { def record = registry['record'] if (record != null) { record.recordResult(result) } } private void maybeRecordError(Throwable cause) { def record = registry['record'] if (record != null) { boolean sanitize = Preferences.sanitizeStackTrace if (sanitize) { cause = StackTraceUtils.deepSanitize(cause); } record.recordError(cause) } } // // Hooks // final Closure defaultResultHook = { result -> boolean showLastResult = !io.quiet && (io.verbose || Preferences.showLastResult) if (showLastResult) { // Need to use String.valueOf() here to avoid icky exceptions causes by GString coercion io.out.println("@|bold ===>|@ ${String.valueOf(result)}") } } Closure resultHook = defaultResultHook private void setLastResult(final Object result) { if (resultHook == null) { throw new IllegalStateException("Result hook is not set") } resultHook.call((Object)result) interp.context['_'] = result maybeRecordResult(result) } private Object getLastResult() { return interp.context['_'] } final Closure defaultErrorHook = { Throwable cause -> assert cause != null io.err.println("@|bold,red ERROR|@ ${cause.class.name}:") io.err.println("@|bold,red ${cause.message}|@") maybeRecordError(cause) if (log.debug) { // If we have debug enabled then skip the fancy bits below log.debug(cause) } else { boolean sanitize = Preferences.sanitizeStackTrace // Sanitize the stack trace unless we are in verbose mode, or the user has request otherwise if (!io.verbose && sanitize) { cause = StackTraceUtils.deepSanitize(cause); } def trace = cause.stackTrace def buff = new StringBuffer() for (e in trace) { buff << " @|bold at|@ ${e.className}.${e.methodName} (@|bold " buff << (e.nativeMethod ? 'Native Method' : (e.fileName != null && e.lineNumber != -1 ? "${e.fileName}:${e.lineNumber}" : (e.fileName != null ? e.fileName : 'Unknown Source'))) buff << '|@)' io.err.println(buff) buff.setLength(0) // Reset the buffer // Stop the trace once we find the root of the evaluated script if (e.className == Interpreter.SCRIPT_FILENAME && e.methodName == 'run') { io.err.println(' @|bold ...|@') break } } } } Closure errorHook = defaultErrorHook private void displayError(final Throwable cause) { if (errorHook == null) { throw new IllegalStateException("Error hook is not set") } errorHook.call(cause) } // // Interactive Shell // int run(final String[] args) { String commandLine = null if (args != null && args.length > 0) { commandLine = args.join(' ') } return run(commandLine as String) } int run(final String commandLine) { def term = Terminal.terminal if (log.debug) { log.debug("Terminal ($term)") log.debug(" Supported: $term.supported") log.debug(" ECHO: $term.echo (enabled: $term.echoEnabled)") log.debug(" H x W: $term.terminalHeight x $term.terminalWidth") log.debug(" ANSI: ${term.isANSISupported()}") if (term instanceof jline.WindowsTerminal) { log.debug(" Direct: ${term.directConsole}") } } def code try { loadUserScript('groovysh.profile') // if args were passed in, just execute as a command // (but cygwin gives an empty string, so ignore that) if (commandLine != null && commandLine.trim().size() > 0) { // Run the given commands execute(commandLine) } else { loadUserScript('groovysh.rc') // Setup the interactive runner runner = new InteractiveShellRunner(this, this.&renderPrompt as Closure) // Setup the history runner.history = history = new History() runner.historyFile = new File(userStateDirectory, 'groovysh.history') // Setup the error handler runner.errorHandler = this.&displayError // // TODO: See if we want to add any more language specific completions, like for println for example? // // Display the welcome banner if (!io.quiet) { def width = term.terminalWidth // If we can't tell, or have something bogus then use a reasonable default if (width < 1) { width = 80 } io.out.println(messages.format('startup_banner.0', GroovySystem.version, System.properties['java.version'])) io.out.println(messages['startup_banner.1']) io.out.println('-' * (width - 1)) } // And let 'er rip... :-) runner.run() } code = 0 } catch (ExitNotification n) { log.debug("Exiting w/code: ${n.code}") code = n.code } catch (Throwable t) { io.err.println(messages.format('info.fatal', t)) t.printStackTrace(io.err) code = 1 } assert code != null // This should never happen return code } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandAlias.groovy0000644001501200150120000000323411627206700026064 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell /** * Provides simple command aliasing. * * @version $Id$ * @author Jason Dillon */ class CommandAlias extends CommandSupport { final String targetName CommandAlias(final Shell shell, final String name, final String shortcut, final String target) { super(shell, name, shortcut) assert target this.targetName = target } Command getTarget() { def command = registry[targetName] assert command != null return command } protected List createCompletors() { return target.createCompletors() } String getDescription() { return messages.format('info.alias_to', targetName) } String getUsage() { return target.usage } String getHelp() { return target.help } boolean getHidden() { return target.hidden } Object execute(final List args) { target.execute(args) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/0000755001501200150120000000000011707612046023243 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/MessageSource.java0000644001501200150120000000755511627206700026664 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util; import java.util.ResourceBundle; import java.util.MissingResourceException; import java.text.MessageFormat; import groovy.lang.GroovyObjectSupport; /** * Message source backed up by one or more {@link java.util.ResourceBundle} * instances for simple i18n support. * * @version $Id$ * @author Jason Dillon */ public class MessageSource extends GroovyObjectSupport { private final String[] bundleNames; private ResourceBundle[] cachedBundles; public MessageSource(final String[] names) { assert names != null; assert names.length != 0; this.bundleNames = names; } public MessageSource(final String name) { this(new String[] { name }); } private static String[] classNames(final Class[] types) { assert types != null; assert types.length != 0; String[] names = new String[types.length]; for (int i=0; iJason Dillon */ class HelpFormatter extends org.apache.commons.cli.HelpFormatter { HelpFormatter() { defaultLeftPad = 2 defaultDescPad = 4 } // Detect the terminal width late public int getDefaultWidth() { return Terminal.terminal.terminalWidth - 1 } protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad) { assert sb != null assert options List prefixes = [] String lpad = ' ' * leftPad List opts = options.shortOpts.values().sort { a, b -> return (a.opt == ' ' ? a.longOpt : a.opt) <=> (b.opt == ' ' ? b.longOpt : b.opt) } // Render the prefixes (-X,--xxxx muck) opts.each { option -> def buff = new StringBuffer(8) if (option.opt == ' ') { buff << "${lpad} ${defaultLongOptPrefix}${option.longOpt}" } else { buff << "${lpad}${defaultOptPrefix}${option.opt}" if (option.hasLongOpt()) { buff << ", ${defaultLongOptPrefix}${option.longOpt}" } } if (option.hasArg()) { if (option.hasArgName()) { if (option.hasOptionalArg()) { buff << "[=${option.argName}]" } else { buff << "=${option.argName}" } } else { buff << ' ' } } prefixes << buff } // Figure out how long the biggest prefix is int maxPrefix = prefixes.max { a, b -> a.size() <=> b.size() }.size() String dpad = ' ' * descPad // And then render each option's prefix with its description opts.eachWithIndex { option, i -> def buff = new StringBuffer(prefixes[i].toString()) if (buff.size() < maxPrefix) { buff << ' ' * (maxPrefix - buff.size()) } buff << dpad int nextLineTabStop = maxPrefix + descPad String text = buff << option.description renderWrappedText(sb, width, nextLineTabStop, text) if (i < opts.size() - 1) { sb << defaultNewLine } } return sb } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.java0000644001501200150120000000324011627206700030333 0ustar miguelmiguel/* * Copyright (C) 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util; import java.security.Permission; /** * Custom security manager to {@link System#exit} (and related) from being used. * * @version $Rev$ $Date$ */ public class NoExitSecurityManager extends SecurityManager { private final SecurityManager parent; public NoExitSecurityManager(final SecurityManager parent) { assert parent != null; this.parent = parent; } public NoExitSecurityManager() { this(System.getSecurityManager()); } public void checkPermission(final Permission perm) { if (parent != null) { parent.checkPermission(perm); } } /** * Always throws {@link SecurityException}. */ public void checkExit(final int code) { throw new SecurityException("Use of System.exit() is forbidden!"); } /* public void checkPermission(final Permission perm) { assert perm != null; if (perm.getName().equals("exitVM")) { System.out.println("exitVM"); } } */ } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/package.html0000644001501200150120000000150411627206700025521 0ustar miguelmiguel

      Utility classes related to the Groovy Shell (aka. groovysh).

      groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/ClassNameCompletor.groovy0000644001501200150120000000251711627206700030247 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util /** * Provides completion for class names. * * @version $Id$ * @author Jason Dillon */ class ClassNameCompletor extends SimpleCompletor { private final GroovyClassLoader classLoader ClassNameCompletor(final GroovyClassLoader classLoader) { assert classLoader this.classLoader = classLoader delimiter = '.' } SortedSet getCandidates() { def set = new TreeSet() // // TODO: Figure out what class names to include, for now just hack in some to test with // set << 'java.lang.System' set << 'groovy.lang.GroovyObject' return set } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/Logger.java0000644001501200150120000000663411707612046025336 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util; import org.codehaus.groovy.tools.shell.IO; import java.io.IOException; import static org.fusesource.jansi.Ansi.ansi; import static org.fusesource.jansi.Ansi.Color; import static org.fusesource.jansi.Ansi.Color.*; import static org.fusesource.jansi.Ansi.Attribute.*; /** * Provides a very, very basic logging API. * * @version $Id$ * @author Jason Dillon */ public final class Logger { public static IO io; public final String name; private Logger(final String name) { assert name != null; this.name = name; } private void log(final String level, Object msg, Throwable cause) { assert level != null; assert msg != null; if (io == null) { io = new IO(); } // Allow the msg to be a Throwable, and handle it properly if no cause is given if (cause == null) { if (msg instanceof Throwable) { cause = (Throwable) msg; msg = cause.getMessage(); } } Color color = GREEN; if (WARN.equals(level) || ERROR.equals(level)) { color = RED; } io.out.println(ansi().a(INTENSITY_BOLD).a(color).a(level).reset().a(" [").a(name).a("] ").a(msg)); if (cause != null) { cause.printStackTrace(io.out); } try { io.flush(); } catch (IOException io) { throw new RuntimeException(io); } } // // Level helpers // private static final String DEBUG = "DEBUG"; public boolean isDebugEnabled() { return Preferences.verbosity == IO.Verbosity.DEBUG; } public boolean isDebug() { return isDebugEnabled(); } public void debug(final Object msg) { if (isDebugEnabled()) { log(DEBUG, msg, null); } } public void debug(final Object msg, final Throwable cause) { if (isDebugEnabled()) { log(DEBUG, msg, cause); } } private static final String WARN = "WARN"; public void warn(final Object msg) { log(WARN, msg, null); } public void warn(final Object msg, final Throwable cause) { log(WARN, msg, cause); } private static final String ERROR = "ERROR"; public void error(final Object msg) { log(ERROR, msg, null); } public void error(final Object msg, final Throwable cause) { log(ERROR, msg, cause); } // // Factory access // public static Logger create(final Class type) { return new Logger(type.getName()); } public static Logger create(final Class type, final String suffix) { return new Logger(type.getName() + "." + suffix); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/XmlCommandRegistrar.groovy0000644001501200150120000000377311627206700030443 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util import org.codehaus.groovy.tools.shell.Shell import org.codehaus.groovy.tools.shell.Command /** * Registers {@link Command} instances from and XML file. * * @version $Id$ * @author Jason Dillon */ class XmlCommandRegistrar { private final Logger log = Logger.create(this.class) private final Shell shell private final ClassLoader classLoader XmlCommandRegistrar(final Shell shell, final ClassLoader classLoader) { assert shell assert classLoader this.shell = shell this.classLoader = classLoader } void register(final URL url) { assert url if (log.debugEnabled) { log.debug("Registering commands from: $url") } url.withReader { reader -> def doc = new XmlParser().parse(reader) doc.command.each { element -> String classname = element.text() Class type = classLoader.loadClass(classname) Command command = type.newInstance(shell) if (log.debugEnabled) { log.debug("Created command '${command.name}': $command") } shell << command } } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/Preferences.java0000644001501200150120000000636111627206700026352 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util; import java.util.prefs.BackingStoreException; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.PreferenceChangeEvent; import org.codehaus.groovy.tools.shell.IO; /** * Container for shell preferences. * * @version $Id$ * @author Jason Dillon */ public class Preferences { private static final java.util.prefs.Preferences STORE = java.util.prefs.Preferences.userRoot().node("/org/codehaus/groovy/tools/shell"); public static IO.Verbosity verbosity; static { String tmp = STORE.get("verbosity", IO.Verbosity.INFO.name); try { verbosity = IO.Verbosity.forName(tmp); } catch (IllegalArgumentException e) { verbosity = IO.Verbosity.INFO; STORE.remove("verbosity"); } addChangeListener(new PreferenceChangeListener() { public void preferenceChange(final PreferenceChangeEvent event) { if (event.getKey().equals("verbosity")) { String name = event.getNewValue(); if (name == null) { name = IO.Verbosity.INFO.name; } try { verbosity = IO.Verbosity.forName(name); } catch (Exception e) { event.getNode().put(event.getKey(), verbosity.name); } } } }); } public static boolean getShowLastResult() { return STORE.getBoolean("show-last-result", true); } public static boolean getSanitizeStackTrace() { return STORE.getBoolean("sanitize-stack-trace", true); } public static String getEditor() { return STORE.get("editor", System.getenv("EDITOR")); } public static String getParserFlavor() { return STORE.get("parser-flavor", "rigid"); } // // Store Access // public static String[] keys() throws BackingStoreException { return STORE.keys(); } public static String get(final String name, final String defaultValue) { return STORE.get(name, defaultValue); } public static String get(final String name) { return get(name, null); } public static void put(final String name, final String value) { STORE.put(name, value); } public static void clear() throws BackingStoreException { STORE.clear(); } public static void addChangeListener(final PreferenceChangeListener listener) { STORE.addPreferenceChangeListener(listener); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/util/SimpleCompletor.java0000644001501200150120000000575711707612046027242 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell.util; import java.util.List; import java.util.Iterator; import java.util.SortedSet; import groovy.lang.Closure; /** * Support for simple completors. * * @version $Id$ * @author Jason Dillon */ public class SimpleCompletor extends jline.SimpleCompletor { public SimpleCompletor(final String[] candidates) { super(candidates); } public SimpleCompletor() { this(new String[0]); } public SimpleCompletor(final Closure loader) { this(); assert loader != null; Object obj = loader.call(); List list = null; if (obj instanceof List) { list = (List)obj; } // // TODO: Maybe handle arrays too? // if (list == null) { throw new IllegalStateException("The loader closure did not return a list of candidates; found: " + obj); } Iterator iter = list.iterator(); while (iter.hasNext()) { add(String.valueOf(iter.next())); } } public void add(final String candidate) { addCandidateString(candidate); } public Object leftShift(final String s) { add(s); return null; } // // NOTE: Duplicated (and augmented) from JLine sources to make it call getCandidates() to make the list more dynamic // public int complete(final String buffer, final int cursor, final List clist) { String start = (buffer == null) ? "" : buffer; SortedSet matches = getCandidates().tailSet(start); for (Iterator i = matches.iterator(); i.hasNext();) { String can = (String) i.next(); if (!(can.startsWith(start))) { break; } String delim = getDelimiter(); if (delim != null) { int index = can.indexOf(delim, cursor); if (index != -1) { can = can.substring(0, index + 1); } } clist.add(can); } if (clist.size() == 1) { clist.set(0, ((String) clist.get(0)) + " "); } // the index of the completion is always from the beginning of the buffer. return (clist.size() == 0) ? (-1) : 0; } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/InteractiveShellRunner.groovy0000644001501200150120000001043611707612046030200 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import jline.ConsoleReader import jline.MultiCompletor import jline.History import jline.Completor import jline.MultiCompletor import org.codehaus.groovy.tools.shell.util.Logger /** * Support for running a {@link Shell} interactively using the JLine library. * * @version $Id$ * @author Jason Dillon */ class InteractiveShellRunner extends ShellRunner implements Runnable { final ConsoleReader reader final Closure prompt final CommandsMultiCompletor completor InteractiveShellRunner(final Shell shell, final Closure prompt) { super(shell) this.prompt = prompt this.reader = new ConsoleReader(shell.io.inputStream, new PrintWriter(shell.io.outputStream, true)) reader.addCompletor(new ReflectionCompletor(shell)) this.completor = new CommandsMultiCompletor() reader.addCompletor(completor) } void run() { for (command in shell.registry) { completor << command } // Force things to become clean completor.refresh() // And then actually run adjustHistory() super.run() } void setHistory(final History history) { reader.history = history } void setHistoryFile(final File file) { def dir = file.parentFile if (!dir.exists()) { dir.mkdirs() log.debug("Created base directory for history file: $dir") } log.debug("Using history file: $file") reader.history.historyFile = file } protected String readLine() { try { return reader.readLine(prompt.call()) } catch (StringIndexOutOfBoundsException e) { log.debug("HACK: Try and work around GROOVY-2152 for now", e) return ""; } } @Override protected boolean work() { boolean result= super.work() adjustHistory() result } private void adjustHistory() { if (shell instanceof Groovysh) { shell.historyFull = shell.history.size() >= shell.history.maxSize if (shell.historyFull) shell.evictedLine = shell.history.historyList[0] } } } /** * Completor for interactive shells. * * @version $Id$ * @author Jason Dillon */ class CommandsMultiCompletor extends MultiCompletor { protected final Logger log = Logger.create(this.class) List/**/ list = [] private boolean dirty = false def leftShift(final Command command) { assert command // // FIXME: Need to handle completor removal when things like aliases are rebound // def c = command.completor if (c) { list << c log.debug("Added completor[${list.size()}] for command: $command.name") dirty = true } } void refresh() { log.debug("Refreshing the completor list") completors = list as Completor[] dirty = false } int complete(final String buffer, final int pos, final List cand) { assert buffer != null // // FIXME: This is a bit of a hack, I'm too lazy to rewrite a more efficient // completor impl that is more dynamic than the jline.MultiCompletor version // so just re-use it and reset the list as needed // if (dirty) { refresh() } return super.complete(buffer, pos, cand) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandRegistry.groovy0000644001501200150120000000555711627206700026655 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.Logger /** * A registry of shell {@link Command} instances which may be executed. * * @version $Id$ * @author Jason Dillon */ class CommandRegistry { protected final Logger log = Logger.create(CommandRegistry.class) // // TODO: Hook up support so one can for (command in registry) { } // /** A list of all of the registered commands. */ final List commands = [] /** A set of all of the command names and shortcuts to ensure they are unique. */ private final Set names = new TreeSet() Command register(final Command command) { assert command // Make sure that the command name and shortcut are unique assert !names.contains(command.name) : "Duplicate comamnd name: $command.name" names << command.name assert !names.contains(command.shortcut) : "Duplicate command shortcut: $command.shortcut" names << command.shortcut // Hold on to the command in order commands << command // Hookup context for alias commands command.registry = this // Add any standard aliases for the command if any command.aliases?.each { this << it } if (log.debugEnabled) { log.debug("Registered command: $command.name") } return command } def leftShift(final Command command) { return register(command) } Command find(final String name) { assert name for (c in commands) { if (name in [ c.name, c.shortcut ]) { return c } } return null } void remove(final Command command) { assert command commands.remove(command) names.remove(command.name) names.remove(command.shortcut) if (log.debugEnabled) { log.debug("Removed command: $command.name") } } List commands() { return commands } def getProperty(final String name) { return find(name) } Iterator iterator() { return commands().iterator() } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/BufferManager.groovy0000644001501200150120000000453211627206700026242 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.Logger /** * Manages the shells buffers. * * @version $Id$ * @author Jason Dillon */ class BufferManager { protected final Logger log = Logger.create(this.class) final List buffers = [] int selected BufferManager() { reset() } void reset() { buffers.clear() create(true) log.debug('Buffers reset') } List current() { assert !buffers.isEmpty() return buffers[selected] } void select(final int index) { assert index >= 0 && index < buffers.size() selected = index } int create(final boolean select) { buffers << [] def i = buffers.size() - 1 if (select) { this.select(i) } if (log.debugEnabled) { log.debug("Created new buffer with index: $i") } return i } void delete(final int index) { assert index >= 0 && index < buffers.size() buffers.remove(index) if (log.debugEnabled) { log.debug("Deleted buffer with index: $index") } } int size() { return buffers.size() } // // Selected operators // void deleteSelected() { delete(selected) def i = selected - 1 if (i < 0) { select(0) } else { select(i) } } void clearSelected() { current().clear() } void updateSelected(final List buffer) { assert buffer != null buffers[selected] = buffer } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Shell.groovy0000644001501200150120000000610611627206700024604 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.Logger /** * A simple shell for invoking commands from a command-line. * * @version $Id$ * @author Jason Dillon */ class Shell { protected final Logger log = Logger.create(this.class) final CommandRegistry registry = new CommandRegistry() final IO io Shell(final IO io) { assert io this.io = io } Shell() { this(new IO()) } protected List parseLine(final String line) { assert line != null return line.trim().tokenize() } Command findCommand(final String line) { assert line // // TODO: Introduce something like 'boolean Command.accepts(String)' to ask // commands if they can take the line? // // Would like to get '!66' to invoke the 'history recall' bits, but currently has // to be '! 66' for it to work with an alias like: // // alias ! history recall // // Or maybe allow commands to register specific syntax hacks into the registry? // then ask the registry for the command for a given line? // def args = parseLine(line) assert args.size() > 0 def name = args[0] def command = registry[name] return command } boolean isExecutable(final String line) { return findCommand(line) != null } Object execute(final String line) { assert line def command = findCommand(line) def result = null if (command) { def args = parseLine(line) if (args.size() == 1) { args = [] } else { args = args[1..-1] } log.debug("Executing command($command.name): $command; w/args: $args") result = command.execute(args) log.debug("Result: ${String.valueOf(result)}") } return result } Command register(final Command command) { return registry << command } def leftShift(final String line) { return execute(line) } def leftShift(final Command command) { return register(command) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Main.properties0000644001501200150120000000240611627206700025267 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # # # CLI messages # cli.option.help.description=Display this help message cli.option.version.description=Display the version cli.option.verbose.description=Enable verbose output cli.option.quiet.description=Suppress superfluous output cli.option.debug.description=Enable debug output cli.option.cp.description=Aliases for '-classpath' cli.option.classpath.description=Specify where to find the class files - must be first argument cli.option.color.description=Enable or disable use of ANSI colors cli.option.define.description=Define a system property cli.option.terminal.description=Specify the terminal TYPE to use cli.info.version=@|green Groovy Shell|@ {0}groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandSupport.properties0000644001501200150120000000123111627206700027351 0ustar miguelmiguel# # Copyright 2003-2007 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Id$ # error.unexpected_args=Unexpected arguments: {0} groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/commands.xml0000644001501200150120000000377211627206700024617 0ustar miguelmiguel org.codehaus.groovy.tools.shell.commands.HelpCommand org.codehaus.groovy.tools.shell.commands.ExitCommand org.codehaus.groovy.tools.shell.commands.ImportCommand org.codehaus.groovy.tools.shell.commands.DisplayCommand org.codehaus.groovy.tools.shell.commands.ClearCommand org.codehaus.groovy.tools.shell.commands.ShowCommand org.codehaus.groovy.tools.shell.commands.InspectCommand org.codehaus.groovy.tools.shell.commands.PurgeCommand org.codehaus.groovy.tools.shell.commands.EditCommand org.codehaus.groovy.tools.shell.commands.LoadCommand org.codehaus.groovy.tools.shell.commands.SaveCommand org.codehaus.groovy.tools.shell.commands.RecordCommand org.codehaus.groovy.tools.shell.commands.HistoryCommand org.codehaus.groovy.tools.shell.commands.AliasCommand org.codehaus.groovy.tools.shell.commands.SetCommand org.codehaus.groovy.tools.shell.commands.ShadowCommand org.codehaus.groovy.tools.shell.commands.RegisterCommand groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/ExitNotification.groovy0000644001501200150120000000167711627206700027025 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell /** * Notification to signal the shell to exit. * * @version $Id$ * @author Jason Dillon */ class ExitNotification extends Error { /** The exit code. */ final int code ExitNotification(final int code) { this.code = code } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/CommandSupport.groovy0000644001501200150120000001122011627206700026501 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import jline.Completor import jline.NullCompletor import jline.ArgumentCompletor import jline.History import org.codehaus.groovy.tools.shell.util.MessageSource import org.codehaus.groovy.tools.shell.util.Logger import org.codehaus.groovy.tools.shell.util.SimpleCompletor /** * Support for {@link Command} instances. * * @version $Id$ * @author Jason Dillon */ abstract class CommandSupport implements Command { protected static final String NEWLINE = System.properties['line.separator'] /** Instance logger for the command, initialized late to include the command name. */ protected final Logger log /** i18n message source for the command. */ protected final MessageSource messages = new MessageSource(this.class, CommandSupport.class) /** The name of the command. */ final String name /** The shortcut switch */ final String shortcut /** The owning shell. */ protected final Shell shell /** The I/O container for the command to spit stuff out. */ protected final IO io /** Provides the command instance with the registry, for aliasing support. */ protected CommandRegistry registry /** Standard aliases for the command. */ final List/**/ aliases = [] /** Flag to indicate if the command should be hidden or not. */ boolean hidden = false protected CommandSupport(final Shell shell, final String name, final String shortcut) { assert shell assert name assert shortcut this.log = Logger.create(this.class, name) this.shell = shell this.io = shell.io this.name = name this.shortcut = shortcut // // NOTE: Registry will be added once registered. // } String getDescription() { return messages['command.description'] } String getUsage() { return messages['command.usage'] } String getHelp() { return messages['command.help'] } /** * Override to provide custom completion semantics for the command. */ protected List createCompletors() { return null } /** * Setup the completor for the command. */ Completor getCompletor() { if (hidden) { return null } def list = [ new SimpleCompletor(name, shortcut) ] def completors = createCompletors() if (completors) { completors.each { if (it) { list << it } else { list << new NullCompletor() } } } else { list << new NullCompletor() } return new ArgumentCompletor(list) } // // Helpers // protected void alias(final String name, final String shortcut) { aliases << new CommandAlias(shell, name, shortcut, this.name) } protected void fail(final String msg) { throw new CommandException(this, msg) } protected void fail(final String msg, final Throwable cause) { throw new CommandException(this, msg, cause) } protected void assertNoArguments(final List args) { assert args != null if (args.size() > 0) { fail(messages.format('error.unexpected_args', args.join(' '))) } } // // Shell access helpers // protected BufferManager getBuffers() { return shell.buffers } protected List getBuffer() { return shell.buffers.current() } protected List getImports() { return shell.imports } protected Binding getBinding() { return shell.interp.context } protected Map getVariables() { return binding.variables } protected History getHistory() { return shell.history } protected GroovyClassLoader getClassLoader() { return shell.interp.classLoader } }groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/Parser.groovy0000644001501200150120000001510111627206700024764 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.control.CompilationFailedException import org.codehaus.groovy.tools.shell.util.Logger import org.codehaus.groovy.tools.shell.util.Preferences import org.codehaus.groovy.antlr.SourceBuffer import org.codehaus.groovy.antlr.UnicodeEscapingReader import org.codehaus.groovy.antlr.parser.GroovyLexer import org.codehaus.groovy.antlr.parser.GroovyRecognizer import antlr.collections.AST import antlr.RecognitionException import antlr.TokenStreamException /** * Provides a facade over the parser to recognize valid Groovy syntax. * * @version $Id$ * @author Jason Dillon */ class Parser { static final String NEWLINE = System.getProperty('line.separator') private static final Logger log = Logger.create(Parser.class) private final def delegate Parser() { def f = Preferences.parserFlavor log.debug("Using parser flavor: $f") switch (f) { case 'relaxed': delegate = new RelaxedParser() break case 'rigid': delegate = new RigidParser() break default: log.error("Invalid parser flavor: $f; using default") delegate = new RigidParser() break } } ParseStatus parse(final List buffer) { return delegate.parse(buffer) } } /** * A relaxed parser, which tends to allow more, but won't really catch valid syntax errors. */ final class RelaxedParser { private final Logger log = Logger.create(this.class) private SourceBuffer sourceBuffer private String[] tokenNames ParseStatus parse(final List buffer) { assert buffer sourceBuffer = new SourceBuffer() def source = buffer.join(Parser.NEWLINE) log.debug("Parsing: $source") try { doParse(new UnicodeEscapingReader(new StringReader(source), sourceBuffer)) log.debug('Parse complete') return new ParseStatus(ParseCode.COMPLETE) } catch (e) { switch (e.class) { case TokenStreamException: case RecognitionException: log.debug("Parse incomplete: $e (${e.class.name})") return new ParseStatus(ParseCode.INCOMPLETE) default: log.debug("Parse error: $e (${e.class.name})") return new ParseStatus(e) } } } protected AST doParse(final UnicodeEscapingReader reader) throws Exception { def lexer = new GroovyLexer(reader) reader.setLexer(lexer) def parser = GroovyRecognizer.make(lexer) parser.setSourceBuffer(sourceBuffer) tokenNames = parser.getTokenNames() parser.compilationUnit() return parser.getAST() } } /** * A more rigid parser which catches more syntax errors, but also tends to barf on stuff that is really valid from time to time. */ final class RigidParser { static final String SCRIPT_FILENAME = 'groovysh_parse' private final Logger log = Logger.create(this.class) ParseStatus parse(final List buffer) { assert buffer String source = buffer.join(Parser.NEWLINE) log.debug("Parsing: $source") SourceUnit parser Throwable error try { parser = SourceUnit.create(SCRIPT_FILENAME, source, /*tolerance*/ 1) parser.parse() log.debug('Parse complete') return new ParseStatus(ParseCode.COMPLETE) } catch (CompilationFailedException e) { // // FIXME: Seems like failedWithUnexpectedEOF() is not always set as expected, as in: // // class a { <--- is true here // def b() { <--- is false here :-( // if (parser.errorCollector.errorCount > 1 || !parser.failedWithUnexpectedEOF()) { // // HACK: Super insane hack... if we detect a syntax error, but the last line of the // buffer ends with a {, [, ''', """ or \ then ignore... // and pretend its okay, cause it might be... // // This seems to get around the problem with things like: // // class a { def b() { // String tmp = buffer[-1].trim() if (tmp.endsWith('{') || tmp.endsWith('[') || tmp.endsWith("'''") || tmp.endsWith('"""') || tmp.endsWith('\\')) { log.debug("Ignoring parse failure; might be valid: $e") } else { error = e } } } catch (Throwable e) { error = e } if (error) { log.debug("Parse error: $error") return new ParseStatus(error) } else { log.debug('Parse incomplete') return new ParseStatus(ParseCode.INCOMPLETE) } } } /** * Container for the parse code. */ final class ParseCode { static final ParseCode COMPLETE = new ParseCode(0) static final ParseCode INCOMPLETE = new ParseCode(1) static final ParseCode ERROR = new ParseCode(2) final int code private ParseCode(int code) { this.code = code } String toString() { return code } } /** * Container for parse status details. */ final class ParseStatus { final ParseCode code final Throwable cause ParseStatus(final ParseCode code, final Throwable cause) { this.code = code this.cause = cause } ParseStatus(final ParseCode code) { this(code, null) } ParseStatus(final Throwable cause) { this(ParseCode.ERROR, cause) } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/shell/ShellRunner.groovy0000644001501200150120000000436011707612046026001 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.shell import org.codehaus.groovy.tools.shell.util.Logger /** * Support for running a {@link Shell}. * * @version $Id$ * @author Jason Dillon */ abstract class ShellRunner implements Runnable { protected final Logger log = Logger.create(this.class) final Shell shell boolean running = false boolean breakOnNull = true Closure errorHandler = { e -> log.debug(e) running = false } ShellRunner(final Shell shell) { assert shell this.shell = shell } void run() { log.debug('Running') running = true while (running) { try { running = work() } catch (ExitNotification n) { throw n } catch (Throwable t) { log.debug("Work failed: $t", t) if (errorHandler) { errorHandler.call(t) } } } log.debug('Finished') } protected boolean work() { def line = readLine() if (log.debugEnabled) { log.debug("Read line: $line") } // Stop on null (maybe) if (line == null && breakOnNull) { return false // stop the loop } // Ignore empty lines if (line.trim().size() > 0) { def result = shell << line } return true } protected abstract String readLine() } groovy-1.8.6/src/main/org/codehaus/groovy/tools/GroovyStarter.java0000644001501200150120000001063411627206700024655 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.lang.reflect .*; import java.io.FileInputStream; /** * Helper class to help classworlds to load classes. */ public class GroovyStarter { static void printUsage() { System.out.println("possible programs are 'groovyc','groovy','console', and 'groovysh'"); System.exit(1); } public static void rootLoader(String args[]) { String conf = System.getProperty("groovy.starter.conf",null); LoaderConfiguration lc = new LoaderConfiguration(); // evaluate parameters boolean hadMain=false, hadConf=false, hadCP=false; int argsOffset = 0; while (args.length-argsOffset>0 && !(hadMain && hadConf && hadCP)) { if (args[argsOffset].equals("--classpath")) { if (hadCP) break; if (args.length==argsOffset+1) { exit("classpath parameter needs argument"); } lc.addClassPath(args[argsOffset+1]); argsOffset+=2; hadCP=true; } else if (args[argsOffset].equals("--main")) { if (hadMain) break; if (args.length==argsOffset+1) { exit("main parameter needs argument"); } lc.setMainClass(args[argsOffset+1]); argsOffset+=2; hadMain=true; } else if (args[argsOffset].equals("--conf")) { if (hadConf) break; if (args.length==argsOffset+1) { exit("conf parameter needs argument"); } conf=args[argsOffset+1]; argsOffset+=2; hadConf=true; } else { break; } } // this allows to override the commandline conf String confOverride = System.getProperty("groovy.starter.conf.override",null); if (confOverride!=null) conf = confOverride; // we need to know the class we want to start if (lc.getMainClass()==null && conf==null) { exit("no configuration file or main class specified"); } // copy arguments for main class String[] newArgs = new String[args.length-argsOffset]; for (int i=0; i * Note: this is very against the normal behavior of * classloaders. Normal is to first check parent and then look in * the resources you gave this classloader. *

      * It's possible to add urls to the classpath at runtime through * {@link addURL(URL)} *

      * Why using RootLoader? * If you have to load classes with multiple classloaders and a * classloader does know a class which depends on a class only * a child of this loader does know, then you won't be able to * load the class. To load the class the child is not allowed * to redirect it's search for the class to the parent first. * That way the child can load the class. If the child does not * have all classes to do this, this fails of course. *

      * For example: *

      *

       *       parentLoader   (has classpath: a.jar;c.jar)
       *           |
       *           |
       *       childLoader    (has classpath: a.jar;b.jar;c.jar)
       *       
      *

      * class C (from c.jar) extends B (from b.jar) *

      * childLoader.find("C") * --> parentLoader does know C.class, try to load it * --> to load C.class it has to load B.class * --> parentLoader is unable to find B.class in a.jar or c.jar * --> NoClassDefFoundException! *

      * if childLoader had tried to load the class by itself, there * would be no problem. Changing childLoader to be a RootLoader * instance will solve that problem. * * @author Jochen Theodorou */ public class RootLoader extends URLClassLoader { private Map customClasses = new HashMap(); /** * constructs a new RootLoader without classpath * * @param parent the parent Loader */ private RootLoader(ClassLoader parent) { this(new URL[0], parent); } /** * constructs a new RootLoader with a parent loader and an * array of URLs as classpath */ public RootLoader(URL[] urls, ClassLoader parent) { super(urls, parent); // major hack here...! try{ customClasses.put("org.w3c.dom.Node",super.loadClass("org.w3c.dom.Node",false)); } catch (Exception e) { /* ignore */ } } private static ClassLoader chooseParent() { ClassLoader cl = RootLoader.class.getClassLoader(); if (cl != null) return cl; return ClassLoader.getSystemClassLoader(); } /** * constructs a new RootLoader with a {@link LoaderConfiguration} * object which holds the classpath */ public RootLoader(LoaderConfiguration lc) { this(chooseParent()); Thread.currentThread().setContextClassLoader(this); URL[] urls = lc.getClassPathUrls(); for (URL url : urls) { addURL(url); } } /** * loads a class using the name of the class */ protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); } catch (ClassNotFoundException cnfe) { // IGNORE } if (c == null) c = super.loadClass(name, resolve); if (resolve) resolveClass(c); return c; } /** * returns the URL of a resource, or null if it is not found */ public URL getResource(String name) { URL url = findResource(name); if (url == null) url = super.getResource(name); return url; } /** * adds an url to the classpath of this classloader */ public void addURL(URL url) { super.addURL(url); } private Class oldFindClass(String name) throws ClassNotFoundException { return super.findClass(name); } protected Class findClass(String name) throws ClassNotFoundException { throw new ClassNotFoundException(name); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/GrapeMain.groovy0000644001501200150120000002455011715031256024274 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools import groovy.grape.Grape import org.apache.ivy.util.DefaultMessageLogger import org.apache.ivy.util.Message import org.apache.commons.cli.* //commands install = {arg, cmd -> if (arg.size() > 5 || arg.size() < 3) { println 'install requires two to four arguments: [] []' return } def ver = '*' if (arg.size() >= 4) { ver = arg[3] } def classifier = null if (arg.size() >= 5) { classifier = arg[4] } // set the instance so we can re-set the logger Grape.getInstance() setupLogging() try { Grape.grab(autoDownload: true, group: arg[1], module: arg[2], version: ver, classifier: classifier, noExceptions: true) } catch (Exception e) { println "An error occured : $ex" } } uninstall = {arg, cmd -> if (arg.size() != 4) { println 'uninstall requires three arguments: ' // TODO make version optional? support classifier? // println 'uninstall requires two to four arguments, [] []' return } String group = arg[1] String module = arg[2] String ver = arg[3] // def classifier = null // set the instance so we can re-set the logger Grape.getInstance() setupLogging() if (!Grape.enumerateGrapes().find {String groupName, Map g -> g.any {String moduleName, List versions -> group == groupName && module == moduleName && ver in versions } }) { println "uninstall did not find grape matching: $group $module $ver" def fuzzyMatches = Grape.enumerateGrapes().findAll { String groupName, Map g -> g.any {String moduleName, List versions -> groupName.contains(group) || moduleName.contains(module) || group.contains(groupName) || module.contains(moduleName) } } if (fuzzyMatches) { println 'possible matches:' fuzzyMatches.each { String groupName, Map g -> println " $groupName: $g" } } return } Grape.instance.uninstallArtifact(group, module, ver) } list = {arg, cmd -> println "" int moduleCount = 0 int versionCount = 0 // set the instance so we can re-set the logger Grape.getInstance() setupLogging() Grape.enumerateGrapes().each {String groupName, Map group -> group.each {String moduleName, List versions -> println "$groupName $moduleName $versions" moduleCount++ versionCount += versions.size() } } println "" println "$moduleCount Grape modules cached" println "$versionCount Grape module versions cached" } resolve = {arg, cmd -> Options options = new Options(); options.addOption( OptionBuilder.hasArg(false) .withLongOpt("ant") .create('a') ); options.addOption( OptionBuilder.hasArg(false) .withLongOpt("dos") .create('d') ); options.addOption( OptionBuilder.hasArg(false) .withLongOpt("shell") .create('s') ); options.addOption( OptionBuilder.hasArg(false) .withLongOpt("ivy") .create('i') ); CommandLine cmd2 = new PosixParser().parse(options, arg[1..-1] as String[], true); arg = cmd2.args // set the instance so we can re-set the logger Grape.getInstance() setupLogging(Message.MSG_ERR) if ((arg.size() % 3) != 0) { println 'There need to be a multiple of three arguments: (group module version)+' return } if (args.size() < 3) { println 'At least one Grape reference is required' return } def before, between, after def ivyFormatRequested = false if (cmd2.hasOption('a')) { before = '\n' } else if (cmd2.hasOption('d')) { before = 'set CLASSPATH=' between = ';' after = '' } else if (cmd2.hasOption('s')) { before = 'export CLASSPATH=' between = ':' after = '' } else if (cmd2.hasOption('i')) { ivyFormatRequested = true before = ' results += ('org="' + dep.group + '" name="' + dep.module + '" revision="' + dep.revision) } } if (results) { println "${before}${results.join(between)}${after}" } else { println 'Nothing was resolved' } } catch (Exception e) { println "Error in resolve:\n\t$e.message" if (e.message =~ /unresolved dependency/) println "Perhaps the grape is not installed?" } } def commands = [ 'install': [closure: install, shortHelp: 'Installs a particular grape'], 'uninstall': [closure: uninstall, shortHelp: 'Uninstalls a particular grape (non-transitively removes the respective jar file from the grape cache)'], 'list': [closure: list, shortHelp: 'Lists all installed grapes'], 'resolve': [closure: resolve, shortHelp: 'Enumerates the jars used by a grape'] ] // command line parsing Options options = new Options(); options.addOption( OptionBuilder.withLongOpt("define") .withDescription("define a system property") .hasArg(true) .withArgName("name=value") .create('D') ); options.addOption( OptionBuilder.hasArg(false) .withDescription("usage information") .withLongOpt("help") .create('h') ); // Logging Level Options options.addOptionGroup( new OptionGroup().addOption( OptionBuilder.hasArg(false) .withDescription("Log level 0 - only errors") .withLongOpt("quiet") .create('q')) .addOption( OptionBuilder.hasArg(false) .withDescription("Log level 1 - errors and warnings") .withLongOpt("warn") .create('w')) .addOption( OptionBuilder.hasArg(false) .withDescription("Log level 2 - info") .withLongOpt("info") .create('i')) .addOption( OptionBuilder.hasArg(false) .withDescription("Log level 3 - verbose") .withLongOpt("verbose") .create('V')) .addOption( OptionBuilder.hasArg(false) .withDescription("Log level 4 - debug") .withLongOpt("debug") .create('d')) ) options.addOption( OptionBuilder.hasArg(false) .withDescription("display the Groovy and JVM versions") .withLongOpt("version") .create('v') ); CommandLine cmd = new PosixParser().parse(options, args, true); grapeHelp = { int spacesLen = commands.keySet().max {it.length()}.length() + 3 String spaces = ' ' * spacesLen PrintWriter pw = new PrintWriter(binding.variables.out ?: System.out) new HelpFormatter().printHelp( pw, 80, "grape [options] [args]\n", "options:", options, 2, 4, null, // footer true); pw.flush() println "" println "commands:" commands.each {String k, v -> println " ${(k + spaces).substring(0, spacesLen)} $v.shortHelp" } println "" } setupLogging = {int defaultLevel = 2 -> // = Message.MSG_INFO -> some parsing error :( if (cmd.hasOption('q')) { Message.setDefaultLogger(new DefaultMessageLogger(Message.MSG_ERR)) } else if (cmd.hasOption('w')) { Message.setDefaultLogger(new DefaultMessageLogger(Message.MSG_WARN)) } else if (cmd.hasOption('i')) { Message.setDefaultLogger(new DefaultMessageLogger(Message.MSG_INFO)) } else if (cmd.hasOption('V')) { Message.setDefaultLogger(new DefaultMessageLogger(Message.MSG_VERBOSE)) } else if (cmd.hasOption('d')) { Message.setDefaultLogger(new DefaultMessageLogger(Message.MSG_DEBUG)) } else { Message.setDefaultLogger(new DefaultMessageLogger(defaultLevel)) } } if (cmd.hasOption('h')) { grapeHelp() return } if (cmd.hasOption('v')) { String version = GroovySystem.getVersion(); println "Groovy Version: $version JVM: ${System.getProperty('java.version')}" return } cmd.getOptionValues('D')?.each {String prop -> def (k, v) = prop.split ('=', 2) as List // array multiple assignment quirk System.setProperty(k, v ?: "") } String[] arg = cmd.args if (arg?.length == 0) { grapeHelp() } else if (commands.containsKey(arg[0])) { commands[arg[0]].closure(arg, cmd) } else { println "grape: '${arg[0]}' is not a grape command. See 'grape --help'" } groovy-1.8.6/src/main/org/codehaus/groovy/tools/Utilities.java0000644001501200150120000000462211627206700023776 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Various utility functions for use in the compiler. */ public abstract class Utilities { private static final Set INVALID_JAVA_IDENTIFIERS = new HashSet(Arrays.asList(( "abstract assert boolean break byte case catch char class const continue default do double else enum " + "extends final finally float for goto if implements import instanceof int interface long native new " + "package private protected public short static strictfp super switch synchronized this throw throws " + "transient try void volatile while true false null").split(" "))); /** * Returns a string made up of repetitions of the specified string. */ public static String repeatString( String pattern, int repeats ) { StringBuffer buffer = new StringBuffer( pattern.length() * repeats ); for( int i = 0; i < repeats; i++ ) { buffer.append( pattern ); } return new String( buffer ); } /** * Returns the end-of-line marker. */ public static String eol() { return eol; } /** * Tells if the given string is a valid Java identifier. */ public static boolean isJavaIdentifier(String name) { if (name.length() == 0 || INVALID_JAVA_IDENTIFIERS.contains(name)) return false; char[] chars = name.toCharArray(); if (!Character.isJavaIdentifierStart(chars[0])) return false; for (int i = 1; i < chars.length; i++ ) { if (!Character.isJavaIdentifierPart(chars[i])) return false; } return true; } private static String eol = System.getProperty( "line.separator", "\n" ); } groovy-1.8.6/src/main/org/codehaus/groovy/tools/gse/0000755001501200150120000000000011627206700021732 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/tools/gse/StringSetMap.java0000644001501200150120000000365711627206700025170 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.gse; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class StringSetMap extends LinkedHashMap> { public StringSetMap() { super(); } public StringSetMap(StringSetMap other) { for (String key : other.keySet()) { get(key).addAll(other.get(key)); } } public Set get(Object o){ String name = (String) o; Set set = super.get(name); if (set==null) { set = new LinkedHashSet(); put(name,set); } return set; } public void makeTransitiveHull() { Set nameSet = new TreeSet(keySet()); // TODO use it or lose it StringSetMap ret = new StringSetMap(this); for (String k: nameSet) { StringSetMap delta = new StringSetMap(); for (String i: nameSet) { for (String j: nameSet) { Set iSet = get(i); if (iSet.contains(k) && get(k).contains(j)) { delta.get(i).add(j); } } } for (String i: nameSet) get(i).addAll(delta.get(i)); } } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/gse/DependencyTracker.java0000644001501200150120000000776511627206700026206 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.gse; import java.util.Set; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.control.SourceUnit; public class DependencyTracker extends ClassCodeVisitorSupport { private Set current; private SourceUnit source; private StringSetMap cache; public DependencyTracker(SourceUnit source, StringSetMap cache) { this.source = source; this.cache = cache; } private void addToCache(ClassNode node){ if (!node.isPrimaryClassNode()) return; current.add(node.getName()); } private void addToCache(ClassNode[] nodes){ if (nodes==null) return; for (ClassNode node : nodes) addToCache(node); } @Override public void visitClass(ClassNode node) { Set old = current; current = cache.get(node.getName()); addToCache(node); addToCache(node.getSuperClass()); addToCache(node.getInterfaces()); super.visitClass(node); current = old; } @Override protected SourceUnit getSourceUnit() { return source; } @Override public void visitClassExpression(ClassExpression expression) { super.visitClassExpression(expression); addToCache(expression.getType()); } @Override public void visitField(FieldNode node) { super.visitField(node); addToCache(node.getType()); } @Override public void visitMethod(MethodNode node) { for (Parameter p : node.getParameters()) { addToCache(p.getType()); } addToCache(node.getReturnType()); addToCache(node.getExceptions()); super.visitMethod(node); } @Override public void visitArrayExpression(ArrayExpression expression) { super.visitArrayExpression(expression); addToCache(expression.getType()); } @Override public void visitCastExpression(CastExpression expression) { super.visitCastExpression(expression); addToCache(expression.getType()); } @Override public void visitVariableExpression(VariableExpression expression) { super.visitVariableExpression(expression); addToCache(expression.getType()); } @Override public void visitCatchStatement(CatchStatement statement) { super.visitCatchStatement(statement); addToCache(statement.getVariable().getType()); } @Override public void visitAnnotations(AnnotatedNode node) { super.visitAnnotations(node); for (AnnotationNode an : node.getAnnotations()) { addToCache(an.getClassNode()); } } @Override public void visitConstructorCallExpression(ConstructorCallExpression call) { super.visitConstructorCallExpression(call); addToCache(call.getType()); } } groovy-1.8.6/src/main/org/codehaus/groovy/tools/StringHelper.java0000644001501200150120000000512611627206700024431 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools; import java.util.LinkedList; import java.util.List; public class StringHelper { private static final char SPACE = ' ', SINGLE_QUOTE = '\'', DOUBLE_QUOTE = '"'; /** * This method tokenizes a string by space characters, * but ignores spaces in quoted parts,that are parts in * '' or "". The method does allows the usage of "" in '' * and '' in "". The space character between tokens is not * returned. * * @param s the string to tokenize * @return the tokens */ public static String[] tokenizeUnquoted(String s) { List tokens = new LinkedList(); int first = 0; while (first < s.length()) { first = skipWhitespace(s, first); int last = scanToken(s, first); if (first < last) { tokens.add(s.substring(first, last)); } first = last; } return (String[])tokens.toArray(new String[0]); } private static int scanToken(String s, int pos0) { int pos = pos0; while (pos < s.length()) { char c = s.charAt(pos); if (SPACE==c) break; pos++; if (SINGLE_QUOTE == c) { pos = scanQuoted(s, pos, SINGLE_QUOTE); } else if (DOUBLE_QUOTE == c) { pos = scanQuoted(s, pos, DOUBLE_QUOTE); } } return pos; } private static int scanQuoted(String s, int pos0, char quote) { int pos = pos0; while (pos < s.length()) { char c = s.charAt(pos++); if (quote == c) break; } return pos; } private static int skipWhitespace(String s, int pos0) { int pos = pos0; while (pos < s.length()) { char c = s.charAt(pos); if (SPACE!=c) break; pos++; } return pos; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/0000755001501200150120000000000011715031256021134 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/0000755001501200150120000000000011715031256023301 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/FlatNodeListTraversal.java0000644001501200150120000000375711627206700030374 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.util.Iterator; import java.util.List; import org.codehaus.groovy.antlr.AntlrASTProcessor; import org.codehaus.groovy.antlr.GroovySourceAST; import antlr.collections.AST; /** * A simple iterator over an ordered (flat) List of the nodes of the AST. * * @author Jeremy Rayner * @version $Revision: 3626 $ */ public class FlatNodeListTraversal extends TraversalHelper { public FlatNodeListTraversal(Visitor visitor) { super(visitor); } public AST process(AST t) { GroovySourceAST node = (GroovySourceAST) t; // fetch all the nodes in this AST into a List NodeCollector collector = new NodeCollector(); AntlrASTProcessor internalTraversal = new PreOrderTraversal(collector); internalTraversal.process(t); List listOfAllNodesInThisAST = collector.getNodes(); // process each node in turn setUp(node); Iterator itr = listOfAllNodesInThisAST.iterator(); while (itr.hasNext()) { GroovySourceAST currentNode = (GroovySourceAST) itr.next(); accept(currentNode); } tearDown(node); return null; } protected void accept(GroovySourceAST currentNode) { openingVisit(currentNode); closingVisit(currentNode); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/NodeAsHTMLPrinter.java0000644001501200150120000004146011707612044027354 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.io.PrintStream; import java.util.Stack; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; /** * A visitor that prints a html tags of each node to the supplied PrintStream * * @author Jeremy Rayner * @version $Revision$ */ public class NodeAsHTMLPrinter extends VisitorAdapter { private final String[] tokenNames; private final PrintStream out; private final Stack stack; /** * A visitor that prints a html tags, for each node, to the supplied PrintStream. * @param out supplied PrintStream to output nodes to * @param tokenNames an array of token names to use */ public NodeAsHTMLPrinter(PrintStream out,String[] tokenNames) { this.tokenNames = tokenNames; this.out = out; this.stack = new Stack(); } public void setUp() { out.println("

      ");
          }
      
          public void visitDefault(GroovySourceAST t,int visit) {
              if (visit == OPENING_VISIT) {
                  out.print("");
              } else if (visit == CLOSING_VISIT) {
                  out.print("");
              }
          }
      
          private String quote(String tokenName) {
              if (tokenName.length() > 0 && tokenName.charAt(0) != '\'')
                  return "'" + tokenName + "'";
              else
                  return "\"" + tokenName + "\"";
          }
      
          public void tearDown() {
              out.println("
      "); } private String colour(GroovySourceAST t) { String black = "000000"; String blue = "17178B"; String green = "008000"; //String purple = "7C308D"; String colour = black; switch (t.getType()) { case GroovyTokenTypes.ABSTRACT : case GroovyTokenTypes.ANNOTATION : case GroovyTokenTypes.ANNOTATIONS : case GroovyTokenTypes.ANNOTATION_ARRAY_INIT : case GroovyTokenTypes.ANNOTATION_DEF : case GroovyTokenTypes.ANNOTATION_FIELD_DEF : case GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR : case GroovyTokenTypes.ARRAY_DECLARATOR : case GroovyTokenTypes.ASSIGN : case GroovyTokenTypes.AT : case GroovyTokenTypes.BAND : case GroovyTokenTypes.BAND_ASSIGN : case GroovyTokenTypes.BIG_SUFFIX : case GroovyTokenTypes.BLOCK : case GroovyTokenTypes.BNOT : case GroovyTokenTypes.BOR : case GroovyTokenTypes.BOR_ASSIGN : case GroovyTokenTypes.BSR : case GroovyTokenTypes.BSR_ASSIGN : case GroovyTokenTypes.BXOR : case GroovyTokenTypes.BXOR_ASSIGN : case GroovyTokenTypes.CASE_GROUP : case GroovyTokenTypes.CLOSABLE_BLOCK : case GroovyTokenTypes.CLOSABLE_BLOCK_OP : case GroovyTokenTypes.COLON : case GroovyTokenTypes.COMMA : case GroovyTokenTypes.COMPARE_TO : case GroovyTokenTypes.CTOR_CALL : case GroovyTokenTypes.CTOR_IDENT : case GroovyTokenTypes.DEC : case GroovyTokenTypes.DIGIT : case GroovyTokenTypes.DIV : case GroovyTokenTypes.DIV_ASSIGN : case GroovyTokenTypes.DOLLAR : case GroovyTokenTypes.DOT : case GroovyTokenTypes.DYNAMIC_MEMBER : case GroovyTokenTypes.ELIST : case GroovyTokenTypes.EMPTY_STAT : case GroovyTokenTypes.ENUM_CONSTANT_DEF : case GroovyTokenTypes.ENUM_DEF : case GroovyTokenTypes.EOF : case GroovyTokenTypes.EQUAL : case GroovyTokenTypes.ESC : case GroovyTokenTypes.EXPONENT : case GroovyTokenTypes.EXPR : case GroovyTokenTypes.FINAL : case GroovyTokenTypes.FLOAT_SUFFIX : case GroovyTokenTypes.FOR_CONDITION : case GroovyTokenTypes.FOR_EACH_CLAUSE : case GroovyTokenTypes.FOR_INIT : case GroovyTokenTypes.FOR_IN_ITERABLE : case GroovyTokenTypes.FOR_ITERATOR : case GroovyTokenTypes.GE : case GroovyTokenTypes.GT : case GroovyTokenTypes.HEX_DIGIT : case GroovyTokenTypes.IDENT : case GroovyTokenTypes.IMPLICIT_PARAMETERS : case GroovyTokenTypes.INC : case GroovyTokenTypes.INDEX_OP : case GroovyTokenTypes.INSTANCE_INIT : case GroovyTokenTypes.INTERFACE_DEF : case GroovyTokenTypes.LABELED_ARG : case GroovyTokenTypes.LABELED_STAT : case GroovyTokenTypes.LAND : case GroovyTokenTypes.LBRACK : case GroovyTokenTypes.LCURLY : case GroovyTokenTypes.LE : case GroovyTokenTypes.LETTER : case GroovyTokenTypes.LIST_CONSTRUCTOR : case GroovyTokenTypes.LNOT : case GroovyTokenTypes.LOR : case GroovyTokenTypes.LPAREN : case GroovyTokenTypes.LT : case GroovyTokenTypes.MAP_CONSTRUCTOR : case GroovyTokenTypes.MEMBER_POINTER : case GroovyTokenTypes.METHOD_CALL : case GroovyTokenTypes.METHOD_DEF : case GroovyTokenTypes.MINUS : case GroovyTokenTypes.MINUS_ASSIGN : case GroovyTokenTypes.ML_COMMENT : case GroovyTokenTypes.MOD : case GroovyTokenTypes.MODIFIERS : case GroovyTokenTypes.MOD_ASSIGN : case GroovyTokenTypes.NLS : case GroovyTokenTypes.NOT_EQUAL : case GroovyTokenTypes.NULL_TREE_LOOKAHEAD : case GroovyTokenTypes.NUM_BIG_DECIMAL : case GroovyTokenTypes.NUM_BIG_INT : case GroovyTokenTypes.NUM_DOUBLE : case GroovyTokenTypes.NUM_FLOAT : case GroovyTokenTypes.NUM_INT : case GroovyTokenTypes.NUM_LONG : case GroovyTokenTypes.OBJBLOCK : case GroovyTokenTypes.ONE_NL : case GroovyTokenTypes.OPTIONAL_DOT : case GroovyTokenTypes.PARAMETERS : case GroovyTokenTypes.PARAMETER_DEF : case GroovyTokenTypes.PLUS : case GroovyTokenTypes.PLUS_ASSIGN : case GroovyTokenTypes.POST_DEC : case GroovyTokenTypes.POST_INC : case GroovyTokenTypes.QUESTION : case GroovyTokenTypes.RANGE_EXCLUSIVE : case GroovyTokenTypes.RANGE_INCLUSIVE : case GroovyTokenTypes.RBRACK : case GroovyTokenTypes.RCURLY : case GroovyTokenTypes.REGEXP_CTOR_END : case GroovyTokenTypes.REGEXP_SYMBOL : case GroovyTokenTypes.REGEX_FIND : case GroovyTokenTypes.REGEX_MATCH : case GroovyTokenTypes.RPAREN : case GroovyTokenTypes.SELECT_SLOT : case GroovyTokenTypes.SEMI : case GroovyTokenTypes.SH_COMMENT : case GroovyTokenTypes.SL : case GroovyTokenTypes.SLIST : case GroovyTokenTypes.SL_ASSIGN : case GroovyTokenTypes.SL_COMMENT : case GroovyTokenTypes.SPREAD_ARG : case GroovyTokenTypes.SPREAD_DOT : case GroovyTokenTypes.SPREAD_MAP_ARG : case GroovyTokenTypes.SR : case GroovyTokenTypes.SR_ASSIGN : case GroovyTokenTypes.STAR : case GroovyTokenTypes.STAR_ASSIGN : case GroovyTokenTypes.STAR_STAR : case GroovyTokenTypes.STAR_STAR_ASSIGN : case GroovyTokenTypes.STATIC_IMPORT : case GroovyTokenTypes.STATIC_INIT : case GroovyTokenTypes.STRICTFP : case GroovyTokenTypes.STRING_CH : case GroovyTokenTypes.STRING_CONSTRUCTOR : case GroovyTokenTypes.STRING_CTOR_END : case GroovyTokenTypes.STRING_CTOR_MIDDLE : case GroovyTokenTypes.STRING_CTOR_START : case GroovyTokenTypes.STRING_NL : case GroovyTokenTypes.SUPER_CTOR_CALL : case GroovyTokenTypes.TRIPLE_DOT : case GroovyTokenTypes.TYPECAST : case GroovyTokenTypes.TYPE_ARGUMENT : case GroovyTokenTypes.TYPE_ARGUMENTS : case GroovyTokenTypes.TYPE_LOWER_BOUNDS : case GroovyTokenTypes.TYPE_PARAMETER : case GroovyTokenTypes.TYPE_PARAMETERS : case GroovyTokenTypes.TYPE_UPPER_BOUNDS : case GroovyTokenTypes.UNARY_MINUS : case GroovyTokenTypes.UNARY_PLUS : case GroovyTokenTypes.UNUSED_CONST : case GroovyTokenTypes.UNUSED_DO : case GroovyTokenTypes.UNUSED_GOTO : case GroovyTokenTypes.VARIABLE_DEF : case GroovyTokenTypes.VARIABLE_PARAMETER_DEF : case GroovyTokenTypes.VOCAB : case GroovyTokenTypes.WILDCARD_TYPE : case GroovyTokenTypes.WS : colour = black; break; case GroovyTokenTypes.STRING_LITERAL : case GroovyTokenTypes.REGEXP_LITERAL : case GroovyTokenTypes.DOLLAR_REGEXP_LITERAL : colour = green; break; case GroovyTokenTypes.CLASS_DEF : case GroovyTokenTypes.EXTENDS_CLAUSE : case GroovyTokenTypes.IMPLEMENTS_CLAUSE : case GroovyTokenTypes.IMPORT : case GroovyTokenTypes.LITERAL_as : case GroovyTokenTypes.LITERAL_assert : case GroovyTokenTypes.LITERAL_boolean : case GroovyTokenTypes.LITERAL_break : case GroovyTokenTypes.LITERAL_byte : case GroovyTokenTypes.LITERAL_case : case GroovyTokenTypes.LITERAL_catch : case GroovyTokenTypes.LITERAL_char : case GroovyTokenTypes.LITERAL_class : case GroovyTokenTypes.LITERAL_continue : case GroovyTokenTypes.LITERAL_def : case GroovyTokenTypes.LITERAL_default : case GroovyTokenTypes.LITERAL_double : case GroovyTokenTypes.LITERAL_else : case GroovyTokenTypes.LITERAL_enum : case GroovyTokenTypes.LITERAL_extends : case GroovyTokenTypes.LITERAL_false : case GroovyTokenTypes.LITERAL_finally : case GroovyTokenTypes.LITERAL_float : case GroovyTokenTypes.LITERAL_for : case GroovyTokenTypes.LITERAL_if : case GroovyTokenTypes.LITERAL_implements : case GroovyTokenTypes.LITERAL_import : case GroovyTokenTypes.LITERAL_in : case GroovyTokenTypes.LITERAL_instanceof : case GroovyTokenTypes.LITERAL_int : case GroovyTokenTypes.LITERAL_interface : case GroovyTokenTypes.LITERAL_long : case GroovyTokenTypes.LITERAL_native : case GroovyTokenTypes.LITERAL_new : case GroovyTokenTypes.LITERAL_null : case GroovyTokenTypes.LITERAL_package : case GroovyTokenTypes.LITERAL_private : case GroovyTokenTypes.LITERAL_protected : case GroovyTokenTypes.LITERAL_public : case GroovyTokenTypes.LITERAL_return : case GroovyTokenTypes.LITERAL_short : case GroovyTokenTypes.LITERAL_static : case GroovyTokenTypes.LITERAL_super : case GroovyTokenTypes.LITERAL_switch : case GroovyTokenTypes.LITERAL_synchronized : case GroovyTokenTypes.LITERAL_this : case GroovyTokenTypes.LITERAL_threadsafe : case GroovyTokenTypes.LITERAL_throw : case GroovyTokenTypes.LITERAL_throws : case GroovyTokenTypes.LITERAL_transient : case GroovyTokenTypes.LITERAL_true : case GroovyTokenTypes.LITERAL_try : case GroovyTokenTypes.LITERAL_void : case GroovyTokenTypes.LITERAL_volatile : case GroovyTokenTypes.LITERAL_while : case GroovyTokenTypes.PACKAGE_DEF : case GroovyTokenTypes.TYPE : colour = blue; break; default: colour = black; break; } return colour; } public void push(GroovySourceAST t) { stack.push(t); } public GroovySourceAST pop() { if (!stack.empty()) { return (GroovySourceAST) stack.pop(); } return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/NodeCollector.java0000644001501200150120000000241311627206700026700 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.util.ArrayList; import java.util.List; import org.codehaus.groovy.antlr.GroovySourceAST; /** * A simple antlr AST visitor that collects all nodes into a List. * * @author Jeremy Rayner * @version $Revision: 4032 $ */ public class NodeCollector extends VisitorAdapter { private List nodes; public NodeCollector() { nodes = new ArrayList(); } public List getNodes() { return nodes; } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { nodes.add(t); } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/MindMapPrinter.java0000644001501200150120000004607611707612044027053 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.LineColumn; import org.codehaus.groovy.antlr.SourceBuffer; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import java.io.PrintStream; /** * An antlr AST visitor that prints a format suitable for viewing in http://freemind.sourceforge.net * * @author Jeremy Rayner * @version $Revision$ */ public class MindMapPrinter extends VisitorAdapter { private final String[] tokenNames; private final PrintStream out; private int depth; private SourceBuffer sourceBuffer; /** * A visitor that prints a format suitable for viewing in http://freemind.sourceforge.net * @param out where to print the mindmap file contents to * @param tokenNames an array of token names from antlr */ public MindMapPrinter(PrintStream out,String[] tokenNames) { this.tokenNames = tokenNames; this.out = out; } public MindMapPrinter(PrintStream out,String[] tokenNames, SourceBuffer sourceBuffer) { this.tokenNames = tokenNames; this.out = out; this.sourceBuffer = sourceBuffer; } public void setUp() { depth = 0; out.println(""); } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { depth++; String name = getName(t); String colour = getColour(t); String folded = getFolded(t); out.print(""); } else if (visit == CLOSING_VISIT) { out.println(""); depth--; } } public void tearDown() { out.println(""); } private String getFolded(GroovySourceAST t) { if (depth > 2 && t.getNumberOfChildren() > 0) { switch (t.getType()) { case GroovyTokenTypes.EXPR : case GroovyTokenTypes.METHOD_DEF : case GroovyTokenTypes.VARIABLE_DEF : return " FOLDED='true'"; } } if (t.getType() == GroovyTokenTypes.IMPORT) { return " FOLDED='true'"; } return ""; } private String getColour(GroovySourceAST t) { String colour = ""; String black = " COLOR=\"#000000\""; String cyan = " COLOR=\"#006699\""; String blue = " COLOR=\"#17178B\""; String green = " COLOR=\"#008000\""; switch (t.getType()) { case GroovyTokenTypes.ABSTRACT : case GroovyTokenTypes.ANNOTATION : case GroovyTokenTypes.ANNOTATIONS : case GroovyTokenTypes.ANNOTATION_ARRAY_INIT : case GroovyTokenTypes.ANNOTATION_DEF : case GroovyTokenTypes.ANNOTATION_FIELD_DEF : case GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR : case GroovyTokenTypes.ARRAY_DECLARATOR : case GroovyTokenTypes.ASSIGN : case GroovyTokenTypes.AT : case GroovyTokenTypes.BAND : case GroovyTokenTypes.BAND_ASSIGN : case GroovyTokenTypes.BIG_SUFFIX : case GroovyTokenTypes.BLOCK : case GroovyTokenTypes.BNOT : case GroovyTokenTypes.BOR : case GroovyTokenTypes.BOR_ASSIGN : case GroovyTokenTypes.BSR : case GroovyTokenTypes.BSR_ASSIGN : case GroovyTokenTypes.BXOR : case GroovyTokenTypes.BXOR_ASSIGN : case GroovyTokenTypes.CASE_GROUP : case GroovyTokenTypes.CLOSABLE_BLOCK : case GroovyTokenTypes.CLOSABLE_BLOCK_OP : case GroovyTokenTypes.COLON : case GroovyTokenTypes.COMMA : case GroovyTokenTypes.COMPARE_TO : case GroovyTokenTypes.CTOR_CALL : case GroovyTokenTypes.CTOR_IDENT : case GroovyTokenTypes.DEC : case GroovyTokenTypes.DIGIT : case GroovyTokenTypes.DIV : case GroovyTokenTypes.DIV_ASSIGN : case GroovyTokenTypes.DOLLAR : case GroovyTokenTypes.DOT : case GroovyTokenTypes.DYNAMIC_MEMBER : case GroovyTokenTypes.ELIST : case GroovyTokenTypes.EMPTY_STAT : case GroovyTokenTypes.ENUM_CONSTANT_DEF : case GroovyTokenTypes.ENUM_DEF : case GroovyTokenTypes.EOF : case GroovyTokenTypes.EQUAL : case GroovyTokenTypes.ESC : case GroovyTokenTypes.EXPONENT : case GroovyTokenTypes.EXPR : case GroovyTokenTypes.FINAL : case GroovyTokenTypes.FLOAT_SUFFIX : case GroovyTokenTypes.FOR_CONDITION : case GroovyTokenTypes.FOR_EACH_CLAUSE : case GroovyTokenTypes.FOR_INIT : case GroovyTokenTypes.FOR_IN_ITERABLE : case GroovyTokenTypes.FOR_ITERATOR : case GroovyTokenTypes.GE : case GroovyTokenTypes.GT : case GroovyTokenTypes.HEX_DIGIT : case GroovyTokenTypes.IMPLICIT_PARAMETERS : case GroovyTokenTypes.INC : case GroovyTokenTypes.INDEX_OP : case GroovyTokenTypes.INSTANCE_INIT : case GroovyTokenTypes.INTERFACE_DEF : case GroovyTokenTypes.LABELED_ARG : case GroovyTokenTypes.LABELED_STAT : case GroovyTokenTypes.LAND : case GroovyTokenTypes.LBRACK : case GroovyTokenTypes.LCURLY : case GroovyTokenTypes.LE : case GroovyTokenTypes.LETTER : case GroovyTokenTypes.LIST_CONSTRUCTOR : case GroovyTokenTypes.LNOT : case GroovyTokenTypes.LOR : case GroovyTokenTypes.LPAREN : case GroovyTokenTypes.LT : case GroovyTokenTypes.MAP_CONSTRUCTOR : case GroovyTokenTypes.MEMBER_POINTER : case GroovyTokenTypes.METHOD_CALL : case GroovyTokenTypes.METHOD_DEF : case GroovyTokenTypes.MINUS : case GroovyTokenTypes.MINUS_ASSIGN : case GroovyTokenTypes.ML_COMMENT : case GroovyTokenTypes.MOD : case GroovyTokenTypes.MODIFIERS : case GroovyTokenTypes.MOD_ASSIGN : case GroovyTokenTypes.NLS : case GroovyTokenTypes.NOT_EQUAL : case GroovyTokenTypes.NULL_TREE_LOOKAHEAD : case GroovyTokenTypes.NUM_BIG_DECIMAL : case GroovyTokenTypes.NUM_BIG_INT : case GroovyTokenTypes.NUM_DOUBLE : case GroovyTokenTypes.NUM_FLOAT : case GroovyTokenTypes.NUM_INT : case GroovyTokenTypes.NUM_LONG : case GroovyTokenTypes.OBJBLOCK : case GroovyTokenTypes.ONE_NL : case GroovyTokenTypes.OPTIONAL_DOT : case GroovyTokenTypes.PARAMETERS : case GroovyTokenTypes.PARAMETER_DEF : case GroovyTokenTypes.PLUS : case GroovyTokenTypes.PLUS_ASSIGN : case GroovyTokenTypes.POST_DEC : case GroovyTokenTypes.POST_INC : case GroovyTokenTypes.QUESTION : case GroovyTokenTypes.RANGE_EXCLUSIVE : case GroovyTokenTypes.RANGE_INCLUSIVE : case GroovyTokenTypes.RBRACK : case GroovyTokenTypes.RCURLY : case GroovyTokenTypes.REGEXP_CTOR_END : case GroovyTokenTypes.REGEXP_SYMBOL : case GroovyTokenTypes.REGEX_FIND : case GroovyTokenTypes.REGEX_MATCH : case GroovyTokenTypes.RPAREN : case GroovyTokenTypes.SELECT_SLOT : case GroovyTokenTypes.SEMI : case GroovyTokenTypes.SH_COMMENT : case GroovyTokenTypes.SL : case GroovyTokenTypes.SLIST : case GroovyTokenTypes.SL_ASSIGN : case GroovyTokenTypes.SL_COMMENT : case GroovyTokenTypes.SPREAD_ARG : case GroovyTokenTypes.SPREAD_DOT : case GroovyTokenTypes.SPREAD_MAP_ARG : case GroovyTokenTypes.SR : case GroovyTokenTypes.SR_ASSIGN : case GroovyTokenTypes.STAR : case GroovyTokenTypes.STAR_ASSIGN : case GroovyTokenTypes.STAR_STAR : case GroovyTokenTypes.STAR_STAR_ASSIGN : case GroovyTokenTypes.STATIC_IMPORT : case GroovyTokenTypes.STATIC_INIT : case GroovyTokenTypes.STRICTFP : case GroovyTokenTypes.STRING_CH : case GroovyTokenTypes.STRING_CONSTRUCTOR : case GroovyTokenTypes.STRING_CTOR_END : case GroovyTokenTypes.STRING_CTOR_MIDDLE : case GroovyTokenTypes.STRING_CTOR_START : case GroovyTokenTypes.STRING_NL : case GroovyTokenTypes.SUPER_CTOR_CALL : case GroovyTokenTypes.TRIPLE_DOT : case GroovyTokenTypes.TYPECAST : case GroovyTokenTypes.TYPE_ARGUMENT : case GroovyTokenTypes.TYPE_ARGUMENTS : case GroovyTokenTypes.TYPE_LOWER_BOUNDS : case GroovyTokenTypes.TYPE_PARAMETER : case GroovyTokenTypes.TYPE_PARAMETERS : case GroovyTokenTypes.TYPE_UPPER_BOUNDS : case GroovyTokenTypes.UNARY_MINUS : case GroovyTokenTypes.UNARY_PLUS : case GroovyTokenTypes.UNUSED_CONST : case GroovyTokenTypes.UNUSED_DO : case GroovyTokenTypes.UNUSED_GOTO : case GroovyTokenTypes.VARIABLE_DEF : case GroovyTokenTypes.VARIABLE_PARAMETER_DEF : case GroovyTokenTypes.VOCAB : case GroovyTokenTypes.WILDCARD_TYPE : case GroovyTokenTypes.WS : colour = black; break; case GroovyTokenTypes.STRING_LITERAL : case GroovyTokenTypes.REGEXP_LITERAL : case GroovyTokenTypes.DOLLAR_REGEXP_LITERAL : colour = green; break; case GroovyTokenTypes.CLASS_DEF : case GroovyTokenTypes.EXTENDS_CLAUSE : case GroovyTokenTypes.IMPLEMENTS_CLAUSE : case GroovyTokenTypes.IMPORT : case GroovyTokenTypes.LITERAL_as : case GroovyTokenTypes.LITERAL_assert : case GroovyTokenTypes.LITERAL_boolean : case GroovyTokenTypes.LITERAL_break : case GroovyTokenTypes.LITERAL_byte : case GroovyTokenTypes.LITERAL_case : case GroovyTokenTypes.LITERAL_catch : case GroovyTokenTypes.LITERAL_char : case GroovyTokenTypes.LITERAL_class : case GroovyTokenTypes.LITERAL_continue : case GroovyTokenTypes.LITERAL_def : case GroovyTokenTypes.LITERAL_default : case GroovyTokenTypes.LITERAL_double : case GroovyTokenTypes.LITERAL_else : case GroovyTokenTypes.LITERAL_enum : case GroovyTokenTypes.LITERAL_extends : case GroovyTokenTypes.LITERAL_false : case GroovyTokenTypes.LITERAL_finally : case GroovyTokenTypes.LITERAL_float : case GroovyTokenTypes.LITERAL_for : case GroovyTokenTypes.LITERAL_if : case GroovyTokenTypes.LITERAL_implements : case GroovyTokenTypes.LITERAL_import : case GroovyTokenTypes.LITERAL_in : case GroovyTokenTypes.LITERAL_instanceof : case GroovyTokenTypes.LITERAL_int : case GroovyTokenTypes.LITERAL_interface : case GroovyTokenTypes.LITERAL_long : case GroovyTokenTypes.LITERAL_native : case GroovyTokenTypes.LITERAL_new : case GroovyTokenTypes.LITERAL_null : case GroovyTokenTypes.LITERAL_package : case GroovyTokenTypes.LITERAL_private : case GroovyTokenTypes.LITERAL_protected : case GroovyTokenTypes.LITERAL_public : case GroovyTokenTypes.LITERAL_return : case GroovyTokenTypes.LITERAL_short : case GroovyTokenTypes.LITERAL_static : case GroovyTokenTypes.LITERAL_super : case GroovyTokenTypes.LITERAL_switch : case GroovyTokenTypes.LITERAL_synchronized : case GroovyTokenTypes.LITERAL_this : case GroovyTokenTypes.LITERAL_threadsafe : case GroovyTokenTypes.LITERAL_throw : case GroovyTokenTypes.LITERAL_throws : case GroovyTokenTypes.LITERAL_transient : case GroovyTokenTypes.LITERAL_true : case GroovyTokenTypes.LITERAL_try : case GroovyTokenTypes.LITERAL_void : case GroovyTokenTypes.LITERAL_volatile : case GroovyTokenTypes.LITERAL_while : case GroovyTokenTypes.PACKAGE_DEF : case GroovyTokenTypes.TYPE : colour = blue; break; case GroovyTokenTypes.IDENT : colour = cyan; break; default: colour = black; break; } // leaf nodes that haven't been coloured yet if (black.equals(colour) && t.getNumberOfChildren() == 0) { colour = cyan; } return colour; } private String getName(GroovySourceAST t) { String name = tokenNames[t.getType()] + " <" + t.getType() + ">"; if (!(escape(tokenNames[t.getType()]).equals(escape(t.getText())))) { name = name + " : " + t.getText(); } switch (t.getType()) { case GroovyTokenTypes.METHOD_DEF : case GroovyTokenTypes.VARIABLE_DEF : GroovySourceAST identNode = t.childOfType(GroovyTokenTypes.IDENT); if (identNode != null) { name = name + " : " + identNode.getText() + ""; } } name = escape(name); if (sourceBuffer != null) { name += " "; name += t.getLine() + "," + t.getColumn() + " - " + t.getLineLast() + "," + t.getColumnLast(); name += " "; name += escape(sourceBuffer.getSnippet(new LineColumn(t.getLine(), t.getColumn()), new LineColumn(t.getLineLast(), t.getColumnLast()))); } return name; } private String escape(String name) { if (name == null) return null; // remove middle of large bits of text if (name.length() > 200) { name = name.substring(0,100) + " ..... " + name.substring(name.length() - 100); } name = name.replace('"',' '); name = name.replace('\'',' '); name = name.replaceAll("&","&"); name = name.replaceAll("<","<"); name = name.replaceAll(">",">"); name = name.trim(); return name; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/SourcePrinter.java0000644001501200150120000010300511715031256026747 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.io.PrintStream; import java.util.Stack; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; /** * An antlr AST visitor that prints groovy source code for each visited node * to the supplied PrintStream. * * @author Jeremy Rayner * @version $Revision$ */ public class SourcePrinter extends VisitorAdapter { private final String[] tokenNames; private int tabLevel; private int lastLinePrinted; private final boolean newLines; protected final PrintStream out; private String className; private final Stack stack; private int stringConstructorCounter; /** * A visitor that prints groovy source code for each node visited. * @param out where to print the source code to * @param tokenNames an array of token names from antlr */ public SourcePrinter(PrintStream out,String[] tokenNames) { this(out,tokenNames,true); } /** * A visitor that prints groovy source code for each node visited. * @param out where to print the source code to * @param tokenNames an array of token names from antlr * @param newLines output newline character */ public SourcePrinter(PrintStream out,String[] tokenNames, boolean newLines) { this.tokenNames = tokenNames; tabLevel = 0; lastLinePrinted = 0; this.out = out; this.newLines = newLines; this.stack = new Stack(); } public void visitAbstract(GroovySourceAST t, int visit) { print(t,visit,"abstract ",null,null); } public void visitAnnotation(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { print(t,visit,"@"); } if (visit == SECOND_VISIT) { print(t,visit,"("); } if (visit == SUBSEQUENT_VISIT) { print(t,visit,", "); } if (visit == CLOSING_VISIT) { if (t.getNumberOfChildren() > 1) { print(t,visit,") "); } else { print(t,visit," "); } } } public void visitAnnotations(GroovySourceAST t, int visit) { // do nothing } public void visitAnnotationDef(GroovySourceAST t,int visit) { print(t,visit,"@interface ",null,null); } public void visitAnnotationFieldDef(GroovySourceAST t, int visit) { print(t,visit,"() ","default ",null); } public void visitAnnotationMemberValuePair(GroovySourceAST t, int visit) { print(t,visit," = ",null,null); } public void visitArrayDeclarator(GroovySourceAST t, int visit) { //int primes = new int(5) if (getParentNode().getType() == GroovyTokenTypes.TYPE || getParentNode().getType() == GroovyTokenTypes.TYPECAST) { // ugly hack // type definition, i.e. int[] x; print(t,visit,null,null,"[]"); } else { // usually in new, i.e. def y = new int[5]; print(t,visit,"[",null,"]"); } } public void visitAssign(GroovySourceAST t,int visit) { print(t,visit," = ",null,null); } // visitAt() ... // token type 'AT' should never be visited, as annotation definitions and usage, and // direct field access should have all moved this token out of the way. No test needed. // one of the BAND tokens is actually replaced by TYPE_UPPER_BOUNDS (e.g. class Foo {T t} ) public void visitBand(GroovySourceAST t, int visit) { print(t,visit," & ",null,null); } public void visitBandAssign(GroovySourceAST t,int visit) { print(t,visit," &= ",null,null); } // visitBigSuffix() ... // token type BIG_SUFFIX never created/visited, NUM_BIG_INT, NUM_BIG_DECIMAL instead... // visitBlock() ... // token type BLOCK never created/visited, see CLOSABLE_BLOCK etc... public void visitBnot(GroovySourceAST t, int visit) { print(t,visit,"~",null,null); } // Note: old closure syntax using BOR is deprecated, and also never creates/visits a BOR node public void visitBor(GroovySourceAST t, int visit) { print(t,visit," | ",null,null); } public void visitBorAssign(GroovySourceAST t,int visit) { print(t,visit," |= ",null,null); } public void visitBsr(GroovySourceAST t, int visit) { print(t,visit," >>> ",null,null); } public void visitBsrAssign(GroovySourceAST t,int visit) { print(t,visit," >>>= ",null,null); } public void visitBxor(GroovySourceAST t, int visit) { print(t,visit," ^ ",null,null); } public void visitBxorAssign(GroovySourceAST t,int visit) { print(t,visit," ^= ",null,null); } public void visitCaseGroup(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { tabLevel++; } if (visit == CLOSING_VISIT) { tabLevel--; } } public void visitClassDef(GroovySourceAST t,int visit) { print(t,visit,"class ",null,null); if (visit == OPENING_VISIT) { // store name of class away for use in constructor ident className = t.childOfType(GroovyTokenTypes.IDENT).getText(); } } public void visitClosedBlock(GroovySourceAST t, int visit) { printUpdatingTabLevel(t,visit,"{","-> ","}"); } public void visitClosureList(GroovySourceAST t, int visit) { print(t,visit,"(","; ",")"); } // visitClosureOp ... // token type CLOSABLE_BLOCK_OP never created/visited, see CLOSABLE_BLOCK... // visitColon ... // token type COLON never created/visited, see LABELED_STAT, FOR_IN_ITERABLE, // ASSERT, CASE, QUESTION, MAP_CONSTRUCTOR, LABELED_ARG, SPREAD_MAP_ARG // visitComma ... // token type COMMA never created/visited, // see TYPE_ARGUMENTS, ANNOTATION, many others ... public void visitCompareTo(GroovySourceAST t,int visit) { print(t,visit," <=> ",null,null); } public void visitCtorCall(GroovySourceAST t,int visit) { printUpdatingTabLevel(t,visit,"this("," ",")"); } public void visitCtorIdent(GroovySourceAST t, int visit) { // use name of class for constructor from the class definition print(t,visit,className,null,null); } public void visitDec(GroovySourceAST t, int visit) { print(t,visit,"--",null,null); } // visitDigit ... // never created/visited public void visitDiv(GroovySourceAST t, int visit) { print(t,visit," / ",null,null); } public void visitDivAssign(GroovySourceAST t,int visit) { print(t,visit," /= ",null,null); } // visitDollar ... // token type DOLLAR never created/visited, see SCOPE_ESCAPE instead public void visitDot(GroovySourceAST t,int visit) { print(t,visit,".",null,null); } public void visitDynamicMember(GroovySourceAST t, int visit) { if (t.childOfType(GroovyTokenTypes.STRING_CONSTRUCTOR) == null) { printUpdatingTabLevel(t,visit,"(",null,")"); } } public void visitElist(GroovySourceAST t,int visit) { if (getParentNode().getType() == GroovyTokenTypes.ENUM_CONSTANT_DEF) { print(t,visit,"(",", ",")"); } else { print(t,visit,null,", ",null); } } // visitEmptyStat ... // token type EMPTY_STAT obsolete and should be removed, never visited/created public void visitEnumConstantDef(GroovySourceAST t,int visit) { GroovySourceAST sibling = (GroovySourceAST)t.getNextSibling(); if (sibling != null && sibling.getType() == GroovyTokenTypes.ENUM_CONSTANT_DEF) { print(t,visit,null,null,", "); } } public void visitEnumDef(GroovySourceAST t,int visit) { print(t,visit,"enum ",null,null); } // visitEof ... // token type EOF never visited/created public void visitEqual(GroovySourceAST t,int visit) { print(t,visit," == ",null,null); } // visitExponent ... // token type EXPONENT only used by lexer, never visited/created public void visitExpr(GroovySourceAST t,int visit) { // do nothing } public void visitExtendsClause(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { if (t.getNumberOfChildren() != 0) { print(t,visit," extends "); } } } public void visitFinal(GroovySourceAST t, int visit) { print(t,visit,"final ",null,null); } // visitFloatSuffix ... never visited/created see NUM_DOUBLE or NUM_FLOAT instead public void visitForCondition(GroovySourceAST t, int visit) { print(t,visit," ; ",null,null); } // visitForEachClause ... // FOR_EACH_CLAUSE obsolete and should be removed, never visited/created public void visitForInit(GroovySourceAST t, int visit) { print(t,visit,"(",null,null); } public void visitForInIterable(GroovySourceAST t, int visit) { printUpdatingTabLevel(t,visit,"("," in ",") "); } public void visitForIterator(GroovySourceAST t, int visit) { print(t,visit," ; ",null,")"); } public void visitGe(GroovySourceAST t, int visit) { print(t,visit," >= ",null,null); } public void visitGt(GroovySourceAST t, int visit) { print(t,visit," > ",null,null); } public void visitIdent(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitImplementsClause(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { if (t.getNumberOfChildren() != 0) { print(t,visit," implements "); } } if (visit == CLOSING_VISIT) { //space between classdef and objblock print(t,visit," "); } } public void visitImplicitParameters(GroovySourceAST t, int visit) { // do nothing } public void visitImport(GroovySourceAST t,int visit) { print(t,visit,"import ",null,null); } public void visitInc(GroovySourceAST t, int visit) { print(t,visit,"++",null,null); } public void visitIndexOp(GroovySourceAST t, int visit) { printUpdatingTabLevel(t,visit,"[",null,"]"); } public void visitInterfaceDef(GroovySourceAST t,int visit) { print(t,visit,"interface ",null,null); } public void visitInstanceInit(GroovySourceAST t, int visit) { // do nothing } public void visitLabeledArg(GroovySourceAST t, int visit) { print(t,visit,":",null,null); } public void visitLabeledStat(GroovySourceAST t, int visit) { print(t,visit,":",null,null); } public void visitLand(GroovySourceAST t, int visit) { print(t,visit," && ",null,null); } // visit lbrack() // token type LBRACK only used inside parser, never visited/created // visit lcurly() // token type LCURLY only used inside parser, never visited/created public void visitLe(GroovySourceAST t, int visit) { print(t,visit," <= ",null,null); } // visitLetter ... // token type LETTER only used by lexer, never visited/created public void visitListConstructor(GroovySourceAST t, int visit) { printUpdatingTabLevel(t,visit,"[",null,"]"); } public void visitLiteralAs(GroovySourceAST t,int visit) { print(t,visit," as ",null,null); } public void visitLiteralAssert(GroovySourceAST t,int visit) { if (t.getNumberOfChildren() > 1) { print(t,visit,"assert ",null," : "); } else { print(t,visit,"assert ",null,null); } } public void visitLiteralBoolean(GroovySourceAST t, int visit) { print(t,visit,"boolean",null,null); } public void visitLiteralBreak(GroovySourceAST t, int visit) { print(t,visit,"break ",null,null); } public void visitLiteralByte(GroovySourceAST t, int visit) { print(t,visit,"byte",null,null); } public void visitLiteralCase(GroovySourceAST t, int visit) { print(t,visit,"case ",null,":"); } public void visitLiteralCatch(GroovySourceAST t,int visit) { printUpdatingTabLevel(t,visit," catch (",null,") "); } public void visitLiteralChar(GroovySourceAST t, int visit) { print(t,visit,"char",null,null); } // visitLiteralClass ... // token type "class" only used by parser, never visited/created directly public void visitLiteralContinue(GroovySourceAST t, int visit) { print(t,visit,"continue ",null,null); } // visitLiteralDef ... // token type "def" only used by parser, never visited/created directly public void visitLiteralDefault(GroovySourceAST t,int visit) { print(t,visit,"default",null,":"); } public void visitLiteralDouble(GroovySourceAST t, int visit) { print(t,visit,"double",null,null); } // visitLiteralElse ... // token type "else" only used by parser, never visited/created directly // visitLiteralEnum ... // token type "enum" only used by parser, never visited/created directly // visitLiteralExtends // token type "extends" only used by parser, never visited/created directly public void visitLiteralFalse(GroovySourceAST t,int visit) { print(t,visit,"false",null,null); } public void visitLiteralFinally(GroovySourceAST t,int visit) { print(t,visit,"finally ",null,null); } public void visitLiteralFloat(GroovySourceAST t,int visit) { print(t,visit,"float",null,null); } public void visitLiteralFor(GroovySourceAST t,int visit) { print(t,visit,"for ",null,null); } public void visitLiteralIf(GroovySourceAST t,int visit) { // slightly strange as subsequent visit is done after closing visit printUpdatingTabLevel(t,visit,"if ("," else ",") "); } // visitLiteralImplements // token type "implements" only used by parser, never visited/created directly // visitLiteralImport // token type "import" only used by parser, never visited/created directly public void visitLiteralIn(GroovySourceAST t, int visit) { print(t,visit," in ",null,null); } public void visitLiteralInstanceof(GroovySourceAST t, int visit) { print(t,visit," instanceof ",null,null); } public void visitLiteralInt(GroovySourceAST t,int visit) { print(t,visit,"int",null,null); } // visitLiteralInterface // token type "interface" only used by parser, never visited/created directly public void visitLiteralLong(GroovySourceAST t,int visit) { print(t,visit,"long",null,null); } public void visitLiteralNative(GroovySourceAST t,int visit) { print(t,visit,"native ",null,null); } public void visitLiteralNew(GroovySourceAST t,int visit) { if (t.childOfType(GroovyTokenTypes.ARRAY_DECLARATOR) == null) { // only print parenthesis if is not of form def x = new int[5] print(t,visit,"new ","(",")"); } else { print(t,visit,"new ",null,null); } } public void visitLiteralNull(GroovySourceAST t, int visit) { print(t,visit,"null",null,null); } // visitLiteralPackage // token type "package" only used by parser, never visited/created directly public void visitLiteralPrivate(GroovySourceAST t,int visit) { print(t,visit,"private ",null,null); } public void visitLiteralProtected(GroovySourceAST t,int visit) { print(t,visit,"protected ",null,null); } public void visitLiteralPublic(GroovySourceAST t,int visit) { print(t,visit,"public ",null,null); } public void visitLiteralReturn(GroovySourceAST t, int visit) { print(t,visit,"return ",null,null); } public void visitLiteralShort(GroovySourceAST t,int visit) { print(t,visit,"short",null,null); } public void visitLiteralStatic(GroovySourceAST t, int visit) { print(t,visit,"static ",null,null); } public void visitLiteralSuper(GroovySourceAST t, int visit) { // only visited when calling super() without parentheses, i.e. "super 99" is equivalent to "super(99)" print(t,visit,"super",null,null); } public void visitLiteralSwitch(GroovySourceAST t, int visit) { if (visit == OPENING_VISIT) { print(t,visit,"switch ("); tabLevel++; } if (visit == SUBSEQUENT_VISIT) { print(t,visit,") {"); } if (visit == CLOSING_VISIT) { tabLevel--; print(t,visit,"}"); } } public void visitLiteralSynchronized(GroovySourceAST t,int visit) { if (t.getNumberOfChildren() > 0) { print(t,visit,"synchronized (",null,") "); } else { print(t,visit,"synchronized ",null,null); } } public void visitLiteralThis(GroovySourceAST t, int visit) { print(t,visit,"this",null,null); } public void visitLiteralThreadsafe(GroovySourceAST t,int visit) { print(t,visit,"threadsafe ",null,null); } public void visitLiteralThrow(GroovySourceAST t, int visit) { print(t,visit,"throw ",null,null); } public void visitLiteralThrows(GroovySourceAST t, int visit) { print(t,visit,"throws ",null,null); } public void visitLiteralTransient(GroovySourceAST t,int visit) { print(t,visit,"transient ",null,null); } public void visitLiteralTrue(GroovySourceAST t,int visit) { print(t,visit,"true",null,null); } public void visitLiteralTry(GroovySourceAST t,int visit) { print(t,visit,"try ",null,null); } public void visitLiteralVoid(GroovySourceAST t,int visit) { print(t,visit,"void",null,null); } public void visitLiteralVolatile(GroovySourceAST t,int visit) { print(t,visit,"volatile ",null,null); } public void visitLiteralWhile(GroovySourceAST t,int visit) { printUpdatingTabLevel(t,visit,"while (",null,") "); } //deprecated // public void visitLiteralWith(GroovySourceAST t,int visit) { // printUpdatingTabLevel(t,visit,"with (",null,") "); // } public void visitLnot(GroovySourceAST t, int visit) { print(t,visit,"!",null,null); } // Note: old closure syntax using LOR is deprecated, and also never creates/visits a LOR node public void visitLor(GroovySourceAST t, int visit) { print(t,visit," || ",null,null); } public void visitLt(GroovySourceAST t, int visit) { print(t,visit," < ",null,null); } public void visitMapConstructor(GroovySourceAST t, int visit) { if (t.getNumberOfChildren() == 0) { print(t,visit,"[:]",null,null); } else { printUpdatingTabLevel(t,visit,"[",null,"]"); } } public void visitMemberPointer(GroovySourceAST t, int visit) { print(t,visit,".&",null,null); } public void visitMethodCall(GroovySourceAST t,int visit) { if ("".equals(t.getText())) { printUpdatingTabLevel(t,visit," "," ",null); } else { printUpdatingTabLevel(t,visit,"("," ",")"); } } public void visitMethodDef(GroovySourceAST t,int visit) { //do nothing } public void visitMinus(GroovySourceAST t,int visit) { print(t,visit," - ",null,null); } public void visitMinusAssign(GroovySourceAST t, int visit) { print(t,visit," -= ",null,null); } // visitMlComment // multi-line comments are not created on the AST currently. public void visitMod(GroovySourceAST t, int visit) { print(t,visit," % ",null,null); } public void visitModifiers(GroovySourceAST t,int visit) { //do nothing } public void visitModAssign(GroovySourceAST t, int visit) { print(t,visit," %= ",null,null); } // visitNls // new lines are used by parser, but are not created on the AST, // they can be implied by the source code line/column information // visitNullTreeLookahead // not used explicitly by parser. public void visitNotEqual(GroovySourceAST t, int visit) { print(t,visit," != ",null,null); } public void visitNumBigDecimal(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitNumBigInt(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitNumDouble(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitNumInt(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitNumFloat(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitNumLong(GroovySourceAST t,int visit) { print(t,visit,t.getText(),null,null); } public void visitObjblock(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { tabLevel++; print(t,visit,"{"); } else { tabLevel--; print(t,visit,"}"); } } // visitOneNl // new lines are used by parser, but are not created on the AST, // they can be implied by the source code line/column information public void visitOptionalDot(GroovySourceAST t,int visit) { print(t,visit,"?.",null,null); } public void visitPackageDef(GroovySourceAST t, int visit) { print(t,visit,"package ",null,null); } public void visitParameterDef(GroovySourceAST t,int visit) { //do nothing } public void visitParameters(GroovySourceAST t,int visit) { if (getParentNode().getType() == GroovyTokenTypes.CLOSABLE_BLOCK) { printUpdatingTabLevel(t,visit,null,","," "); } else { printUpdatingTabLevel(t,visit,"(",", ",") "); } } public void visitPlus(GroovySourceAST t, int visit) { print(t,visit," + ",null,null); } public void visitPlusAssign(GroovySourceAST t, int visit) { print(t,visit," += ",null,null); } public void visitPostDec(GroovySourceAST t, int visit) { print(t,visit,null,null,"--"); } public void visitPostInc(GroovySourceAST t, int visit) { print(t,visit,null,null,"++"); } public void visitQuestion(GroovySourceAST t, int visit) { // ternary operator print(t,visit,"?",":",null); } public void visitRangeExclusive(GroovySourceAST t, int visit) { print(t,visit,"..<",null,null); } public void visitRangeInclusive(GroovySourceAST t, int visit) { print(t,visit,"..",null,null); } // visit rbrack() // token type RBRACK only used inside parser, never visited/created // visit rcurly() // token type RCURLY only used inside parser, never visited/created // visit RegexpCtorEnd // visit RegexpLiteral // visit RegexpSymbol // token types REGEXP_CTOR_END, REGEXP_LITERAL, REGEXP_SYMBOL only used inside lexer public void visitRegexFind(GroovySourceAST t, int visit) { print(t,visit," =~ ",null,null); } public void visitRegexMatch(GroovySourceAST t, int visit) { print(t,visit," ==~ ",null,null); } // visit rparen() // token type RPAREN only used inside parser, never visited/created public void visitSelectSlot(GroovySourceAST t, int visit) { print(t,visit,"@",null,null); } // visit semi() // SEMI only used inside parser, never visited/created (see visitForCondition(), visitForIterator()) // visit ShComment() // never visited/created by parser public void visitSl(GroovySourceAST t, int visit) { print(t,visit," << ",null,null); } public void visitSlAssign(GroovySourceAST t, int visit) { print(t,visit," <<= ",null,null); } public void visitSlist(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { tabLevel++; print(t,visit,"{"); } else { tabLevel--; print(t,visit,"}"); } } // visit SlComment() // never visited/created by parser public void visitSpreadArg(GroovySourceAST t,int visit) { print(t,visit,"*",null,null); } public void visitSpreadDot(GroovySourceAST t,int visit) { print(t,visit,"*.",null,null); } public void visitSpreadMapArg(GroovySourceAST t,int visit) { print(t,visit,"*:",null,null); } public void visitSr(GroovySourceAST t, int visit) { print(t,visit," >> ",null,null); } public void visitSrAssign(GroovySourceAST t, int visit) { print(t,visit," >>= ",null,null); } public void visitStar(GroovySourceAST t,int visit) { print(t,visit,"*",null,null); } public void visitStarAssign(GroovySourceAST t, int visit) { print(t,visit," *= ",null,null); } public void visitStarStar(GroovySourceAST t,int visit) { print(t,visit,"**",null,null); } public void visitStarStarAssign(GroovySourceAST t, int visit) { print(t,visit," **= ",null,null); } public void visitStaticInit(GroovySourceAST t, int visit) { print(t,visit,"static ",null,null); } public void visitStaticImport(GroovySourceAST t,int visit) { print(t,visit,"import static ",null,null); } public void visitStrictfp(GroovySourceAST t,int visit) { print(t,visit,"strictfp ",null,null); } // visitStringch // String characters only used by lexer, never visited/created directly public void visitStringConstructor(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { stringConstructorCounter = 0; print(t,visit,"\""); } if (visit == SUBSEQUENT_VISIT) { // every other subsequent visit use an escaping $ if (stringConstructorCounter % 2 == 0) { print(t,visit,"$"); } stringConstructorCounter++; } if (visit == CLOSING_VISIT) { print(t,visit,"\""); } } public void visitStringLiteral(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { String theString = escape(t.getText()); if (getParentNode().getType() != GroovyTokenTypes.LABELED_ARG && getParentNode().getType() != GroovyTokenTypes.STRING_CONSTRUCTOR) { theString = "\"" + theString + "\""; } print(t,visit,theString); } } private String escape(String literal) { literal = literal.replaceAll("\n","\\\\<>n"); // can't seem to do \n in one go with Java regex literal = literal.replaceAll("<>",""); return literal; } public void visitSuperCtorCall(GroovySourceAST t,int visit) { printUpdatingTabLevel(t,visit,"super("," ",")"); } // visit TripleDot, not used in the AST public void visitType(GroovySourceAST t,int visit) { GroovySourceAST parent = getParentNode(); GroovySourceAST modifiers = parent.childOfType(GroovyTokenTypes.MODIFIERS); // No need to print 'def' if we already have some modifiers if (modifiers == null || modifiers.getNumberOfChildren() == 0) { if (visit == OPENING_VISIT) { if (t.getNumberOfChildren() == 0 && parent.getType() != GroovyTokenTypes.PARAMETER_DEF) { // no need for 'def' if in a parameter list print(t,visit,"def"); } } if (visit == CLOSING_VISIT) { if ( parent.getType() == GroovyTokenTypes.VARIABLE_DEF || parent.getType() == GroovyTokenTypes.METHOD_DEF || parent.getType() == GroovyTokenTypes.ANNOTATION_FIELD_DEF || (parent.getType() == GroovyTokenTypes.PARAMETER_DEF && t.getNumberOfChildren()!=0)) { print(t,visit," "); } } /*if (visit == CLOSING_VISIT) { print(t,visit," "); }*/ } else { if (visit == CLOSING_VISIT) { if (t.getNumberOfChildren() != 0) { print(t,visit," "); } } } } public void visitTypeArgument(GroovySourceAST t, int visit) { // print nothing } public void visitTypeArguments(GroovySourceAST t, int visit) { print(t,visit,"<",", ",">"); } public void visitTypecast(GroovySourceAST t,int visit) { print(t,visit,"(",null,")"); } public void visitTypeLowerBounds(GroovySourceAST t,int visit) { print(t,visit," super "," & ",null); } public void visitTypeParameter(GroovySourceAST t, int visit) { // print nothing } public void visitTypeParameters(GroovySourceAST t, int visit) { print(t,visit,"<",", ",">"); } public void visitTypeUpperBounds(GroovySourceAST t,int visit) { print(t,visit," extends "," & ",null); } public void visitUnaryMinus(GroovySourceAST t, int visit) { print(t,visit,"-",null,null); } public void visitUnaryPlus(GroovySourceAST t, int visit) { print(t,visit,"+",null,null); } // visit Unused "const", "do", "goto" - unsurprisingly these are unused by the AST. public void visitVariableDef(GroovySourceAST t,int visit) { // do nothing } // a.k.a. "variable arity parameter" in the JLS public void visitVariableParameterDef(GroovySourceAST t,int visit) { print(t,visit,null,"... ",null); } // visit Vocab - only used by Lexer public void visitWildcardType(GroovySourceAST t, int visit) { print(t,visit,"?",null,null); } // visit WS - only used by lexer public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { print(t,visit,"<" + tokenNames[t.getType()] + ">"); //out.print("<" + t.getType() + ">"); } else { print(t,visit,""); //out.print(""); } } protected void printUpdatingTabLevel(GroovySourceAST t,int visit,String opening, String subsequent, String closing) { if (visit == OPENING_VISIT && opening != null) { print(t,visit,opening); tabLevel++; } if (visit == SUBSEQUENT_VISIT && subsequent != null) { print(t,visit,subsequent); } if (visit == CLOSING_VISIT && closing != null) { tabLevel--; print(t,visit,closing); } } protected void print(GroovySourceAST t,int visit,String opening, String subsequent, String closing) { if (visit == OPENING_VISIT && opening != null) { print(t,visit,opening); } if (visit == SUBSEQUENT_VISIT && subsequent != null) { print(t,visit,subsequent); } if (visit == CLOSING_VISIT && closing != null) { print(t,visit,closing); } } protected void print(GroovySourceAST t,int visit,String value) { if(visit == OPENING_VISIT) { printNewlineAndIndent(t, visit); } if (visit == CLOSING_VISIT) { printNewlineAndIndent(t, visit); } out.print(value); } protected void printNewlineAndIndent(GroovySourceAST t, int visit) { int currentLine = t.getLine(); if (lastLinePrinted == 0) { lastLinePrinted = currentLine; } if (lastLinePrinted != currentLine) { if (newLines) { if (!(visit == OPENING_VISIT && t.getType() == GroovyTokenTypes.SLIST)) { for (int i=lastLinePrinted;i currentLine) { out.println(); lastLinePrinted = currentLine; } if (visit == OPENING_VISIT || (visit == CLOSING_VISIT && lastLinePrinted > currentLine)) { for (int i=0;i package org.codehaus.groovy.antlr.treewalker.*

      Classes for walking the AST.

      groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/CompositeVisitor.java0000644001501200150120000012351711715031256027477 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.util.*; import org.codehaus.groovy.antlr.GroovySourceAST; /** * A composite of many visitors. Any call to a method from Visitor * will invoke each visitor in turn, and reverse the invocation * order on a closing visit. * i.e. * with the list of visitors = [a,b,c] * composite.visitDefault() would... * call on the opening visit - a.visitDefault() then b.visitDefault() then c.visitDefault() * call on the closing visit - c.visitDefault() then b.visitDefault() then a.visitDefault() * * @author Jeremy Rayner * @version $Revision$ */ public class CompositeVisitor implements Visitor{ final List visitors; final List backToFrontVisitors; private final Stack stack; /** * A composite of the supplied list of antlr AST visitors. * @param visitors a List of implementations of the Visitor interface */ public CompositeVisitor(List visitors) { this.visitors = visitors; this.stack = new Stack(); backToFrontVisitors = new ArrayList(); backToFrontVisitors.addAll(visitors); Collections.reverse(backToFrontVisitors); } private Iterator itr(int visit) { Iterator itr=visitors.iterator(); if (visit == CLOSING_VISIT) { itr = backToFrontVisitors.iterator(); } return itr; } public void setUp() { Iterator itr = visitors.iterator(); while (itr.hasNext()) {((Visitor)itr.next()).setUp();} } public void visitAbstract(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAbstract(t,visit);} } public void visitAnnotation(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotation(t,visit);} } public void visitAnnotations(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotations(t,visit);} } public void visitAnnotationArrayInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationArrayInit(t,visit);} } public void visitAnnotationDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationDef(t,visit);} } public void visitAnnotationFieldDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationFieldDef(t,visit);} } public void visitAnnotationMemberValuePair(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationMemberValuePair(t,visit);} } public void visitArrayDeclarator(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitArrayDeclarator(t,visit);} } public void visitAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAssign(t,visit);} } public void visitAt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAt(t,visit);} } public void visitBand(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBand(t,visit);} } public void visitBandAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBandAssign(t,visit);} } public void visitBigSuffix(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBigSuffix(t,visit);} } public void visitBlock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBlock(t,visit);} } public void visitBnot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBnot(t,visit);} } public void visitBor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBor(t,visit);} } public void visitBorAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBorAssign(t,visit);} } public void visitBsr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBsr(t,visit);} } public void visitBsrAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBsrAssign(t,visit);} } public void visitBxor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBxor(t,visit);} } public void visitBxorAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBxorAssign(t,visit);} } public void visitCaseGroup(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCaseGroup(t,visit);} } public void visitClassDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClassDef(t,visit);} } public void visitClosedBlock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosedBlock(t,visit);} } public void visitClosureList(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosureList(t,visit);} } public void visitClosureOp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosureOp(t,visit);} } public void visitColon(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitColon(t,visit);} } public void visitComma(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitComma(t,visit);} } public void visitCompareTo(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCompareTo(t,visit);} } public void visitCtorCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCtorCall(t,visit);} } public void visitCtorIdent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCtorIdent(t,visit);} } public void visitDec(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDec(t,visit);} } public void visitDigit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDigit(t,visit);} } public void visitDiv(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDiv(t,visit);} } public void visitDivAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDivAssign(t,visit);} } public void visitDollar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDollar(t,visit);} } public void visitDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDot(t,visit);} } public void visitDynamicMember(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDynamicMember(t,visit);} } public void visitElist(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitElist(t,visit);} } public void visitEmptyStat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEmptyStat(t,visit);} } public void visitEnumConstantDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEnumConstantDef(t,visit);} } public void visitEnumDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEnumDef(t,visit);} } public void visitEof(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEof(t,visit);} } public void visitEqual(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEqual(t,visit);} } public void visitEsc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEsc(t,visit);} } public void visitExponent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExponent(t,visit);} } public void visitExpr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExpr(t,visit);} } public void visitExtendsClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExtendsClause(t,visit);} } public void visitFinal(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitFinal(t,visit);} } public void visitFloatSuffix(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitFloatSuffix(t,visit);} } public void visitForCondition(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForCondition(t,visit);} } public void visitForEachClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForEachClause(t,visit);} } public void visitForInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForInit(t,visit);} } public void visitForInIterable(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForInIterable(t,visit);} } public void visitForIterator(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForIterator(t,visit);} } public void visitGe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitGe(t,visit);} } public void visitGt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitGt(t,visit);} } public void visitHexDigit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitHexDigit(t,visit);} } public void visitIdent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitIdent(t,visit);} } public void visitImplementsClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImplementsClause(t,visit);} } public void visitImplicitParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImplicitParameters(t,visit);} } public void visitImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImport(t,visit);} } public void visitInc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInc(t,visit);} } public void visitIndexOp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitIndexOp(t,visit);} } public void visitInstanceInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInstanceInit(t,visit);} } public void visitInterfaceDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInterfaceDef(t,visit);} } public void visitLabeledArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLabeledArg(t,visit);} } public void visitLabeledStat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLabeledStat(t,visit);} } public void visitLand(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLand(t,visit);} } public void visitLbrack(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLbrack(t,visit);} } public void visitLcurly(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLcurly(t,visit);} } public void visitLe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLe(t,visit);} } public void visitLetter(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLetter(t,visit);} } public void visitListConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitListConstructor(t,visit);} } public void visitLiteralAs(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralAs(t,visit);} } public void visitLiteralAssert(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralAssert(t,visit);} } public void visitLiteralBoolean(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralBoolean(t,visit);} } public void visitLiteralBreak(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralBreak(t,visit);} } public void visitLiteralByte(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralByte(t,visit);} } public void visitLiteralCase(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralCase(t,visit);} } public void visitLiteralCatch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralCatch(t,visit);} } public void visitLiteralChar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralChar(t,visit);} } public void visitLiteralClass(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralClass(t,visit);} } public void visitLiteralContinue(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralContinue(t,visit);} } public void visitLiteralDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDef(t,visit);} } public void visitLiteralDefault(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDefault(t,visit);} } public void visitLiteralDouble(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDouble(t,visit);} } public void visitLiteralElse(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralElse(t,visit);} } public void visitLiteralEnum(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralEnum(t,visit);} } public void visitLiteralExtends(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralExtends(t,visit);} } public void visitLiteralFalse(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFalse(t,visit);} } public void visitLiteralFinally(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFinally(t,visit);} } public void visitLiteralFloat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFloat(t,visit);} } public void visitLiteralFor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFor(t,visit);} } public void visitLiteralIf(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralIf(t,visit);} } public void visitLiteralImplements(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralImplements(t,visit);} } public void visitLiteralImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralImport(t,visit);} } public void visitLiteralIn(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralIn(t,visit);} } public void visitLiteralInstanceof(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInstanceof(t,visit);} } public void visitLiteralInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInt(t,visit);} } public void visitLiteralInterface(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInterface(t,visit);} } public void visitLiteralLong(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralLong(t,visit);} } public void visitLiteralNative(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNative(t,visit);} } public void visitLiteralNew(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNew(t,visit);} } public void visitLiteralNull(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNull(t,visit);} } public void visitLiteralPackage(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPackage(t,visit);} } public void visitLiteralPrivate(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPrivate(t,visit);} } public void visitLiteralProtected(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralProtected(t,visit);} } public void visitLiteralPublic(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPublic(t,visit);} } public void visitLiteralReturn(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralReturn(t,visit);} } public void visitLiteralShort(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralShort(t,visit);} } public void visitLiteralStatic(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralStatic(t,visit);} } public void visitLiteralSuper(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSuper(t,visit);} } public void visitLiteralSwitch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSwitch(t,visit);} } public void visitLiteralSynchronized(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSynchronized(t,visit);} } public void visitLiteralThis(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThis(t,visit);} } public void visitLiteralThreadsafe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThreadsafe(t,visit);} } public void visitLiteralThrow(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThrow(t,visit);} } public void visitLiteralThrows(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThrows(t,visit);} } public void visitLiteralTransient(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTransient(t,visit);} } public void visitLiteralTrue(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTrue(t,visit);} } public void visitLiteralTry(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTry(t,visit);} } public void visitLiteralVoid(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralVoid(t,visit);} } public void visitLiteralVolatile(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralVolatile(t,visit);} } public void visitLiteralWhile(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralWhile(t,visit);} } public void visitLnot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLnot(t,visit);} } public void visitLor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLor(t,visit);} } public void visitLparen(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLparen(t,visit);} } public void visitLt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLt(t,visit);} } public void visitMapConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMapConstructor(t,visit);} } public void visitMemberPointer(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMemberPointer(t,visit);} } public void visitMethodCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMethodCall(t,visit);} } public void visitMethodDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMethodDef(t,visit);} } public void visitMinus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMinus(t,visit);} } public void visitMinusAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMinusAssign(t,visit);} } public void visitMlComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMlComment(t,visit);} } public void visitMod(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMod(t,visit);} } public void visitModifiers(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitModifiers(t,visit);} } public void visitModAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitModAssign(t,visit);} } public void visitNls(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNls(t,visit);} } public void visitNotEqual(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNotEqual(t,visit);} } public void visitNullTreeLookahead(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNullTreeLookahead(t,visit);} } public void visitNumBigDecimal(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumBigDecimal(t,visit);} } public void visitNumBigInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumBigInt(t,visit);} } public void visitNumDouble(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumDouble(t,visit);} } public void visitNumFloat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumFloat(t,visit);} } public void visitNumInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumInt(t,visit);} } public void visitNumLong(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumLong(t,visit);} } public void visitObjblock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitObjblock(t,visit);} } public void visitOneNl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitOneNl(t,visit);} } public void visitOptionalDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitOptionalDot(t,visit);} } public void visitPackageDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPackageDef(t,visit);} } public void visitParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitParameters(t,visit);} } public void visitParameterDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitParameterDef(t,visit);} } public void visitPlus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPlus(t,visit);} } public void visitPlusAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPlusAssign(t,visit);} } public void visitPostDec(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPostDec(t,visit);} } public void visitPostInc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPostInc(t,visit);} } public void visitQuestion(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitQuestion(t,visit);} } public void visitRangeExclusive(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRangeExclusive(t,visit);} } public void visitRangeInclusive(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRangeInclusive(t,visit);} } public void visitRbrack(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRbrack(t,visit);} } public void visitRcurly(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRcurly(t,visit);} } public void visitRegexpCtorEnd(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpCtorEnd(t,visit);} } public void visitRegexpLiteral(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpLiteral(t,visit);} } public void visitRegexpSymbol(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpSymbol(t,visit);} } public void visitRegexFind(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexFind(t,visit);} } public void visitRegexMatch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexMatch(t,visit);} } public void visitRparen(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRparen(t,visit);} } public void visitSelectSlot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSelectSlot(t,visit);} } public void visitSemi(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSemi(t,visit);} } public void visitShComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitShComment(t,visit);} } public void visitSl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSl(t,visit);} } public void visitSlist(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlist(t,visit);} } public void visitSlAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlAssign(t,visit);} } public void visitSlComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlComment(t,visit);} } public void visitSpreadArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadArg(t,visit);} } public void visitSpreadDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadDot(t,visit);} } public void visitSpreadMapArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadMapArg(t,visit);} } public void visitSr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSr(t,visit);} } public void visitSrAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSrAssign(t,visit);} } public void visitStar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStar(t,visit);} } public void visitStarAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarAssign(t,visit);} } public void visitStarStar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarStar(t,visit);} } public void visitStarStarAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarStarAssign(t,visit);} } public void visitStaticImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStaticImport(t,visit);} } public void visitStaticInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStaticInit(t,visit);} } public void visitStrictfp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStrictfp(t,visit);} } public void visitStringCh(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCh(t,visit);} } public void visitStringConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringConstructor(t,visit);} } public void visitStringCtorEnd(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorEnd(t,visit);} } public void visitStringCtorMiddle(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorMiddle(t,visit);} } public void visitStringCtorStart(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorStart(t,visit);} } public void visitStringLiteral(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringLiteral(t,visit);} } public void visitStringNl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringNl(t,visit);} } public void visitSuperCtorCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSuperCtorCall(t,visit);} } public void visitTripleDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTripleDot(t,visit);} } public void visitType(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitType(t,visit);} } public void visitTypecast(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypecast(t,visit);} } public void visitTypeArgument(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeArgument(t,visit);} } public void visitTypeArguments(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeArguments(t,visit);} } public void visitTypeLowerBounds(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeLowerBounds(t,visit);} } public void visitTypeParameter(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeParameter(t,visit);} } public void visitTypeParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeParameters(t,visit);} } public void visitTypeUpperBounds(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeUpperBounds(t,visit);} } public void visitUnaryMinus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnaryMinus(t,visit);} } public void visitUnaryPlus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnaryPlus(t,visit);} } public void visitUnusedConst(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedConst(t,visit);} } public void visitUnusedDo(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedDo(t,visit);} } public void visitUnusedGoto(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedGoto(t,visit);} } public void visitVariableDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVariableDef(t,visit);} } public void visitVariableParameterDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVariableParameterDef(t,visit);} } public void visitVocab(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVocab(t,visit);} } public void visitWildcardType(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitWildcardType(t,visit);} } public void visitWs(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitWs(t,visit);} } public void visitDefault(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDefault(t,visit);} } public void tearDown() { Iterator itr = backToFrontVisitors.iterator(); while (itr.hasNext()) {((Visitor)itr.next()).tearDown();} } public void push(GroovySourceAST t) { Iterator itr = visitors.iterator(); while (itr.hasNext()) {((Visitor)itr.next()).push(t);} } public GroovySourceAST pop() { GroovySourceAST lastNodePopped = null; Iterator itr = backToFrontVisitors.iterator(); while (itr.hasNext()) {lastNodePopped = (GroovySourceAST) ((Visitor)itr.next()).pop();} return lastNodePopped; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/SourceCodeTraversal.java0000644001501200150120000002676411627206700030102 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.util.ArrayList; import java.util.Collections; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; /** * A treewalker for the antlr generated AST that attempts to visit the * AST nodes in the order needed to generate valid groovy source code. * * @author Jeremy Rayner */ public class SourceCodeTraversal extends TraversalHelper { /** * Constructs a treewalker for the antlr generated AST that attempts to visit the * AST nodes in the order needed to generate valid groovy source code. * @param visitor the visitor implementation to call for each AST node. */ public SourceCodeTraversal(Visitor visitor) { super(visitor); } /** * gather, sort and process all unvisited nodes * @param t the AST to process */ public void setUp(GroovySourceAST t) { super.setUp(t); // gather and sort all unvisited AST nodes unvisitedNodes = new ArrayList(); traverse(t); Collections.sort(unvisitedNodes); } /** * traverse an AST node * @param t the AST node to traverse */ private void traverse(GroovySourceAST t) { if (t == null) { return; } if (unvisitedNodes != null) { unvisitedNodes.add(t); } GroovySourceAST child = (GroovySourceAST)t.getFirstChild(); if (child != null) { traverse(child); } GroovySourceAST sibling = (GroovySourceAST)t.getNextSibling(); if (sibling != null) { traverse(sibling); } } protected void accept(GroovySourceAST currentNode) { if (currentNode != null && unvisitedNodes != null && unvisitedNodes.size() > 0) { GroovySourceAST t = currentNode; if (!(unvisitedNodes.contains(currentNode))) { return; } push(t); switch (t.getType()) { case GroovyTokenTypes.QUESTION: // expr?foo:bar accept_FirstChild_v_SecondChild_v_ThirdChild_v(t); break; case GroovyTokenTypes.CASE_GROUP: // case GroovyTokenTypes.LITERAL_instanceof: // foo instanceof MyType accept_FirstChild_v_SecondChildsChildren_v(t); break; case GroovyTokenTypes.ANNOTATION: accept_v_FirstChild_2ndv_SecondChild_v___LastChild_v(t); break; case GroovyTokenTypes.CLOSURE_LIST: // (a=1; a<10; a++) case GroovyTokenTypes.ELIST: // a,b,c case GroovyTokenTypes.PARAMETERS: // a,b,c case GroovyTokenTypes.TYPE_ARGUMENTS: // case GroovyTokenTypes.STRING_CONSTRUCTOR: // "foo${bar}wibble" case GroovyTokenTypes.TYPE_PARAMETER: // class Foo case GroovyTokenTypes.TYPE_PARAMETERS: // class Foo case GroovyTokenTypes.TYPE_UPPER_BOUNDS: // class Foo accept_v_FirstChild_v_SecondChild_v___LastChild_v(t); // todo : confirm that TYPE_LOWER_BOUNDS does not have multiple children break; case GroovyTokenTypes.VARIABLE_PARAMETER_DEF: // void f(String ... others) {} accept_v_FirstChild_SecondChild_v_ThirdChild_v(t); break; case GroovyTokenTypes.INDEX_OP: //accept_FirstChild_v_SecondChild_v(t); accept_SecondChild_v_ThirdChild_v(t); break; case GroovyTokenTypes.ENUM_CONSTANT_DEF: // enum Foo(THESE,ARE,THEY) case GroovyTokenTypes.EXPR: case GroovyTokenTypes.IMPORT: case GroovyTokenTypes.STATIC_IMPORT: case GroovyTokenTypes.VARIABLE_DEF: case GroovyTokenTypes.METHOD_DEF: case GroovyTokenTypes.OBJBLOCK: //class Foo {def bar()} <-- this block case GroovyTokenTypes.PARAMETER_DEF: // void f(String me) {} case GroovyTokenTypes.SLIST: // list of expressions, variable defs etc accept_v_AllChildren_v(t); break; case GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR: // @Blue(foo=123) case GroovyTokenTypes.ASSIGN: // a = b case GroovyTokenTypes.BAND_ASSIGN: // a &= b case GroovyTokenTypes.BOR_ASSIGN: // a |= b case GroovyTokenTypes.BSR_ASSIGN: // a >>>= b case GroovyTokenTypes.BXOR_ASSIGN: // a ^= b case GroovyTokenTypes.COMPARE_TO: // a <=> b case GroovyTokenTypes.DIV_ASSIGN: // a /= b case GroovyTokenTypes.EQUAL: // a == b case GroovyTokenTypes.MINUS_ASSIGN: // a -= b case GroovyTokenTypes.MOD_ASSIGN: // a %= b case GroovyTokenTypes.NOT_EQUAL: // a != b case GroovyTokenTypes.PLUS_ASSIGN: // a += b case GroovyTokenTypes.REGEX_FIND: // a =~ b case GroovyTokenTypes.REGEX_MATCH: // a ==~ b case GroovyTokenTypes.SL_ASSIGN: // a <<= b case GroovyTokenTypes.SR_ASSIGN: // a >>= b case GroovyTokenTypes.STAR_ASSIGN: // a *= b case GroovyTokenTypes.STAR_STAR_ASSIGN: // x **= 3 if (t.childAt(1) != null) { accept_FirstChild_v_RestOfTheChildren(t); } else { accept_v_FirstChild_v_RestOfTheChildren(t); } break; case GroovyTokenTypes.ANNOTATION_FIELD_DEF: // @interface Foo{ int bar()... accept_FirstSecondAndThirdChild_v_v_ForthChild(t); break; case GroovyTokenTypes.ANNOTATION_DEF: // @interface Foo... case GroovyTokenTypes.BAND: // 1 & 2 case GroovyTokenTypes.BOR: // 1 | 2 case GroovyTokenTypes.BSR: // 1 >>> 2 case GroovyTokenTypes.BXOR: // 1 ^ 2 case GroovyTokenTypes.CLASS_DEF: // class Foo... case GroovyTokenTypes.CTOR_IDENT: // private Foo() {... case GroovyTokenTypes.DIV: // 3/4 case GroovyTokenTypes.DOT: // foo.bar case GroovyTokenTypes.ENUM_DEF: // enum Foo... case GroovyTokenTypes.GE: // a >= b case GroovyTokenTypes.GT: // a > b case GroovyTokenTypes.INTERFACE_DEF: // interface Foo... case GroovyTokenTypes.LABELED_ARG: // myMethod(name:"Jez") case GroovyTokenTypes.LABELED_STAT: // foo:x=1 case GroovyTokenTypes.LAND: // true && false case GroovyTokenTypes.LE: // a <= b case GroovyTokenTypes.LITERAL_as: // foo as Bar case GroovyTokenTypes.LITERAL_in: // if (i in myList) ... case GroovyTokenTypes.LOR: // true && false case GroovyTokenTypes.LT: // a < b case GroovyTokenTypes.MEMBER_POINTER: // this.&foo() case GroovyTokenTypes.MOD: // 4 % 3 case GroovyTokenTypes.MINUS: // 1 - 1 case GroovyTokenTypes.OPTIONAL_DOT: // foo?.bar case GroovyTokenTypes.PACKAGE_DEF: case GroovyTokenTypes.PLUS: // 1 + 1 case GroovyTokenTypes.RANGE_EXCLUSIVE: // [1..<10] case GroovyTokenTypes.RANGE_INCLUSIVE: // [1..10] case GroovyTokenTypes.SL: // a << b case GroovyTokenTypes.SPREAD_DOT: // foo*.bar case GroovyTokenTypes.SR: // a >> b case GroovyTokenTypes.STAR: // a * b or import foo.* case GroovyTokenTypes.STAR_STAR: // x ** 3 accept_FirstChild_v_RestOfTheChildren(t); break; case GroovyTokenTypes.CTOR_CALL: case GroovyTokenTypes.METHOD_CALL: if (t.getNumberOfChildren() == 2 && t.childAt(1) != null && t.childAt(1).getType() == GroovyTokenTypes.CLOSABLE_BLOCK) { // myMethod {... accept_FirstChild_v_SecondChild(t); } else { GroovySourceAST lastChild = t.childAt(t.getNumberOfChildren() -1); if (lastChild != null && lastChild.getType() == GroovyTokenTypes.CLOSABLE_BLOCK) { // myMethod(a,b) {... accept_FirstChild_v_RestOfTheChildren_v_LastChild(t); } else { // myMethod(a,b) accept_FirstChild_v_RestOfTheChildren_v(t); } } break; case GroovyTokenTypes.LITERAL_while: //deprecated case GroovyTokenTypes.LITERAL_with: case GroovyTokenTypes.TYPECAST: // (String)itr.next() accept_v_FirstChildsFirstChild_v_RestOfTheChildren(t); break; case GroovyTokenTypes.LITERAL_if: // if (grandchild) {child1} else {child2} ... accept_v_FirstChildsFirstChild_v_Child2_Child3_v_Child4_v___v_LastChild(t); break; case GroovyTokenTypes.CLOSABLE_BLOCK: // [1,2,3].each {foo(it)} <-- Closure if (t.childAt(0) != null && t.childAt(0).getType() == GroovyTokenTypes.IMPLICIT_PARAMETERS) { accept_v_AllChildren_v(t); } else { accept_v_FirstChild_v_RestOfTheChildren_v(t); } break; case GroovyTokenTypes.FOR_IN_ITERABLE: case GroovyTokenTypes.LITERAL_for: case GroovyTokenTypes.LITERAL_new: case GroovyTokenTypes.LITERAL_switch: accept_v_FirstChild_v_RestOfTheChildren_v(t); break; case GroovyTokenTypes.ANNOTATIONS: // just like modifiers but for package/enum declarations case GroovyTokenTypes.LITERAL_assert: case GroovyTokenTypes.LITERAL_catch: case GroovyTokenTypes.LITERAL_synchronized: case GroovyTokenTypes.LITERAL_try: case GroovyTokenTypes.MODIFIERS: accept_v_FirstChild_v_RestOfTheChildren(t); break; case GroovyTokenTypes.WILDCARD_TYPE: accept_v_Siblings_v(t); break; default: accept_v_FirstChild_v(t); break; } pop(); } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/NodePrinter.java0000644001501200150120000000316011627206700026375 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.io.PrintStream; import org.codehaus.groovy.antlr.GroovySourceAST; /** * A simple antlr AST visitor that outputs the tokenName of each node in a pseudo xml style. * * @author Jeremy Rayner * @version $Revision$ */ public class NodePrinter extends VisitorAdapter { private String[] tokenNames; private PrintStream out; /** * A visitor that prints a pseudo xml output to the supplied PrintStream * @param out supplied PrintStream to output nodes to * @param tokenNames an array of token names to use */ public NodePrinter(PrintStream out,String[] tokenNames) { this.tokenNames = tokenNames; this.out = out; } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { out.print("<"+ tokenNames[t.getType()] + ">"); } else { out.print(""); } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/VisitorAdapter.java0000644001501200150120000004632211715031256027113 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import org.codehaus.groovy.antlr.GroovySourceAST; /** * A default implementation of all visitor methods. * If you extend this class, any un-overridden visit methods will * call visitDefault. * * @author Jeremy Rayner * @version $Revision$ */ public class VisitorAdapter implements Visitor { public void setUp() {} public void visitAbstract(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotation(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotations(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotationArrayInit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotationDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotationFieldDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAnnotationMemberValuePair(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitArrayDeclarator(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitAt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBand(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBandAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBigSuffix(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBlock(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBnot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBorAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBsr(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBsrAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBxor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitBxorAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitCaseGroup(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitClassDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitClosedBlock(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitClosureOp(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitClosureList(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitColon(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitComma(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitCompareTo(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitCtorCall(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitCtorIdent(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDec(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDigit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDiv(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDivAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDollar(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDynamicMember(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitElist(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEmptyStat(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEnumConstantDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEnumDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEof(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEqual(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitEsc(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitExponent(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitExpr(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitExtendsClause(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitFinal(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitFloatSuffix(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitForCondition(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitForEachClause(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitForInit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitForInIterable(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitForIterator(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitGe(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitGt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitHexDigit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitIdent(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitImplementsClause(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitImplicitParameters(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitImport(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitInc(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitIndexOp(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitInstanceInit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitInterfaceDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLabeledArg(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLabeledStat(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLand(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLbrack(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLcurly(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLe(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLetter(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitListConstructor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralAs(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralAssert(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralBoolean(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralBreak(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralByte(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralCase(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralCatch(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralChar(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralClass(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralContinue(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralDefault(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralDouble(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralElse(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralEnum(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralExtends(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralFalse(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralFinally(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralFloat(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralFor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralIf(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralImplements(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralImport(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralIn(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralInstanceof(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralInt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralInterface(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralLong(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralNative(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralNew(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralNull(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralPackage(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralPrivate(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralProtected(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralPublic(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralReturn(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralShort(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralStatic(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralSuper(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralSwitch(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralSynchronized(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralThis(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralThreadsafe(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralThrow(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralThrows(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralTransient(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralTrue(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralTry(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralVoid(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralVolatile(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLiteralWhile(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLnot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLparen(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitLt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMapConstructor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMemberPointer(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMethodCall(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMethodDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMinus(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMinusAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMlComment(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitMod(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitModifiers(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitModAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNls(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNotEqual(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNullTreeLookahead(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumBigDecimal(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumBigInt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumDouble(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumFloat(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumInt(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitNumLong(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitObjblock(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitOneNl(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitOptionalDot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitPackageDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitParameters(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitParameterDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitPlus(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitPlusAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitPostDec(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitPostInc(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitQuestion(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRangeExclusive(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRangeInclusive(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRbrack(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRcurly(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRegexpCtorEnd(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRegexpLiteral(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRegexpSymbol(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRegexFind(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRegexMatch(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitRparen(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSelectSlot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSemi(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitShComment(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSl(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSlist(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSlAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSlComment(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSpreadArg(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSpreadDot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSpreadMapArg(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSr(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSrAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStar(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStarAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStarStar(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStarStarAssign(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStaticImport(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStaticInit(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStrictfp(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringCh(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringConstructor(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringCtorEnd(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringCtorMiddle(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringCtorStart(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringLiteral(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitStringNl(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitSuperCtorCall(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTripleDot(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitType(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypecast(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeArgument(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeArguments(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeLowerBounds(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeParameter(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeParameters(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitTypeUpperBounds(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitUnaryMinus(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitUnaryPlus(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitUnusedConst(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitUnusedDo(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitUnusedGoto(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitVariableDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitVariableParameterDef(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitVocab(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitWildcardType(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitWs(GroovySourceAST t,int visit) {visitDefault(t,visit);} public void visitDefault(GroovySourceAST t,int visit) {} public void tearDown() {} public void push(GroovySourceAST t) {} public GroovySourceAST pop() {return null;} } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/PreOrderTraversal.java0000644001501200150120000000254211627206700027555 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import org.codehaus.groovy.antlr.GroovySourceAST; /** * A simple preorder traversal over the supplied antlr AST. * * @author Jeremy Rayner * @version $Revision$ */ public class PreOrderTraversal extends TraversalHelper { /** * A simple preorder traversal over the supplied antlr AST. * @param visitor the Visitor to call for each node visited */ public PreOrderTraversal(Visitor visitor) { super(visitor); } public void accept(GroovySourceAST currentNode) { push(currentNode); openingVisit(currentNode); acceptChildren(currentNode); closingVisit(currentNode); pop(); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/Visitor.java0000644001501200150120000003170211715031256025606 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import org.codehaus.groovy.antlr.GroovySourceAST; /** * An interface for visiting a GroovySourceAST node. * * @author Jeremy Rayner * @version $Revision$ */ public interface Visitor { int OPENING_VISIT = 1; int SECOND_VISIT = 2; // only used on rare occasions, e.g. the '(' in this snippet... @Foo ( a=1, b=2, c=3) int SUBSEQUENT_VISIT = 3; int CLOSING_VISIT = 4; void setUp(); void visitAbstract(GroovySourceAST t, int visit); void visitAnnotation(GroovySourceAST t, int visit); void visitAnnotations(GroovySourceAST t, int visit); void visitAnnotationArrayInit(GroovySourceAST t, int visit); void visitAnnotationDef(GroovySourceAST t, int visit); void visitAnnotationFieldDef(GroovySourceAST t, int visit); void visitAnnotationMemberValuePair(GroovySourceAST t, int visit); void visitArrayDeclarator(GroovySourceAST t, int visit); void visitAssign(GroovySourceAST t, int visit); void visitAt(GroovySourceAST t, int visit); void visitBand(GroovySourceAST t, int visit); void visitBandAssign(GroovySourceAST t, int visit); void visitBigSuffix(GroovySourceAST t, int visit); void visitBlock(GroovySourceAST t, int visit); void visitBnot(GroovySourceAST t, int visit); void visitBor(GroovySourceAST t, int visit); void visitBorAssign(GroovySourceAST t, int visit); void visitBsr(GroovySourceAST t, int visit); void visitBsrAssign(GroovySourceAST t, int visit); void visitBxor(GroovySourceAST t, int visit); void visitBxorAssign(GroovySourceAST t, int visit); void visitCaseGroup(GroovySourceAST t, int visit); void visitClassDef(GroovySourceAST t, int visit); void visitClosedBlock(GroovySourceAST t, int visit); void visitClosureList(GroovySourceAST t, int visit); void visitClosureOp(GroovySourceAST t, int visit); void visitColon(GroovySourceAST t, int visit); void visitComma(GroovySourceAST t, int visit); void visitCompareTo(GroovySourceAST t, int visit); void visitCtorCall(GroovySourceAST t, int visit); void visitCtorIdent(GroovySourceAST t, int visit); void visitDec(GroovySourceAST t, int visit); void visitDigit(GroovySourceAST t, int visit); void visitDiv(GroovySourceAST t, int visit); void visitDivAssign(GroovySourceAST t, int visit); void visitDollar(GroovySourceAST t, int visit); void visitDot(GroovySourceAST t, int visit); void visitDynamicMember(GroovySourceAST t, int visit); void visitElist(GroovySourceAST t, int visit); void visitEmptyStat(GroovySourceAST t, int visit); void visitEnumConstantDef(GroovySourceAST t, int visit); void visitEnumDef(GroovySourceAST t, int visit); void visitEof(GroovySourceAST t, int visit); void visitEqual(GroovySourceAST t, int visit); void visitEsc(GroovySourceAST t, int visit); void visitExponent(GroovySourceAST t, int visit); void visitExpr(GroovySourceAST t, int visit); void visitExtendsClause(GroovySourceAST t, int visit); void visitFinal(GroovySourceAST t, int visit); void visitFloatSuffix(GroovySourceAST t, int visit); void visitForCondition(GroovySourceAST t, int visit); void visitForEachClause(GroovySourceAST t, int visit); void visitForInit(GroovySourceAST t, int visit); void visitForInIterable(GroovySourceAST t, int visit); void visitForIterator(GroovySourceAST t, int visit); void visitGe(GroovySourceAST t, int visit); void visitGt(GroovySourceAST t, int visit); void visitHexDigit(GroovySourceAST t, int visit); void visitIdent(GroovySourceAST t, int visit); void visitImplementsClause(GroovySourceAST t, int visit); void visitImplicitParameters(GroovySourceAST t, int visit); void visitImport(GroovySourceAST t, int visit); void visitInc(GroovySourceAST t, int visit); void visitIndexOp(GroovySourceAST t, int visit); void visitInstanceInit(GroovySourceAST t, int visit); void visitInterfaceDef(GroovySourceAST t, int visit); void visitLabeledArg(GroovySourceAST t, int visit); void visitLabeledStat(GroovySourceAST t, int visit); void visitLand(GroovySourceAST t, int visit); void visitLbrack(GroovySourceAST t, int visit); void visitLcurly(GroovySourceAST t, int visit); void visitLe(GroovySourceAST t, int visit); void visitLetter(GroovySourceAST t, int visit); void visitListConstructor(GroovySourceAST t, int visit); void visitLiteralAs(GroovySourceAST t, int visit); void visitLiteralAssert(GroovySourceAST t, int visit); void visitLiteralBoolean(GroovySourceAST t, int visit); void visitLiteralBreak(GroovySourceAST t, int visit); void visitLiteralByte(GroovySourceAST t, int visit); void visitLiteralCase(GroovySourceAST t, int visit); void visitLiteralCatch(GroovySourceAST t, int visit); void visitLiteralChar(GroovySourceAST t, int visit); void visitLiteralClass(GroovySourceAST t, int visit); void visitLiteralContinue(GroovySourceAST t, int visit); void visitLiteralDef(GroovySourceAST t, int visit); void visitLiteralDefault(GroovySourceAST t, int visit); void visitLiteralDouble(GroovySourceAST t, int visit); void visitLiteralElse(GroovySourceAST t, int visit); void visitLiteralEnum(GroovySourceAST t, int visit); void visitLiteralExtends(GroovySourceAST t, int visit); void visitLiteralFalse(GroovySourceAST t, int visit); void visitLiteralFinally(GroovySourceAST t, int visit); void visitLiteralFloat(GroovySourceAST t, int visit); void visitLiteralFor(GroovySourceAST t, int visit); void visitLiteralIf(GroovySourceAST t, int visit); void visitLiteralImplements(GroovySourceAST t, int visit); void visitLiteralImport(GroovySourceAST t, int visit); void visitLiteralIn(GroovySourceAST t, int visit); void visitLiteralInstanceof(GroovySourceAST t, int visit); void visitLiteralInt(GroovySourceAST t, int visit); void visitLiteralInterface(GroovySourceAST t, int visit); void visitLiteralLong(GroovySourceAST t, int visit); void visitLiteralNative(GroovySourceAST t, int visit); void visitLiteralNew(GroovySourceAST t, int visit); void visitLiteralNull(GroovySourceAST t, int visit); void visitLiteralPackage(GroovySourceAST t, int visit); void visitLiteralPrivate(GroovySourceAST t, int visit); void visitLiteralProtected(GroovySourceAST t, int visit); void visitLiteralPublic(GroovySourceAST t, int visit); void visitLiteralReturn(GroovySourceAST t, int visit); void visitLiteralShort(GroovySourceAST t, int visit); void visitLiteralStatic(GroovySourceAST t, int visit); void visitLiteralSuper(GroovySourceAST t, int visit); void visitLiteralSwitch(GroovySourceAST t, int visit); void visitLiteralSynchronized(GroovySourceAST t, int visit); void visitLiteralThis(GroovySourceAST t, int visit); void visitLiteralThreadsafe(GroovySourceAST t, int visit); void visitLiteralThrow(GroovySourceAST t, int visit); void visitLiteralThrows(GroovySourceAST t, int visit); void visitLiteralTransient(GroovySourceAST t, int visit); void visitLiteralTrue(GroovySourceAST t, int visit); void visitLiteralTry(GroovySourceAST t, int visit); void visitLiteralVoid(GroovySourceAST t, int visit); void visitLiteralVolatile(GroovySourceAST t, int visit); void visitLiteralWhile(GroovySourceAST t, int visit); void visitLnot(GroovySourceAST t, int visit); void visitLor(GroovySourceAST t, int visit); void visitLparen(GroovySourceAST t, int visit); void visitLt(GroovySourceAST t, int visit); void visitMapConstructor(GroovySourceAST t, int visit); void visitMemberPointer(GroovySourceAST t, int visit); void visitMethodCall(GroovySourceAST t, int visit); void visitMethodDef(GroovySourceAST t, int visit); void visitMinus(GroovySourceAST t, int visit); void visitMinusAssign(GroovySourceAST t, int visit); void visitMlComment(GroovySourceAST t, int visit); void visitMod(GroovySourceAST t, int visit); void visitModifiers(GroovySourceAST t, int visit); void visitModAssign(GroovySourceAST t, int visit); void visitNls(GroovySourceAST t, int visit); void visitNotEqual(GroovySourceAST t, int visit); void visitNullTreeLookahead(GroovySourceAST t, int visit); void visitNumBigDecimal(GroovySourceAST t, int visit); void visitNumBigInt(GroovySourceAST t, int visit); void visitNumDouble(GroovySourceAST t, int visit); void visitNumFloat(GroovySourceAST t, int visit); void visitNumInt(GroovySourceAST t, int visit); void visitNumLong(GroovySourceAST t, int visit); void visitObjblock(GroovySourceAST t, int visit); void visitOneNl(GroovySourceAST t, int visit); void visitOptionalDot(GroovySourceAST t, int visit); void visitPackageDef(GroovySourceAST t, int visit); void visitParameters(GroovySourceAST t, int visit); void visitParameterDef(GroovySourceAST t, int visit); void visitPlus(GroovySourceAST t, int visit); void visitPlusAssign(GroovySourceAST t, int visit); void visitPostDec(GroovySourceAST t, int visit); void visitPostInc(GroovySourceAST t, int visit); void visitQuestion(GroovySourceAST t, int visit); void visitRangeExclusive(GroovySourceAST t, int visit); void visitRangeInclusive(GroovySourceAST t, int visit); void visitRbrack(GroovySourceAST t, int visit); void visitRcurly(GroovySourceAST t, int visit); void visitRegexpCtorEnd(GroovySourceAST t, int visit); void visitRegexpLiteral(GroovySourceAST t, int visit); void visitRegexpSymbol(GroovySourceAST t, int visit); void visitRegexFind(GroovySourceAST t, int visit); void visitRegexMatch(GroovySourceAST t, int visit); void visitRparen(GroovySourceAST t, int visit); void visitSelectSlot(GroovySourceAST t, int visit); void visitSemi(GroovySourceAST t, int visit); void visitShComment(GroovySourceAST t, int visit); void visitSl(GroovySourceAST t, int visit); void visitSlist(GroovySourceAST t, int visit); void visitSlAssign(GroovySourceAST t, int visit); void visitSlComment(GroovySourceAST t, int visit); void visitSpreadArg(GroovySourceAST t, int visit); void visitSpreadDot(GroovySourceAST t, int visit); void visitSpreadMapArg(GroovySourceAST t, int visit); void visitSr(GroovySourceAST t, int visit); void visitSrAssign(GroovySourceAST t, int visit); void visitStar(GroovySourceAST t, int visit); void visitStarAssign(GroovySourceAST t, int visit); void visitStarStar(GroovySourceAST t, int visit); void visitStarStarAssign(GroovySourceAST t, int visit); void visitStaticImport(GroovySourceAST t, int visit); void visitStaticInit(GroovySourceAST t, int visit); void visitStrictfp(GroovySourceAST t, int visit); void visitStringCh(GroovySourceAST t, int visit); void visitStringConstructor(GroovySourceAST t, int visit); void visitStringCtorEnd(GroovySourceAST t, int visit); void visitStringCtorMiddle(GroovySourceAST t, int visit); void visitStringCtorStart(GroovySourceAST t, int visit); void visitStringLiteral(GroovySourceAST t, int visit); void visitStringNl(GroovySourceAST t, int visit); void visitSuperCtorCall(GroovySourceAST t, int visit); void visitTripleDot(GroovySourceAST t, int visit); void visitType(GroovySourceAST t, int visit); void visitTypecast(GroovySourceAST t, int visit); void visitTypeArgument(GroovySourceAST t, int visit); void visitTypeArguments(GroovySourceAST t, int visit); void visitTypeLowerBounds(GroovySourceAST t, int visit); void visitTypeParameter(GroovySourceAST t, int visit); void visitTypeParameters(GroovySourceAST t, int visit); void visitTypeUpperBounds(GroovySourceAST t, int visit); void visitUnaryMinus(GroovySourceAST t, int visit); void visitUnaryPlus(GroovySourceAST t, int visit); void visitUnusedConst(GroovySourceAST t, int visit); void visitUnusedDo(GroovySourceAST t, int visit); void visitUnusedGoto(GroovySourceAST t, int visit); void visitVariableDef(GroovySourceAST t, int visit); void visitVariableParameterDef(GroovySourceAST t, int visit); void visitVocab(GroovySourceAST t, int visit); void visitWildcardType(GroovySourceAST t, int visit); void visitWs(GroovySourceAST t, int visit); void visitDefault(GroovySourceAST t,int visit); void tearDown(); void push(GroovySourceAST t); GroovySourceAST pop(); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/treewalker/TraversalHelper.java0000644001501200150120000011006011715031256027245 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.treewalker; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.AntlrASTProcessor; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import antlr.collections.AST; /** * Helper Class for Antlr AST traversal and visitation. * * @author Jeremy Rayner * @version $Revision$ */ public abstract class TraversalHelper implements AntlrASTProcessor { protected List unvisitedNodes; private final Visitor v; public TraversalHelper(Visitor visitor) { this.unvisitedNodes = new ArrayList(); this.v = visitor; } protected void setUp(GroovySourceAST ast) { v.setUp(); } protected void tearDown(GroovySourceAST ast) { v.tearDown(); } protected void push(GroovySourceAST ast) { v.push(ast); } protected GroovySourceAST pop() { return v.pop(); } protected void visitNode(GroovySourceAST ast, int n) { if (ast != null) { switch (ast.getType()) { case GroovyTokenTypes.ABSTRACT : v.visitAbstract(ast,n); break; case GroovyTokenTypes.ANNOTATION : v.visitAnnotation(ast,n); break; case GroovyTokenTypes.ANNOTATIONS : v.visitAnnotations(ast,n); break; case GroovyTokenTypes.ANNOTATION_ARRAY_INIT : v.visitAnnotationArrayInit(ast,n); break; // obsolete? case GroovyTokenTypes.ANNOTATION_DEF : v.visitAnnotationDef(ast,n); break; case GroovyTokenTypes.ANNOTATION_FIELD_DEF : v.visitAnnotationFieldDef(ast,n); break; case GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR : v.visitAnnotationMemberValuePair(ast,n); break; case GroovyTokenTypes.ARRAY_DECLARATOR : v.visitArrayDeclarator(ast,n); break; case GroovyTokenTypes.ASSIGN : v.visitAssign(ast,n); break; case GroovyTokenTypes.AT : v.visitAt(ast,n); break; case GroovyTokenTypes.BAND : v.visitBand(ast,n); break; case GroovyTokenTypes.BAND_ASSIGN : v.visitBandAssign(ast,n); break; case GroovyTokenTypes.BIG_SUFFIX : v.visitBigSuffix(ast,n); break; case GroovyTokenTypes.BLOCK : v.visitBlock(ast,n); break; case GroovyTokenTypes.BNOT : v.visitBnot(ast,n); break; case GroovyTokenTypes.BOR : v.visitBor(ast,n); break; case GroovyTokenTypes.BOR_ASSIGN : v.visitBorAssign(ast,n); break; case GroovyTokenTypes.BSR : v.visitBsr(ast,n); break; case GroovyTokenTypes.BSR_ASSIGN : v.visitBsrAssign(ast,n); break; case GroovyTokenTypes.BXOR : v.visitBxor(ast,n); break; case GroovyTokenTypes.BXOR_ASSIGN : v.visitBxorAssign(ast,n); break; case GroovyTokenTypes.CASE_GROUP : v.visitCaseGroup(ast,n); break; case GroovyTokenTypes.CLASS_DEF : v.visitClassDef(ast,n); break; case GroovyTokenTypes.CLOSABLE_BLOCK : v.visitClosedBlock(ast,n); break; case GroovyTokenTypes.CLOSABLE_BLOCK_OP : v.visitClosureOp(ast,n); break; case GroovyTokenTypes.CLOSURE_LIST : v.visitClosureList(ast,n); break; case GroovyTokenTypes.COLON : v.visitColon(ast,n); break; case GroovyTokenTypes.COMMA : v.visitComma(ast,n); break; case GroovyTokenTypes.COMPARE_TO : v.visitCompareTo(ast,n); break; case GroovyTokenTypes.CTOR_CALL : v.visitCtorCall(ast,n); break; case GroovyTokenTypes.CTOR_IDENT : v.visitCtorIdent(ast,n); break; case GroovyTokenTypes.DEC : v.visitDec(ast,n); break; case GroovyTokenTypes.DIGIT : v.visitDigit(ast,n); break; case GroovyTokenTypes.DIV : v.visitDiv(ast,n); break; case GroovyTokenTypes.DIV_ASSIGN : v.visitDivAssign(ast,n); break; case GroovyTokenTypes.DOLLAR : v.visitDollar(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_CTOR_END : v.visitRegexpCtorEnd(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_LITERAL : v.visitRegexpLiteral(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_SYMBOL : v.visitRegexpSymbol(ast,n); break; case GroovyTokenTypes.DOT : v.visitDot(ast,n); break; case GroovyTokenTypes.DYNAMIC_MEMBER : v.visitDynamicMember(ast,n); break; case GroovyTokenTypes.ELIST : v.visitElist(ast,n); break; case GroovyTokenTypes.EMPTY_STAT : v.visitEmptyStat(ast,n); break; case GroovyTokenTypes.ENUM_CONSTANT_DEF : v.visitEnumConstantDef(ast,n); break; case GroovyTokenTypes.ENUM_DEF : v.visitEnumDef(ast,n); break; case GroovyTokenTypes.EOF : v.visitEof(ast,n); break; case GroovyTokenTypes.EQUAL : v.visitEqual(ast,n); break; case GroovyTokenTypes.ESC : v.visitEsc(ast,n); break; case GroovyTokenTypes.EXPONENT : v.visitExponent(ast,n); break; case GroovyTokenTypes.EXPR : v.visitExpr(ast,n); break; case GroovyTokenTypes.EXTENDS_CLAUSE : v.visitExtendsClause(ast,n); break; case GroovyTokenTypes.FINAL : v.visitFinal(ast,n); break; case GroovyTokenTypes.FLOAT_SUFFIX : v.visitFloatSuffix(ast,n); break; case GroovyTokenTypes.FOR_CONDITION : v.visitForCondition(ast,n); break; case GroovyTokenTypes.FOR_EACH_CLAUSE : v.visitForEachClause(ast,n); break; case GroovyTokenTypes.FOR_INIT : v.visitForInit(ast,n); break; case GroovyTokenTypes.FOR_IN_ITERABLE : v.visitForInIterable(ast,n); break; case GroovyTokenTypes.FOR_ITERATOR : v.visitForIterator(ast,n); break; case GroovyTokenTypes.GE : v.visitGe(ast,n); break; case GroovyTokenTypes.GT : v.visitGt(ast,n); break; case GroovyTokenTypes.HEX_DIGIT : v.visitHexDigit(ast,n); break; case GroovyTokenTypes.IDENT : v.visitIdent(ast,n); break; case GroovyTokenTypes.IMPLEMENTS_CLAUSE : v.visitImplementsClause(ast,n); break; case GroovyTokenTypes.IMPLICIT_PARAMETERS : v.visitImplicitParameters(ast,n); break; case GroovyTokenTypes.IMPORT : v.visitImport(ast,n); break; case GroovyTokenTypes.INC : v.visitInc(ast,n); break; case GroovyTokenTypes.INDEX_OP : v.visitIndexOp(ast,n); break; case GroovyTokenTypes.INSTANCE_INIT : v.visitInstanceInit(ast,n); break; case GroovyTokenTypes.INTERFACE_DEF : v.visitInterfaceDef(ast,n); break; case GroovyTokenTypes.LABELED_ARG : v.visitLabeledArg(ast,n); break; case GroovyTokenTypes.LABELED_STAT : v.visitLabeledStat(ast,n); break; case GroovyTokenTypes.LAND : v.visitLand(ast,n); break; case GroovyTokenTypes.LBRACK : v.visitLbrack(ast,n); break; case GroovyTokenTypes.LCURLY : v.visitLcurly(ast,n); break; case GroovyTokenTypes.LE : v.visitLe(ast,n); break; case GroovyTokenTypes.LETTER : v.visitLetter(ast,n); break; case GroovyTokenTypes.LIST_CONSTRUCTOR : v.visitListConstructor(ast,n); break; case GroovyTokenTypes.LITERAL_as : v.visitLiteralAs(ast,n); break; case GroovyTokenTypes.LITERAL_assert : v.visitLiteralAssert(ast,n); break; case GroovyTokenTypes.LITERAL_boolean : v.visitLiteralBoolean(ast,n); break; case GroovyTokenTypes.LITERAL_break : v.visitLiteralBreak(ast,n); break; case GroovyTokenTypes.LITERAL_byte : v.visitLiteralByte(ast,n); break; case GroovyTokenTypes.LITERAL_case : v.visitLiteralCase(ast,n); break; case GroovyTokenTypes.LITERAL_catch : v.visitLiteralCatch(ast,n); break; case GroovyTokenTypes.LITERAL_char : v.visitLiteralChar(ast,n); break; case GroovyTokenTypes.LITERAL_class : v.visitLiteralClass(ast,n); break; case GroovyTokenTypes.LITERAL_continue : v.visitLiteralContinue(ast,n); break; case GroovyTokenTypes.LITERAL_def : v.visitLiteralDef(ast,n); break; case GroovyTokenTypes.LITERAL_default : v.visitLiteralDefault(ast,n); break; case GroovyTokenTypes.LITERAL_double : v.visitLiteralDouble(ast,n); break; case GroovyTokenTypes.LITERAL_else : v.visitLiteralElse(ast,n); break; case GroovyTokenTypes.LITERAL_enum : v.visitLiteralEnum(ast,n); break; case GroovyTokenTypes.LITERAL_extends : v.visitLiteralExtends(ast,n); break; case GroovyTokenTypes.LITERAL_false : v.visitLiteralFalse(ast,n); break; case GroovyTokenTypes.LITERAL_finally : v.visitLiteralFinally(ast,n); break; case GroovyTokenTypes.LITERAL_float : v.visitLiteralFloat(ast,n); break; case GroovyTokenTypes.LITERAL_for : v.visitLiteralFor(ast,n); break; case GroovyTokenTypes.LITERAL_if : v.visitLiteralIf(ast,n); break; case GroovyTokenTypes.LITERAL_implements : v.visitLiteralImplements(ast,n); break; case GroovyTokenTypes.LITERAL_import : v.visitLiteralImport(ast,n); break; case GroovyTokenTypes.LITERAL_in : v.visitLiteralIn(ast,n); break; case GroovyTokenTypes.LITERAL_instanceof : v.visitLiteralInstanceof(ast,n); break; case GroovyTokenTypes.LITERAL_int : v.visitLiteralInt(ast,n); break; case GroovyTokenTypes.LITERAL_interface : v.visitLiteralInterface(ast,n); break; case GroovyTokenTypes.LITERAL_long : v.visitLiteralLong(ast,n); break; case GroovyTokenTypes.LITERAL_native : v.visitLiteralNative(ast,n); break; case GroovyTokenTypes.LITERAL_new : v.visitLiteralNew(ast,n); break; case GroovyTokenTypes.LITERAL_null : v.visitLiteralNull(ast,n); break; case GroovyTokenTypes.LITERAL_package : v.visitLiteralPackage(ast,n); break; case GroovyTokenTypes.LITERAL_private : v.visitLiteralPrivate(ast,n); break; case GroovyTokenTypes.LITERAL_protected : v.visitLiteralProtected(ast,n); break; case GroovyTokenTypes.LITERAL_public : v.visitLiteralPublic(ast,n); break; case GroovyTokenTypes.LITERAL_return : v.visitLiteralReturn(ast,n); break; case GroovyTokenTypes.LITERAL_short : v.visitLiteralShort(ast,n); break; case GroovyTokenTypes.LITERAL_static : v.visitLiteralStatic(ast,n); break; case GroovyTokenTypes.LITERAL_super : v.visitLiteralSuper(ast,n); break; case GroovyTokenTypes.LITERAL_switch : v.visitLiteralSwitch(ast,n); break; case GroovyTokenTypes.LITERAL_synchronized : v.visitLiteralSynchronized(ast,n); break; case GroovyTokenTypes.LITERAL_this : v.visitLiteralThis(ast,n); break; case GroovyTokenTypes.LITERAL_threadsafe : v.visitLiteralThreadsafe(ast,n); break; case GroovyTokenTypes.LITERAL_throw : v.visitLiteralThrow(ast,n); break; case GroovyTokenTypes.LITERAL_throws : v.visitLiteralThrows(ast,n); break; case GroovyTokenTypes.LITERAL_transient : v.visitLiteralTransient(ast,n); break; case GroovyTokenTypes.LITERAL_true : v.visitLiteralTrue(ast,n); break; case GroovyTokenTypes.LITERAL_try : v.visitLiteralTry(ast,n); break; case GroovyTokenTypes.LITERAL_void : v.visitLiteralVoid(ast,n); break; case GroovyTokenTypes.LITERAL_volatile : v.visitLiteralVolatile(ast,n); break; case GroovyTokenTypes.LITERAL_while : v.visitLiteralWhile(ast,n); break; case GroovyTokenTypes.LNOT : v.visitLnot(ast,n); break; case GroovyTokenTypes.LOR : v.visitLor(ast,n); break; case GroovyTokenTypes.LPAREN : v.visitLparen(ast,n); break; case GroovyTokenTypes.LT : v.visitLt(ast,n); break; case GroovyTokenTypes.MAP_CONSTRUCTOR : v.visitMapConstructor(ast,n); break; case GroovyTokenTypes.MEMBER_POINTER : v.visitMemberPointer(ast,n); break; case GroovyTokenTypes.METHOD_CALL : v.visitMethodCall(ast,n); break; case GroovyTokenTypes.METHOD_DEF : v.visitMethodDef(ast,n); break; case GroovyTokenTypes.MINUS : v.visitMinus(ast,n); break; case GroovyTokenTypes.MINUS_ASSIGN : v.visitMinusAssign(ast,n); break; case GroovyTokenTypes.ML_COMMENT : v.visitMlComment(ast,n); break; case GroovyTokenTypes.MOD : v.visitMod(ast,n); break; case GroovyTokenTypes.MODIFIERS : v.visitModifiers(ast,n); break; case GroovyTokenTypes.MOD_ASSIGN : v.visitModAssign(ast,n); break; case GroovyTokenTypes.NLS : v.visitNls(ast,n); break; case GroovyTokenTypes.NOT_EQUAL : v.visitNotEqual(ast,n); break; case GroovyTokenTypes.NULL_TREE_LOOKAHEAD : v.visitNullTreeLookahead(ast,n); break; case GroovyTokenTypes.NUM_BIG_DECIMAL : v.visitNumBigDecimal(ast,n); break; case GroovyTokenTypes.NUM_BIG_INT : v.visitNumBigInt(ast,n); break; case GroovyTokenTypes.NUM_DOUBLE : v.visitNumDouble(ast,n); break; case GroovyTokenTypes.NUM_FLOAT : v.visitNumFloat(ast,n); break; case GroovyTokenTypes.NUM_INT : v.visitNumInt(ast,n); break; case GroovyTokenTypes.NUM_LONG : v.visitNumLong(ast,n); break; case GroovyTokenTypes.OBJBLOCK : v.visitObjblock(ast,n); break; case GroovyTokenTypes.ONE_NL : v.visitOneNl(ast,n); break; case GroovyTokenTypes.OPTIONAL_DOT : v.visitOptionalDot(ast,n); break; case GroovyTokenTypes.PACKAGE_DEF : v.visitPackageDef(ast,n); break; case GroovyTokenTypes.PARAMETERS : v.visitParameters(ast,n); break; case GroovyTokenTypes.PARAMETER_DEF : v.visitParameterDef(ast,n); break; case GroovyTokenTypes.PLUS : v.visitPlus(ast,n); break; case GroovyTokenTypes.PLUS_ASSIGN : v.visitPlusAssign(ast,n); break; case GroovyTokenTypes.POST_DEC : v.visitPostDec(ast,n); break; case GroovyTokenTypes.POST_INC : v.visitPostInc(ast,n); break; case GroovyTokenTypes.QUESTION : v.visitQuestion(ast,n); break; case GroovyTokenTypes.RANGE_EXCLUSIVE : v.visitRangeExclusive(ast,n); break; case GroovyTokenTypes.RANGE_INCLUSIVE : v.visitRangeInclusive(ast,n); break; case GroovyTokenTypes.RBRACK : v.visitRbrack(ast,n); break; case GroovyTokenTypes.RCURLY : v.visitRcurly(ast,n); break; case GroovyTokenTypes.REGEXP_CTOR_END : v.visitRegexpCtorEnd(ast,n); break; case GroovyTokenTypes.REGEXP_LITERAL : v.visitRegexpLiteral(ast,n); break; case GroovyTokenTypes.REGEXP_SYMBOL : v.visitRegexpSymbol(ast,n); break; case GroovyTokenTypes.REGEX_FIND : v.visitRegexFind(ast,n); break; case GroovyTokenTypes.REGEX_MATCH : v.visitRegexMatch(ast,n); break; case GroovyTokenTypes.RPAREN : v.visitRparen(ast,n); break; case GroovyTokenTypes.SELECT_SLOT : v.visitSelectSlot(ast,n); break; case GroovyTokenTypes.SEMI : v.visitSemi(ast,n); break; case GroovyTokenTypes.SH_COMMENT : v.visitShComment(ast,n); break; case GroovyTokenTypes.SL : v.visitSl(ast,n); break; case GroovyTokenTypes.SLIST : v.visitSlist(ast,n); break; case GroovyTokenTypes.SL_ASSIGN : v.visitSlAssign(ast,n); break; case GroovyTokenTypes.SL_COMMENT : v.visitSlComment(ast,n); break; case GroovyTokenTypes.SPREAD_ARG : v.visitSpreadArg(ast,n); break; case GroovyTokenTypes.SPREAD_DOT : v.visitSpreadDot(ast,n); break; case GroovyTokenTypes.SPREAD_MAP_ARG : v.visitSpreadMapArg(ast,n); break; case GroovyTokenTypes.SR : v.visitSr(ast,n); break; case GroovyTokenTypes.SR_ASSIGN : v.visitSrAssign(ast,n); break; case GroovyTokenTypes.STAR : v.visitStar(ast,n); break; case GroovyTokenTypes.STAR_ASSIGN : v.visitStarAssign(ast,n); break; case GroovyTokenTypes.STAR_STAR : v.visitStarStar(ast,n); break; case GroovyTokenTypes.STAR_STAR_ASSIGN : v.visitStarStarAssign(ast,n); break; case GroovyTokenTypes.STATIC_IMPORT : v.visitStaticImport(ast,n); break; case GroovyTokenTypes.STATIC_INIT : v.visitStaticInit(ast,n); break; case GroovyTokenTypes.STRICTFP : v.visitStrictfp(ast,n); break; case GroovyTokenTypes.STRING_CH : v.visitStringCh(ast,n); break; case GroovyTokenTypes.STRING_CONSTRUCTOR : v.visitStringConstructor(ast,n); break; case GroovyTokenTypes.STRING_CTOR_END : v.visitStringCtorEnd(ast,n); break; case GroovyTokenTypes.STRING_CTOR_MIDDLE : v.visitStringCtorMiddle(ast,n); break; case GroovyTokenTypes.STRING_CTOR_START : v.visitStringCtorStart(ast,n); break; case GroovyTokenTypes.STRING_LITERAL : v.visitStringLiteral(ast,n); break; case GroovyTokenTypes.STRING_NL : v.visitStringNl(ast,n); break; case GroovyTokenTypes.SUPER_CTOR_CALL : v.visitSuperCtorCall(ast,n); break; case GroovyTokenTypes.TRIPLE_DOT : v.visitTripleDot(ast,n); break; case GroovyTokenTypes.TYPE : v.visitType(ast,n); break; case GroovyTokenTypes.TYPECAST : v.visitTypecast(ast,n); break; case GroovyTokenTypes.TYPE_ARGUMENT : v.visitTypeArgument(ast,n); break; case GroovyTokenTypes.TYPE_ARGUMENTS : v.visitTypeArguments(ast,n); break; case GroovyTokenTypes.TYPE_LOWER_BOUNDS : v.visitTypeLowerBounds(ast,n); break; case GroovyTokenTypes.TYPE_PARAMETER : v.visitTypeParameter(ast,n); break; case GroovyTokenTypes.TYPE_PARAMETERS : v.visitTypeParameters(ast,n); break; case GroovyTokenTypes.TYPE_UPPER_BOUNDS : v.visitTypeUpperBounds(ast,n); break; case GroovyTokenTypes.UNARY_MINUS : v.visitUnaryMinus(ast,n); break; case GroovyTokenTypes.UNARY_PLUS : v.visitUnaryPlus(ast,n); break; case GroovyTokenTypes.UNUSED_CONST : v.visitUnusedConst(ast,n); break; case GroovyTokenTypes.UNUSED_DO : v.visitUnusedDo(ast,n); break; case GroovyTokenTypes.UNUSED_GOTO : v.visitUnusedGoto(ast,n); break; case GroovyTokenTypes.VARIABLE_DEF : v.visitVariableDef(ast,n); break; case GroovyTokenTypes.VARIABLE_PARAMETER_DEF : v.visitVariableParameterDef(ast,n); break; case GroovyTokenTypes.VOCAB : v.visitVocab(ast,n); break; case GroovyTokenTypes.WILDCARD_TYPE : v.visitWildcardType(ast,n); break; case GroovyTokenTypes.WS : v.visitWs(ast,n); break; default : v.visitDefault(ast,n); break; } } else { // the supplied AST was null v.visitDefault(null,n); } } protected abstract void accept(GroovySourceAST currentNode); protected void accept_v_FirstChildsFirstChild_v_Child2_Child3_v_Child4_v___v_LastChild(GroovySourceAST t) { openingVisit(t); GroovySourceAST expr2 = t.childAt(0); skip(expr2); accept(expr2.childAt(0)); closingVisit(t); GroovySourceAST sibling = (GroovySourceAST) expr2.getNextSibling(); boolean firstSList = true; while (sibling != null) { if (!firstSList) { subsequentVisit(t); } firstSList = false; accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } protected void accept_v_FirstChildsFirstChild_v_RestOfTheChildren(GroovySourceAST t) { openingVisit(t); GroovySourceAST expr = t.childAt(0); skip(expr); accept(expr.childAt(0)); closingVisit(t); acceptSiblings(expr); } protected void accept_FirstChild_v_SecondChild(GroovySourceAST t) { accept(t.childAt(0)); subsequentVisit(t); accept(t.childAt(1)); } protected void accept_FirstChild_v_SecondChild_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); accept(t.childAt(1)); closingVisit(t); } protected void accept_SecondChild_v_ThirdChild_v(GroovySourceAST t) { accept(t.childAt(1)); openingVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstChild_v_SecondChildsChildren_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); GroovySourceAST secondChild = t.childAt(1); if (secondChild != null) { acceptChildren(secondChild); } closingVisit(t); } protected void accept_v_FirstChild_SecondChild_v_ThirdChild_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); accept(t.childAt(1)); subsequentVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstChild_v_SecondChild_v_ThirdChild_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); accept(t.childAt(1)); subsequentVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstSecondAndThirdChild_v_v_ForthChild(GroovySourceAST t) { GroovySourceAST child1 = (GroovySourceAST) t.getFirstChild(); if (child1 != null) { accept(child1); GroovySourceAST child2 = (GroovySourceAST) child1.getNextSibling(); if (child2 != null) { accept(child2); GroovySourceAST child3 = (GroovySourceAST) child2.getNextSibling(); if (child3 != null) { accept(child3); openingVisit(t); GroovySourceAST child4 = (GroovySourceAST) child3.getNextSibling(); if (child4 != null) { subsequentVisit(t); accept(child4); } } } } } protected void accept_v_FirstChild_2ndv_SecondChild_v___LastChild_v(GroovySourceAST t) { openingVisit(t); GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); GroovySourceAST sibling = (GroovySourceAST) child.getNextSibling(); if (sibling != null) { secondVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); while (sibling != null) { subsequentVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } } closingVisit(t); } protected void accept_v_FirstChild_v_SecondChild_v___LastChild_v(GroovySourceAST t) { openingVisit(t); GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); GroovySourceAST sibling = (GroovySourceAST) child.getNextSibling(); while (sibling != null) { subsequentVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } closingVisit(t); } protected void accept_v_FirstChild_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); closingVisit(t); } protected void accept_v_Siblings_v(GroovySourceAST t) { openingVisit(t); acceptSiblings(t); closingVisit(t); } protected void accept_v_AllChildren_v_Siblings(GroovySourceAST t) { openingVisit(t); acceptChildren(t); closingVisit(t); acceptSiblings(t); } protected void accept_v_AllChildren_v(GroovySourceAST t) { openingVisit(t); acceptChildren(t); closingVisit(t); } protected void accept_FirstChild_v_RestOfTheChildren(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); closingVisit(t); acceptSiblings(t.childAt(0)); } protected void accept_FirstChild_v_RestOfTheChildren_v_LastChild(GroovySourceAST t) { int count = 0; accept(t.childAt(0)); count++; openingVisit(t); if (t.childAt(0) != null) { GroovySourceAST sibling = (GroovySourceAST) t.childAt(0).getNextSibling(); while (sibling != null) { if (count == t.getNumberOfChildren() - 1) { closingVisit(t); } accept(sibling); count++; sibling = (GroovySourceAST) sibling.getNextSibling(); } } } protected void accept_FirstChild_v_RestOfTheChildren_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); acceptSiblings(t.childAt(0)); closingVisit(t); } protected void accept_v_FirstChild_v_RestOfTheChildren(GroovySourceAST t) { accept_v_FirstChild_v(t); acceptSiblings(t.childAt(0)); } protected void accept_v_FirstChild_v_RestOfTheChildren_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); subsequentVisit(t); acceptSiblings(t.childAt(0)); closingVisit(t); } protected void acceptSiblings(GroovySourceAST t) { if (t != null) { GroovySourceAST sibling = (GroovySourceAST) t.getNextSibling(); while (sibling != null) { accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } } protected void acceptChildren(GroovySourceAST t) { if (t != null) { GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); acceptSiblings(child); } } } protected void skip(GroovySourceAST expr) { unvisitedNodes.remove(expr); } protected void openingVisit(GroovySourceAST t) { unvisitedNodes.remove(t); int n = Visitor.OPENING_VISIT; visitNode(t, n); } protected void secondVisit(GroovySourceAST t) { int n = Visitor.SECOND_VISIT; visitNode(t, n); } protected void subsequentVisit(GroovySourceAST t) { int n = Visitor.SUBSEQUENT_VISIT; visitNode(t, n); } protected void closingVisit(GroovySourceAST t) { int n = Visitor.CLOSING_VISIT; visitNode(t, n); } public AST process(AST t) { GroovySourceAST node = (GroovySourceAST) t; // process each node in turn setUp(node); accept(node); acceptSiblings(node); tearDown(node); return null; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/groovy.g0000644001501200150120000047327211715031256022650 0ustar miguelmiguel// Note: Please don't use physical tabs. Logical tabs for indent are width 4. header { package org.codehaus.groovy.antlr.parser; import org.codehaus.groovy.antlr.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import antlr.CommonToken; import org.codehaus.groovy.GroovyBugError; import antlr.TokenStreamRecognitionException; } /** JSR-241 Groovy Recognizer. * * Run 'java Main [-showtree] directory-full-of-groovy-files' * * [The -showtree option pops up a Swing frame that shows * the AST constructed from the parser.] * * Contributing authors: * John Mitchell johnm@non.net * Terence Parr parrt@magelang.com * John Lilley jlilley@empathy.com * Scott Stanchfield thetick@magelang.com * Markus Mohnen mohnen@informatik.rwth-aachen.de * Peter Williams pete.williams@sun.com * Allan Jacobs Allan.Jacobs@eng.sun.com * Steve Messick messick@redhills.com * James Strachan jstrachan@protique.com * John Pybus john@pybus.org * John Rose rose00@mac.com * Jeremy Rayner groovy@ross-rayner.com * Alex Popescu the.mindstorm@gmail.com * Martin Kempf mkempf@hsr.ch * Reto Kleeb rkleeb@hsr.ch * * Version 1.00 December 9, 1997 -- initial release * Version 1.01 December 10, 1997 * fixed bug in octal def (0..7 not 0..8) * Version 1.10 August 1998 (parrt) * added tree construction * fixed definition of WS,comments for mac,pc,unix newlines * added unary plus * Version 1.11 (Nov 20, 1998) * Added "shutup" option to turn off last ambig warning. * Fixed inner class def to allow named class defs as statements * synchronized requires compound not simple statement * add [] after builtInType DOT class in primaryExpression * "const" is reserved but not valid..removed from modifiers * Version 1.12 (Feb 2, 1999) * Changed LITERAL_xxx to xxx in tree grammar. * Updated java.g to use tokens {...} now for 2.6.0 (new feature). * * Version 1.13 (Apr 23, 1999) * Didn't have (stat)? for else clause in tree parser. * Didn't gen ASTs for interface extends. Updated tree parser too. * Updated to 2.6.0. * Version 1.14 (Jun 20, 1999) * Allowed final/abstract on local classes. * Removed local interfaces from methods * Put instanceof precedence where it belongs...in relationalExpr * It also had expr not type as arg; fixed it. * Missing ! on SEMI in classBlock * fixed: (expr) + "string" was parsed incorrectly (+ as unary plus). * fixed: didn't like Object[].class in parser or tree parser * Version 1.15 (Jun 26, 1999) * Screwed up rule with instanceof in it. :( Fixed. * Tree parser didn't like (expr).something; fixed. * Allowed multiple inheritance in tree grammar. oops. * Version 1.16 (August 22, 1999) * Extending an interface built a wacky tree: had extra EXTENDS. * Tree grammar didn't allow multiple superinterfaces. * Tree grammar didn't allow empty var initializer: {} * Version 1.17 (October 12, 1999) * ESC lexer rule allowed 399 max not 377 max. * java.tree.g didn't handle the expression of synchronized * statements. * Version 1.18 (August 12, 2001) * Terence updated to Java 2 Version 1.3 by * observing/combining work of Allan Jacobs and Steve * Messick. Handles 1.3 src. Summary: * o primary didn't include boolean.class kind of thing * o constructor calls parsed explicitly now: * see explicitConstructorInvocation * o add strictfp modifier * o missing objBlock after new expression in tree grammar * o merged local class definition alternatives, moved after declaration * o fixed problem with ClassName.super.field * o reordered some alternatives to make things more efficient * o long and double constants were not differentiated from int/float * o whitespace rule was inefficient: matched only one char * o add an examples directory with some nasty 1.3 cases * o made Main.java use buffered IO and a Reader for Unicode support * o supports UNICODE? * Using Unicode charVocabulary makes code file big, but only * in the bitsets at the end. I need to make ANTLR generate * unicode bitsets more efficiently. * Version 1.19 (April 25, 2002) * Terence added in nice fixes by John Pybus concerning floating * constants and problems with super() calls. John did a nice * reorg of the primary/postfix expression stuff to read better * and makes f.g.super() parse properly (it was METHOD_CALL not * a SUPER_CTOR_CALL). Also: * * o "finally" clause was a root...made it a child of "try" * o Added stuff for asserts too for Java 1.4, but *commented out* * as it is not backward compatible. * * Version 1.20 (October 27, 2002) * * Terence ended up reorging John Pybus' stuff to * remove some nondeterminisms and some syntactic predicates. * Note that the grammar is stricter now; e.g., this(...) must * be the first statement. * * Trinary ?: operator wasn't working as array name: * (isBig ? bigDigits : digits)[i]; * * Checked parser/tree parser on source for * Resin-2.0.5, jive-2.1.1, jdk 1.3.1, Lucene, antlr 2.7.2a4, * and the 110k-line jGuru server source. * * Version 1.21 (October 17, 2003) * Fixed lots of problems including: * Ray Waldin: add typeDefinition to interfaceBlock in java.tree.g * He found a problem/fix with floating point that start with 0 * Ray also fixed problem that (int.class) was not recognized. * Thorsten van Ellen noticed that \n are allowed incorrectly in strings. * TJP fixed CHAR_LITERAL analogously. * * Version 1.21.2 (March, 2003) * Changes by Matt Quail to support generics (as per JDK1.5/JSR14) * Notes: * o We only allow the "extends" keyword and not the "implements" * keyword, since that's what JSR14 seems to imply. * o Thanks to Monty Zukowski for his help on the antlr-interest * mail list. * o Thanks to Alan Eliasen for testing the grammar over his * Fink source base * * Version 1.22 (July, 2004) * Changes by Michael Studman to support Java 1.5 language extensions * Notes: * o Added support for annotations types * o Finished off Matt Quail's generics enhancements to support bound type arguments * o Added support for new for statement syntax * o Added support for static import syntax * o Added support for enum types * o Tested against JDK 1.5 source base and source base of jdigraph project * o Thanks to Matt Quail for doing the hard part by doing most of the generics work * * Version 1.22.1 (July 28, 2004) * Bug/omission fixes for Java 1.5 language support * o Fixed tree structure bug with classOrInterface - thanks to Pieter Vangorpto for * spotting this * o Fixed bug where incorrect handling of SR and BSR tokens would cause type * parameters to be recognised as type arguments. * o Enabled type parameters on constructors, annotations on enum constants * and package definitions * o Fixed problems when parsing if ((char.class.equals(c))) {} - solution by Matt Quail at Cenqua * * Version 1.22.2 (July 28, 2004) * Slight refactoring of Java 1.5 language support * o Refactored for/"foreach" productions so that original literal "for" literal * is still used but the for sub-clauses vary by token type * o Fixed bug where type parameter was not included in generic constructor's branch of AST * * Version 1.22.3 (August 26, 2004) * Bug fixes as identified by Michael Stahl; clean up of tabs/spaces * and other refactorings * o Fixed typeParameters omission in identPrimary and newStatement * o Replaced GT reconcilliation code with simple semantic predicate * o Adapted enum/assert keyword checking support from Michael Stahl's java15 grammar * o Refactored typeDefinition production and field productions to reduce duplication * * Version 1.22.4 (October 21, 2004) * Small bux fixes * o Added typeArguments to explicitConstructorInvocation, e.g. new MyParameterised() * o Added typeArguments to postfixExpression productions for anonymous inner class super * constructor invocation, e.g. new Outer().super() * o Fixed bug in array declarations identified by Geoff Roy * * Version 1.22.4.g.1 * o I have taken java.g for Java1.5 from Michael Studman (1.22.4) * and have applied the groovy.diff from java.g (1.22) by John Rose * back onto the new root (1.22.4) - Jeremy Rayner (Jan 2005) * o for a map of the task see... * http://groovy.javanicus.com/java-g.png * * Version 1.22.4.g.2 * o mkempf, rkleeb, Dec 2007 * o fixed various rules so that they call the correct Create Method * to make sure that the line information are correct * * This grammar is in the PUBLIC DOMAIN */ class GroovyRecognizer extends Parser; options { k = 2; // two token lookahead exportVocab=Groovy; // Call its vocabulary "Groovy" codeGenMakeSwitchThreshold = 2; // Some optimizations codeGenBitsetTestThreshold = 3; defaultErrorHandler = false; // Don't generate parser error handlers buildAST = true; } tokens { BLOCK; MODIFIERS; OBJBLOCK; SLIST; METHOD_DEF; VARIABLE_DEF; INSTANCE_INIT; STATIC_INIT; TYPE; CLASS_DEF; INTERFACE_DEF; PACKAGE_DEF; ARRAY_DECLARATOR; EXTENDS_CLAUSE; IMPLEMENTS_CLAUSE; PARAMETERS; PARAMETER_DEF; LABELED_STAT; TYPECAST; INDEX_OP; POST_INC; POST_DEC; METHOD_CALL; EXPR; IMPORT; UNARY_MINUS; UNARY_PLUS; CASE_GROUP; ELIST; FOR_INIT; FOR_CONDITION; FOR_ITERATOR; EMPTY_STAT; FINAL="final"; ABSTRACT="abstract"; UNUSED_GOTO="goto"; UNUSED_CONST="const"; UNUSED_DO="do"; STRICTFP="strictfp"; SUPER_CTOR_CALL; CTOR_CALL; CTOR_IDENT; VARIABLE_PARAMETER_DEF; STRING_CONSTRUCTOR; STRING_CTOR_MIDDLE; CLOSABLE_BLOCK; IMPLICIT_PARAMETERS; SELECT_SLOT; DYNAMIC_MEMBER; LABELED_ARG; SPREAD_ARG; SPREAD_MAP_ARG; //deprecated - SCOPE_ESCAPE; LIST_CONSTRUCTOR; MAP_CONSTRUCTOR; FOR_IN_ITERABLE; STATIC_IMPORT; ENUM_DEF; ENUM_CONSTANT_DEF; FOR_EACH_CLAUSE; ANNOTATION_DEF; ANNOTATIONS; ANNOTATION; ANNOTATION_MEMBER_VALUE_PAIR; ANNOTATION_FIELD_DEF; ANNOTATION_ARRAY_INIT; TYPE_ARGUMENTS; TYPE_ARGUMENT; TYPE_PARAMETERS; TYPE_PARAMETER; WILDCARD_TYPE; TYPE_UPPER_BOUNDS; TYPE_LOWER_BOUNDS; CLOSURE_LIST; } { /** This factory is the correct way to wire together a Groovy parser and lexer. */ public static GroovyRecognizer make(GroovyLexer lexer) { GroovyRecognizer parser = new GroovyRecognizer(lexer.plumb()); // TODO: set up a common error-handling control block, to avoid excessive tangle between these guys parser.lexer = lexer; lexer.parser = parser; parser.getASTFactory().setASTNodeClass(GroovySourceAST.class); parser.warningList = new ArrayList(); return parser; } // Create a scanner that reads from the input stream passed to us... public static GroovyRecognizer make(InputStream in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(Reader in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(InputBuffer in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(LexerSharedInputState in) { return make(new GroovyLexer(in)); } private static GroovySourceAST dummyVariableToforceClassLoaderToFindASTClass = new GroovySourceAST(); List warningList; public List getWarningList() { return warningList; } GroovyLexer lexer; public GroovyLexer getLexer() { return lexer; } public void setFilename(String f) { super.setFilename(f); lexer.setFilename(f); } private SourceBuffer sourceBuffer; public void setSourceBuffer(SourceBuffer sourceBuffer) { this.sourceBuffer = sourceBuffer; } /** Create an AST node with the token type and text passed in, but * with the same background information as another supplied Token (e.g. line numbers). * To be used in place of antlr tree construction syntax, * i.e. #[TOKEN,"text"] becomes create(TOKEN,"text",anotherToken) * * todo - change antlr.ASTFactory to do this instead... */ public AST create(int type, String txt, AST first) { AST t = astFactory.create(type,txt); if ( t != null && first != null) { // first copy details from first token t.initialize(first); // then ensure that type and txt are specific to this new node t.initialize(type,txt); } return t; } private AST attachLast(AST t, Object last) { if ((t instanceof GroovySourceAST) && (last instanceof SourceInfo)) { SourceInfo lastInfo = (SourceInfo) last; GroovySourceAST node = (GroovySourceAST)t; node.setColumnLast(lastInfo.getColumn()); node.setLineLast(lastInfo.getLine()); // This is a good point to call node.setSnippet(), // but it bulks up the AST too much for production code. } return t; } public AST create(int type, String txt, Token first, Token last) { return attachLast(create(type, txt, astFactory.create(first)), last); } public AST create(int type, String txt, AST first, Token last) { return attachLast(create(type, txt, first), last); } public AST create(int type, String txt, AST first, AST last) { return attachLast(create(type, txt, first), last); } /** * Clones the token */ public Token cloneToken(Token t) { CommonToken clone = new CommonToken(t.getType(),t.getText()); clone.setLine(t.getLine()); clone.setColumn(t.getColumn()); return clone; } // stuff to adjust ANTLR's tracing machinery public static boolean tracing = false; // only effective if antlr.Tool is run with -traceParser public void traceIn(String rname) throws TokenStreamException { if (!GroovyRecognizer.tracing) return; super.traceIn(rname); } public void traceOut(String rname) throws TokenStreamException { if (!GroovyRecognizer.tracing) return; if (returnAST != null) rname += returnAST.toStringList(); super.traceOut(rname); } // Error handling. This is a funnel through which parser errors go, when the parser can suggest a solution. public void requireFailed(String problem, String solution) throws SemanticException { // TODO: Needs more work. Token lt = null; int lineNum = Token.badToken.getLine(), colNum = Token.badToken.getColumn(); try { lt = LT(1); if(lt != null) { lineNum = lt.getLine(); colNum = lt.getColumn(); } } catch (TokenStreamException ee) { if(ee instanceof TokenStreamRecognitionException) { lineNum = ((TokenStreamRecognitionException) ee).recog.getLine(); colNum = ((TokenStreamRecognitionException) ee).recog.getColumn(); } } throw new SemanticException(problem + ";\n solution: " + solution, getFilename(), lineNum, colNum); } public void addWarning(String warning, String solution) { Token lt = null; try { lt = LT(1); } catch (TokenStreamException ee) { } if (lt == null) lt = Token.badToken; Map row = new HashMap(); row.put("warning", warning); row.put("solution", solution); row.put("filename", getFilename()); row.put("line", Integer.valueOf(lt.getLine())); row.put("column", Integer.valueOf(lt.getColumn())); // System.out.println(row); warningList.add(row); } // Convenience method for checking of expected error syndromes. private void require(boolean z, String problem, String solution) throws SemanticException { if (!z) requireFailed(problem, solution); } private boolean matchGenericTypeBrackets(boolean z, String problem, String solution) throws SemanticException { if (!z) matchGenericTypeBracketsFailed(problem, solution); return z; } public void matchGenericTypeBracketsFailed(String problem, String solution) throws SemanticException { Token lt = null; int lineNum = Token.badToken.getLine(), colNum = Token.badToken.getColumn(); try { lt = LT(1); if(lt != null) { lineNum = lt.getLine(); colNum = lt.getColumn(); } } catch (TokenStreamException ee) { if(ee instanceof TokenStreamRecognitionException) { lineNum = ((TokenStreamRecognitionException) ee).recog.getLine(); colNum = ((TokenStreamRecognitionException) ee).recog.getColumn(); } } throw new SemanticException(problem + ";\n solution: " + solution, getFilename(), lineNum, colNum); } // Query a name token to see if it begins with a capital letter. // This is used to tell the difference (w/o symbol table access) between {String x} and {println x}. private boolean isUpperCase(Token x) { if (x == null || x.getType() != IDENT) return false; // cannot happen? String xtext = x.getText(); return (xtext.length() > 0 && Character.isUpperCase(xtext.charAt(0))); } private AST currentClass = null; // current enclosing class (for constructor recognition) // Query a name token to see if it is identical with the current class name. // This is used to distinguish constructors from other methods. private boolean isConstructorIdent(Token x) { if (currentClass == null) return false; if (currentClass.getType() != IDENT) return false; // cannot happen? String cname = currentClass.getText(); if (x == null || x.getType() != IDENT) return false; // cannot happen? return cname.equals(x.getText()); } private void dumpTree(AST ast, String offset) { dump(ast, offset); for (AST node = ast.getFirstChild(); node != null; node = node.getNextSibling()) { dumpTree(node, offset+"\t"); } } private void dump(AST node, String offset) { System.out.println(offset+"Type: " + getTokenName(node) + " text: " + node.getText()); } private String getTokenName(AST node) { if (node == null) return "null"; return getTokenName(node.getType()); } // Scratch variable for last 'sep' token. // Written by the 'sep' rule, read only by immediate callers of 'sep'. // (Not entirely clean, but better than a million xx=sep occurrences.) private int sepToken = EOF; // Scratch variable for last argument list; tells whether there was a label. // Written by 'argList' rule, read only by immediate callers of 'argList'. private boolean argListHasLabels = false; // Scratch variable, holds most recently completed pathExpression. // Read only by immediate callers of 'pathExpression' and 'expression'. private AST lastPathExpression = null; // Inherited attribute pushed into most expression rules. // If not zero, it means that the left context of the expression // being parsed is a statement boundary or an initializer sign '='. // Only such expressions are allowed to reach across newlines // to pull in an LCURLY and appended block. private final int LC_STMT = 1, LC_INIT = 2; /** * Counts the number of LT seen in the typeArguments production. * It is used in semantic predicates to ensure we have seen * enough closing '>' characters; which actually may have been * either GT, SR or BSR tokens. */ private int ltCounter = 0; /* This symbol is used to work around a known ANTLR limitation. * In a loop with syntactic predicate, ANTLR needs help knowing * that the loop exit is a second alternative. * Example usage: ( (LCURLY)=> block | {ANTLR_LOOP_EXIT}? )* * Probably should be an ANTLR RFE. */ ////// Original comment in Java grammar: // Unfortunately a syntactic predicate can only select one of // multiple alternatives on the same level, not break out of // an enclosing loop, which is why this ugly hack (a fake // empty alternative with always-false semantic predicate) // is necessary. private static final boolean ANTLR_LOOP_EXIT = false; } // Compilation Unit: In Groovy, this is a single file or script. This is the start // rule for this parser compilationUnit : // The very first characters of the file may be "#!". If so, ignore the first line. (SH_COMMENT!)? // we can have comments at the top of a file nls! // A compilation unit starts with an optional package definition ( (annotationsOpt "package")=> packageDefinition | (statement[EOF])? ) // The main part of the script is a sequence of any number of statements. // Semicolons and/or significant newlines serve as separators. ( sep! (statement[sepToken])? )* EOF! ; /** A Groovy script or simple expression. Can be anything legal inside {...}. */ snippetUnit : nls! blockBody[EOF] ; // Package statement: optional annotations followed by "package" then the package identifier. packageDefinition {Token first = LT(1);} //TODO? options {defaultErrorHandler = true;} // let ANTLR handle errors : an:annotationsOpt! "package"! id:identifier! {#packageDefinition = #(create(PACKAGE_DEF,"package",first,LT(1)),an,id);} ; // Import statement: import followed by a package or class name importStatement //TODO? options {defaultErrorHandler = true;} { Token first = LT(1); boolean isStatic = false; } : an:annotationsOpt "import"! ( "static"! {isStatic=true;} )? is:identifierStar! {if (isStatic) #importStatement = #(create(STATIC_IMPORT,"static_import",first,LT(1)),an,is); else #importStatement = #(create(IMPORT,"import",first,LT(1)),an,is);} ; // TODO REMOVE // A type definition is either a class, interface, enum or annotation with possible additional semis. //typeDefinition // options {defaultErrorHandler = true;} // : m:modifiers! // typeDefinitionInternal[#m] // | SEMI! // ; // Added this production, even though 'typeDefinition' seems to be obsolete, // as this is referenced by many other parts of the grammar. // Protected type definitions production for reuse in other productions protected typeDefinitionInternal[AST mods] : cd:classDefinition[#mods] // inner class {#typeDefinitionInternal = #cd;} | id:interfaceDefinition[#mods] // inner interface {#typeDefinitionInternal = #id;} | ed:enumDefinition[#mods] // inner enum {#typeDefinitionInternal = #ed;} | ad:annotationDefinition[#mods] // inner annotation {#typeDefinitionInternal = #ad;} ; /** A declaration is the creation of a reference or primitive-type variable, * or (if arguments are present) of a method. * Generically, this is called a 'variable' definition, even in the case of a class field or method. * It may start with the modifiers and/or a declaration keyword "def". * It may also start with the modifiers and a capitalized type name. *

      * AST effect: Create a separate Type/Var tree for each var in the var list. * Must be guarded, as in (declarationStart) => declaration. */ declaration! : // method/variable using a 'def' or a modifier; type is optional m:modifiers (t:typeSpec[false])? v:variableDefinitions[#m, #t] {#declaration = #v;} | // method/variable using a type only t2:typeSpec[false] v2:variableDefinitions[null,#t2] {#declaration = #v2;} ; genericMethod! : // method using a 'def' or a modifier; type is optional m:modifiers p:typeParameters t:typeSpec[false] v:variableDefinitions[#m, #t] { #genericMethod = #v; AST old = #v.getFirstChild(); #genericMethod.setFirstChild(#p); #p.setNextSibling(old); } ; // *TODO* We must also audit the various occurrences of warning // suppressions like "options { greedy = true; }". /** A declaration with one declarator and no initialization, like a parameterDeclaration. * Used to parse loops like for (int x in y) (up to the in keyword). */ singleDeclarationNoInit! : // method/variable using a 'def' or a modifier; type is optional m:modifiers (t:typeSpec[false])? v:singleVariable[#m, #t] {#singleDeclarationNoInit = #v;} | // method/variable using a type only t2:typeSpec[false] v2:singleVariable[null,#t2] {#singleDeclarationNoInit = #v2;} ; /** A declaration with one declarator and optional initialization, like a parameterDeclaration. * Used to parse declarations used for both binding and effect, in places like argument * lists and while statements. */ singleDeclaration : sd:singleDeclarationNoInit! { #singleDeclaration = #sd; } (varInitializer)? ; /** Used only as a lookahead predicate, before diving in and parsing a declaration. * A declaration can be unambiguously introduced with "def", an annotation or a modifier token like "final". * It may also be introduced by a simple identifier whose first character is an uppercase letter, * as in {String x}. A declaration can also be introduced with a built in type like 'int' or 'void'. * Brackets (array and generic) are allowed, as in {List[] x} or {int[][] y}. * Anything else is parsed as a statement of some sort (expression or command). *

      * (In the absence of explicit method-call parens, we assume a capitalized name is a type name. * Yes, this is a little hacky. Alternatives are to complicate the declaration or command * syntaxes, or to have the parser query the symbol table. Parse-time queries are evil. * And we want both {String x} and {println x}. So we need a syntactic razor-edge to slip * between 'println' and 'String'.) * * *TODO* The declarationStart production needs to be strengthened to recognize * things like {List foo}. * Right now it only knows how to skip square brackets after the type, not * angle brackets. * This probably turns out to be tricky because of >> vs. > >. If so, * just put a TODO comment in. */ declarationStart! : ( ("def" nls) | modifier nls | annotation nls | ( upperCaseIdent | builtInType | qualifiedTypeName ) (typeArguments)? (LBRACK balancedTokens RBRACK)* )+ ( IDENT | STRING_LITERAL ) ; /** * lookahead predicate for usage of generics in methods * as parameter for the method. Example: * static T foo(){} * must be first after the modifier. * This rule allows more and does no exact match, but it * is only a lookahead, not the real rule. */ genericMethodStart! : ( "def" nls | modifier nls | annotation nls )+ LT ; qualifiedTypeName! : IDENT DOT (IDENT DOT)* upperCaseIdent ; /** Used to look ahead for a constructor */ constructorStart! : modifiersOpt! id:IDENT! {isConstructorIdent(id)}? nls! LPAREN! //... ; /** Used only as a lookahead predicate for nested type declarations. */ /*TODO* The lookahead in typeDeclarationStart needs to skip annotations, not just stop at '@', because variable and method declarations can also be annotated. > typeDeclarationStart! > : (modifier!)* ("class" | "interface" | "enum" | AT ) S.B. something like > : (modifier! | annotationTokens!)* ("class" | "interface" | > "enum" ) (And maybe @interface, if Java 5 allows nested annotation types? Don't know offhand.) Where annotationTokens can be a quick paren-skipper, as in other places: '@' ident '(' balancedTokens ')'. */ typeDeclarationStart! : modifiersOpt! ("class" | "interface" | "enum" | AT "interface") ; /** An IDENT token whose spelling is required to start with an uppercase letter. * In the case of a simple statement {UpperID name} the identifier is taken to be a type name, not a command name. */ upperCaseIdent : {isUpperCase(LT(1))}? IDENT ; // A type specification is a type name with possible brackets afterwards // (which would make it an array type). // Set addImagNode true for types inside expressions, not declarations. typeSpec[boolean addImagNode] : classTypeSpec[addImagNode] | builtInTypeSpec[addImagNode] ; // also check that 'classOrInterfaceType[false]' is a suitable substitution for 'identifier' // A class type specification is a class type with either: // - possible brackets afterwards // (which would make it an array type). // - generic type arguments after classTypeSpec[boolean addImagNode] {Token first = LT(1);} : ct:classOrInterfaceType[false]! declaratorBrackets[#ct] { if ( addImagNode ) { #classTypeSpec = #(create(TYPE,"TYPE",first,LT(1)), #classTypeSpec); } } ; // A non-built in type name, with possible type parameters classOrInterfaceType[boolean addImagNode] {Token first = LT(1);} : i1:IDENT^ (typeArguments|typeArgumentsDiamond)? ( options{greedy=true;}: // match as many as possible d:DOT! i2:IDENT! (ta:typeArguments!)? {#i1 = #(create(DOT,".",first,LT(1)),i1,i2,ta);} )* { #classOrInterfaceType = #i1; if ( addImagNode ) { #classOrInterfaceType = #(create(TYPE,"TYPE",first,LT(1)), #classOrInterfaceType); } } ; // A specialised form of typeSpec where built in types must be arrays typeArgumentSpec : classTypeSpec[true] | builtInTypeArraySpec[true] ; // A generic type argument is a class type, a possibly bounded wildcard type or a built-in type array typeArgument {Token first = LT(1);} : ( typeArgumentSpec | wildcardType ) {#typeArgument = #(create(TYPE_ARGUMENT,"TYPE_ARGUMENT",first,LT(1)), #typeArgument);} ; // Wildcard type indicating all types (with possible constraint) wildcardType : QUESTION (("extends" | "super")=> typeArgumentBounds)? {#wildcardType.setType(WILDCARD_TYPE);} ; typeArgumentsDiamond {Token first = LT(1);} : LT! GT! nls! ; // Type arguments to a class or interface type typeArguments {Token first = LT(1); int currentLtLevel = 0;} : {currentLtLevel = ltCounter;} LT! {ltCounter++;} nls! typeArgument ( options{greedy=true;}: // match as many as possible {inputState.guessing !=0 || ltCounter == currentLtLevel + 1}? COMMA! nls! typeArgument )* nls! ( // turn warning off since Antlr generates the right code, // plus we have our semantic predicate below options{generateAmbigWarnings=false;}: typeArgumentsOrParametersEnd )? // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel), "Missing closing bracket '>' for generics types", "Please specify the missing bracket!")}? {#typeArguments = #(create(TYPE_ARGUMENTS, "TYPE_ARGUMENTS",first,LT(1)), #typeArguments);} ; // this gobbles up *some* amount of '>' characters, and counts how many // it gobbled. protected typeArgumentsOrParametersEnd : GT! {ltCounter-=1;} | SR! {ltCounter-=2;} | BSR! {ltCounter-=3;} ; // Restriction on wildcard types based on super class or derived class typeArgumentBounds {Token first = LT(1);boolean isUpperBounds = false;} : ( "extends"! {isUpperBounds=true;} | "super"! ) nls! classOrInterfaceType[true] nls! { if (isUpperBounds) { #typeArgumentBounds = #(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1)), #typeArgumentBounds); } else { #typeArgumentBounds = #(create(TYPE_LOWER_BOUNDS,"TYPE_LOWER_BOUNDS",first,LT(1)), #typeArgumentBounds); } } ; // A builtin type array specification is a builtin type with brackets afterwards builtInTypeArraySpec[boolean addImagNode] {Token first = LT(1);} : bt:builtInType! ( (LBRACK)=> // require at least one [] declaratorBrackets[#bt] | {require(false, "primitive type parameters not allowed here", "use the corresponding wrapper type, such as Integer for int" );} ) { if ( addImagNode ) { #builtInTypeArraySpec = #(create(TYPE,"TYPE",first,LT(1)), #builtInTypeArraySpec); } } ; // A builtin type specification is a builtin type with possible brackets // afterwards (which would make it an array type). builtInTypeSpec[boolean addImagNode] {Token first = LT(1);} : bt:builtInType! declaratorBrackets[#bt] { if ( addImagNode ) { #builtInTypeSpec = #(create(TYPE,"TYPE",first,LT(1)), #builtInTypeSpec); } } ; // A type name. which is either a (possibly qualified and parameterized) // class name or a primitive (builtin) type type : classOrInterfaceType[false] | builtInType ; // The primitive types. builtInType : "void" | "boolean" | "byte" | "char" | "short" | "int" | "float" | "long" | "double" ; // A (possibly-qualified) java identifier. We start with the first IDENT // and expand its name by adding dots and following IDENTS identifier {Token first = LT(1);} : i1:IDENT! ( options { greedy = true; } : d:DOT! nls! i2:IDENT! {#i1 = #(create(DOT,".",first,LT(1)),i1,i2);} )* {#identifier = #i1;} ; identifierStar {Token first = LT(1);} : i1:IDENT! ( options { greedy = true; } : d1:DOT! nls! i2:IDENT! {#i1 = #(create(DOT,".",first,LT(1)),i1,i2);} )* ( d2:DOT! nls! s:STAR! {#i1 = #(create(DOT,".",first,LT(1)),i1,s);} | "as"! nls! alias:IDENT! {#i1 = #(create(LITERAL_as,"as",first,LT(1)),i1,alias);} )? {#identifierStar = #i1;} ; modifiersInternal { int seenDef = 0; } : ( // Without this hush, there is a warning that @IDENT and @interface // can follow modifiersInternal. But how is @IDENT possible after // modifiersInternal? And how is @interface possible inside modifiersInternal? // Is there an antlr bug? options{generateAmbigWarnings=false;}: // 'def' is an empty modifier, for disambiguating declarations {seenDef++ == 0}? // do not allow multiple "def" tokens "def"! nls! | // Note: Duplication of modifiers is detected when walking the AST. modifier nls! | {break; /* go out of the ()+ loop*/} AT "interface" | annotation nls! )+ ; /** A list of one or more modifier, annotation, or "def". */ modifiers {Token first = LT(1);} : modifiersInternal {#modifiers = #(create(MODIFIERS, "MODIFIERS",first,LT(1)), #modifiers);} ; /** A list of zero or more modifiers, annotations, or "def". */ modifiersOpt {Token first = LT(1);} : ( // See comment above on hushing warnings. options{generateAmbigWarnings=false;}: modifiersInternal )? {#modifiersOpt = #(create(MODIFIERS, "MODIFIERS",first,LT(1)), #modifiersOpt);} ; // modifiers for Java classes, interfaces, class/instance vars and methods modifier : "private" | "public" | "protected" | "static" | "transient" | "final" | "abstract" | "native" | "threadsafe" | "synchronized" | "volatile" | "strictfp" ; annotation! {Token first = LT(1);} : AT! i:identifier nls! (options{greedy=true;}: LPAREN! ( args:annotationArguments )? RPAREN! )? {#annotation = #(create(ANNOTATION,"ANNOTATION",first,LT(1)), i, args);} ; annotationsInternal : ( options{generateAmbigWarnings=false;}: {break; /* go out of the ()* loop*/} AT "interface" | annotation nls!)* ; annotationsOpt {Token first = LT(1);} : ( // See comment above on hushing warnings. options{generateAmbigWarnings=false;}: annotationsInternal )? {#annotationsOpt = #(create(ANNOTATIONS, "ANNOTATIONS", first, LT(1)), #annotationsOpt);} ; annotationArguments : v:annotationMemberValueInitializer { Token itkn = new Token(IDENT, "value"); AST i; #i = #(create(IDENT, "value", itkn, itkn)); #annotationArguments = #(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",LT(1),LT(1)), i, v);} | annotationMemberValuePairs ; annotationMemberValuePairs : annotationMemberValuePair ( COMMA! nls! annotationMemberValuePair )* ; annotationMemberValuePair! {Token first = LT(1);} : i:annotationIdent ASSIGN! nls! v:annotationMemberValueInitializer {#annotationMemberValuePair = #(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",first,LT(1)), i, v);} ; annotationIdent : IDENT | keywordPropertyNames ; annotationMemberValueInitializer : conditionalExpression[0] | annotation ; /*OBS* // This is an initializer used to set up an annotation member array. annotationMemberArrayInitializer : lc:LCURLY^ {#lc.setType(ANNOTATION_ARRAY_INIT);} ( annotationMemberArrayValueInitializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA! nls! annotationMemberArrayValueInitializer )* (COMMA! nls!)? )? RCURLY! ; *OBS*/ // The two things that can initialize an annotation array element are a conditional expression // and an annotation (nested annotation array initialisers are not valid) annotationMemberArrayValueInitializer : conditionalExpression[0] | annotation nls! ; superClassClause! {Token first = LT(1);} : ( "extends" nls! c:classOrInterfaceType[false] nls! )? {#superClassClause = #(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1)),c);} ; // Definition of a Java class classDefinition![AST modifiers] {Token first = cloneToken(LT(1));AST prevCurrentClass = currentClass; if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); }} : "class" IDENT nls! { currentClass = #IDENT; } // it _might_ have type parameters (tp:typeParameters nls!)? // it _might_ have a superclass... sc:superClassClause // it might implement some interfaces... ic:implementsClause // now parse the body of the class cb:classBlock {#classDefinition = #(create(CLASS_DEF,"CLASS_DEF",first,LT(1)), modifiers,IDENT,tp,sc,ic,cb);} { currentClass = prevCurrentClass; } ; //TODO - where has superClassClause! production gone??? // Definition of a Java Interface interfaceDefinition![AST modifiers] {Token first = cloneToken(LT(1)); if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); }} : "interface" IDENT nls! // it _might_ have type parameters (tp:typeParameters nls!)? // it might extend some other interfaces ie:interfaceExtends // now parse the body of the interface (looks like a class...) ib:interfaceBlock {#interfaceDefinition = #(create(INTERFACE_DEF,"INTERFACE_DEF",first,LT(1)), modifiers,IDENT,tp,ie,ib);} ; enumDefinition![AST modifiers] {Token first = cloneToken(LT(1)); AST prevCurrentClass = currentClass; if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); }} : "enum" IDENT { currentClass = #IDENT; } nls! // it might implement some interfaces... ic:implementsClause nls! // now parse the body of the enum eb:enumBlock {#enumDefinition = #(create(ENUM_DEF,"ENUM_DEF",first,LT(1)), modifiers,IDENT,ic,eb);} { currentClass = prevCurrentClass; } ; annotationDefinition![AST modifiers] {Token first = cloneToken(LT(1)); if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); }} : AT "interface" IDENT // now parse the body of the annotation ab:annotationBlock {#annotationDefinition = #(create(ANNOTATION_DEF,"ANNOTATION_DEF",first,LT(1)), modifiers,IDENT,ab);} ; typeParameters {Token first = LT(1);int currentLtLevel = 0;} : {currentLtLevel = ltCounter;} LT! {ltCounter++;} nls! typeParameter (COMMA! nls! typeParameter)* nls! (typeArgumentsOrParametersEnd)? // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel), "Missing closing bracket '>' for generics types", "Please specify the missing bracket!")}? {#typeParameters = #(create(TYPE_PARAMETERS, "TYPE_PARAMETERS",first,LT(1)), #typeParameters);} ; typeParameter {Token first = LT(1);} : // I'm pretty sure Antlr generates the right thing here: (id:IDENT) ( options{generateAmbigWarnings=false;}: typeParameterBounds )? {#typeParameter = #(create(TYPE_PARAMETER,"TYPE_PARAMETER",first,LT(1)), #typeParameter);} ; typeParameterBounds {Token first = LT(1);} : "extends"! nls! classOrInterfaceType[true] (BAND! nls! classOrInterfaceType[true])* {#typeParameterBounds = #(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1)), #typeParameterBounds);} ; // This is the body of a class. You can have classFields and extra semicolons. classBlock {Token first = LT(1);} : LCURLY! ( classField )? ( sep! ( classField )? )* RCURLY! {#classBlock = #(create(OBJBLOCK, "OBJBLOCK",first,LT(1)), #classBlock);} ; // This is the body of an interface. You can have interfaceField and extra semicolons. interfaceBlock {Token first = LT(1);} : LCURLY! ( interfaceField )? ( sep! ( interfaceField )? )* RCURLY! {#interfaceBlock = #(create(OBJBLOCK, "OBJBLOCK",first,LT(1)), #interfaceBlock);} ; // This is the body of an annotation. You can have annotation fields and extra semicolons, // That's about it (until you see what an annotation field is...) annotationBlock {Token first = LT(1);} : LCURLY! ( annotationField )? ( sep! ( annotationField )? )* RCURLY! {#annotationBlock = #(create(OBJBLOCK, "OBJBLOCK",first,LT(1)), #annotationBlock);} ; // This is the body of an enum. You can have zero or more enum constants // followed by any number of fields like a regular class enumBlock {Token first = LT(1);} : LCURLY! nls! ( // Need a syntactic predicate, since enumConstants // can start with foo() as well as classField. // (It's a true ambiguity, visible in the specification. // To resolve in practice, use "def" before a real method.) (enumConstantsStart) => enumConstants | (classField)? ) ( sep! (classField)? )* RCURLY! {#enumBlock = #(create(OBJBLOCK, "OBJBLOCK",first,LT(1)), #enumBlock);} ; /** Guard for enumConstants. */ enumConstantsStart : annotationsOpt IDENT (LCURLY | LPAREN | nls (SEMI | COMMA | declarationStart | RCURLY)) ; /** Comma-separated list of one or more enum constant definitions. */ enumConstants : enumConstant ( options {generateAmbigWarnings=false;} : (nls (RCURLY | classField)) => { break; /* leave ()* loop */ } | nls! COMMA! ( (nls (RCURLY | classField)) => { break; /* leave ()* loop */ } | (nls annotationsOpt IDENT) => nls! enumConstant ) )* ; // An annotation field annotationField! {Token first = LT(1);} : mods:modifiersOpt! ( td:typeDefinitionInternal[#mods] {#annotationField = #td;} | t:typeSpec[false] // annotation field ( // Need a syntactic predicate, since variableDefinitions // can start with foo() also. Since method defs are not legal // in this context, there's no harm done. (IDENT LPAREN)=> i:IDENT // the name of the field LPAREN! RPAREN! /*OBS* rt:declaratorBrackets[#t] *OBS*/ ( "default" nls! amvi:annotationMemberValueInitializer )? {#annotationField = #(create(ANNOTATION_FIELD_DEF,"ANNOTATION_FIELD_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),t), i,amvi );} | v:variableDefinitions[#mods,#t] // variable {#annotationField = #v;} ) ) ; //An enum constant may have optional parameters and may have a //a class body enumConstant! {Token first = LT(1);} : an:annotationsOpt // Note: Cannot start with "def" or another modifier. i:IDENT ( LPAREN! a:argList RPAREN! )? ( b:enumConstantBlock )? {#enumConstant = #(create(ENUM_CONSTANT_DEF, "ENUM_CONSTANT_DEF",first,LT(1)), an, i, a, b);} ; //The class-like body of an enum constant enumConstantBlock {Token first = LT(1);} : LCURLY! (enumConstantField)? ( sep! (enumConstantField)? )* RCURLY! {#enumConstantBlock = #(create(OBJBLOCK, "OBJBLOCK",first,LT(1)), #enumConstantBlock);} ; //An enum constant field is just like a class field but without //the possibility of a constructor definition or a static initializer // TODO - maybe allow 'declaration' production within this production, // but how to disallow constructors and static initializers... enumConstantField! {Token first = LT(1);} : mods:modifiersOpt! ( td:typeDefinitionInternal[#mods] {#enumConstantField = #td;} | // A generic method has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you wanted. (tp:typeParameters)? t:typeSpec[false] // method or variable declaration(s) ( // Need a syntactic predicate, since variableDefinitions // can start with foo() also. Since method defs are not legal // in this context, there's no harm done. (IDENT LPAREN)=> IDENT // the name of the method // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList RPAREN! /*OBS* rt:declaratorBrackets[#t] *OBS*/ // get the list of exceptions that this method is // declared to throw ((nls "throws") => tc:throwsClause)? ( s2:compoundStatement )? // TODO - verify that 't' is useful/correct here, used to be 'rt' {#enumConstantField = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, tp, #(create(TYPE,"TYPE",first,LT(1)),t), IDENT, param, tc, s2);} | v:variableDefinitions[#mods,#t] {#enumConstantField = #v;} ) ) // "{ ... }" instance initializer | s4:compoundStatement {#enumConstantField = #(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1)), s4);} ; // An interface can extend several other interfaces... interfaceExtends {Token first = LT(1);} : ( e:"extends"! nls! classOrInterfaceType[true] ( COMMA! nls! classOrInterfaceType[true] )* nls! )? {#interfaceExtends = #(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1)), #interfaceExtends);} ; // A class can implement several interfaces... implementsClause {Token first = LT(1);} : ( i:"implements"! nls! classOrInterfaceType[true] ( COMMA! nls! classOrInterfaceType[true] )* nls! )? {#implementsClause = #(create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE",first,LT(1)), #implementsClause);} ; // Now the various things that can be defined inside a class classField! {Token first = LT(1);} : // method, constructor, or variable declaration (constructorStart)=> mc:modifiersOpt! ctor:constructorDefinition[#mc] {#classField = #ctor;} | (genericMethodStart)=> dg:genericMethod {#classField = #dg;} | (multipleAssignmentDeclarationStart)=> mad:multipleAssignmentDeclaration {#classField = #mad;} | (declarationStart)=> dd:declaration {#classField = #dd;} | //TODO - unify typeDeclaration and typeDefinitionInternal names // type declaration (typeDeclarationStart)=> mods:modifiersOpt! ( td:typeDefinitionInternal[#mods] {#classField = #td;} ) // "static { ... }" class initializer | "static" nls! s3:compoundStatement {#classField = #(create(STATIC_INIT,"STATIC_INIT",first,LT(1)), s3);} // "{ ... }" instance initializer | s4:compoundStatement {#classField = #(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1)), s4);} ; // Now the various things that can be defined inside an interface interfaceField! : // method or variable declaration or inner interface (declarationStart)=> d:declaration {#interfaceField = #d;} | (genericMethodStart)=> dg:genericMethod {#interfaceField = #dg;} | //TODO - unify typeDeclaration and typeDefinitionInternal names // type declaration (typeDeclarationStart)=> mods:modifiersOpt ( td:typeDefinitionInternal[#mods] {#interfaceField = #td;} ) ; constructorBody {Token first = LT(1);} : LCURLY! nls! ( (explicitConstructorInvocation) => // Java compatibility hack eci:explicitConstructorInvocation! (sep! bb1:blockBody[sepToken]!)? | bb2:blockBody[EOF]! ) RCURLY! {if (#eci != null) #constructorBody = #(create(SLIST,"{",first,LT(1)),eci,bb1); else #constructorBody = #(create(SLIST,"{",first,LT(1)),bb2);} ; /** Catch obvious constructor calls, but not the expr.super(...) calls */ explicitConstructorInvocation : (typeArguments)? ( "this"! lp1:LPAREN^ argList RPAREN! {#lp1.setType(CTOR_CALL);} | "super"! lp2:LPAREN^ argList RPAREN! {#lp2.setType(SUPER_CTOR_CALL);} ) ; listOfVariables[AST mods, AST t, Token first] : variableDeclarator[getASTFactory().dupTree(mods), getASTFactory().dupTree(t),first] ( COMMA! nls! {first = LT(1);} variableDeclarator[getASTFactory().dupTree(mods), getASTFactory().dupTree(t),first] )* ; multipleAssignmentDeclarationStart : (modifier nls | annotation nls)* "def" nls LPAREN ; typeNamePairs[AST mods, Token first] : (t:typeSpec[false]!)? singleVariable[getASTFactory().dupTree(mods),#t] ( COMMA! nls! {first = LT(1);} (tn:typeSpec[false]!)? singleVariable[getASTFactory().dupTree(mods),#tn] )* ; multipleAssignmentDeclaration {Token first = cloneToken(LT(1));} : mods:modifiers! (t:typeSpec[false]!)? LPAREN^ nls! typeNamePairs[#mods,first] RPAREN! ASSIGN^ nls! assignmentExpression[0] {#multipleAssignmentDeclaration=#(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1)), #mods, #(create(TYPE,"TYPE",first,LT(1)),#t), #multipleAssignmentDeclaration);} ; /** The tail of a declaration. * Either v1, v2, ... (with possible initializers) or else m(args){body}. * The two arguments are the modifier list (if any) and the declaration head (if any). * The declaration head is the variable type, or (for a method) the return type. * If it is missing, then the variable type is taken from its initializer (if there is one). * Otherwise, the variable type defaults to 'any'. * DECIDE: Method return types default to the type of the method body, as an expression. */ variableDefinitions[AST mods, AST t] {Token first = cloneToken(LT(1)); if (mods != null) { first.setLine(mods.getLine()); first.setColumn(mods.getColumn()); } else if (t != null) { first.setLine(t.getLine()); first.setColumn(t.getColumn()); }} : listOfVariables[mods,t,first] | // The parser allows a method definition anywhere a variable definition is accepted. ( id:IDENT | qid:STRING_LITERAL {#qid.setType(IDENT);} // use for operator definitions, etc. ) // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList! RPAREN! /*OBS*rt:declaratorBrackets[#t]*/ // get the list of exceptions that this method is // declared to throw ((nls "throws") => tc:throwsClause! )? // the method body is an open block // but, it may have an optional constructor call (for constructors only) // this constructor clause is only used for constructors using 'def' // which look like method declarations // since the block is optional and nls is part of sep we have to be sure // a newline is followed by a block or ignore the nls too ((nls! LCURLY) => (nlsWarn! mb:openBlock!))? { if (#qid != null) #id = #qid; #variableDefinitions = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),t), id, param, tc, mb); } ; /** I've split out constructors separately; we could maybe integrate back into variableDefinitions * later on if we maybe simplified 'def' to be a type declaration? */ constructorDefinition[AST mods] {Token first = cloneToken(LT(1)); if (mods != null) { first.setLine(mods.getLine()); first.setColumn(mods.getColumn()); }} : id:IDENT // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList! RPAREN! /*OBS*rt:declaratorBrackets[#t]*/ // get the list of exceptions that this method is // declared to throw ((nls "throws") => tc:throwsClause! )? nlsWarn! // the method body is an open block // but, it may have an optional constructor call (for constructors only) // TODO assert that the id matches the class { isConstructorIdent(id); } cb:constructorBody! { #constructorDefinition = #(create(CTOR_IDENT,"CTOR_IDENT",first,LT(1)), mods, param, tc, cb); } ; /** Declaration of a variable. This can be a class/instance variable, * or a local variable in a method * It can also include possible initialization. */ variableDeclarator![AST mods, AST t,Token first] : id:variableName /*OBS*d:declaratorBrackets[t]*/ (v:varInitializer)? {#variableDeclarator = #(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),t), id, v);} ; /** Used in cases where a declaration cannot have commas, or ends with the "in" operator instead of '='. */ singleVariable![AST mods, AST t] {Token first = LT(1);} : id:variableName {#singleVariable = #(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),t), id);} ; variableName : IDENT ; /** After some type names, where zero or more empty bracket pairs are allowed. * We use ARRAY_DECLARATOR to represent this. * TODO: Is there some more Groovy way to view this in terms of the indexed property syntax? */ declaratorBrackets[AST typ] : {#declaratorBrackets=typ;} ( // A following list constructor might conflict with index brackets; prefer the declarator. options {greedy=true;} : LBRACK! RBRACK! {#declaratorBrackets = #(create(ARRAY_DECLARATOR,"[",typ,LT(1)), #declaratorBrackets);} )* ; /** An assignment operator '=' followed by an expression. (Never empty.) */ varInitializer : ASSIGN^ nls! expressionStatementNoCheck // In {T x = y}, the left-context of y is that of an initializer. ; /*OBS* // This is an initializer used to set up an array. arrayInitializer : lc:LCURLY^ {#lc.setType(ARRAY_INIT);} ( initializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA! initializer )* (COMMA!)? )? RCURLY! ; *OBS*/ /*OBS* // Use [...] for initializing all sorts of sequences, including arrays. // The two "things" that can initialize an array element are an expression // and another (nested) array initializer. initializer : expression | arrayInitializer ; *OBS*/ /*OBS??? // This is the header of a method. It includes the name and parameters // for the method. // This also watches for a list of exception classes in a "throws" clause. ctorHead : IDENT // the name of the method // parse the formal parameter declarations. LPAREN! parameterDeclarationList RPAREN! // get the list of exceptions that this method is declared to throw (throwsClause)? ; *OBS*/ // This is a list of exception classes that the method is declared to throw throwsClause : nls! "throws"^ nls! identifier ( COMMA! nls! identifier )* ; /** A list of zero or more formal parameters. * If a parameter is variable length (e.g. String... myArg) it should be * to the right of any other parameters of the same kind. * General form: (req, ..., opt, ..., [rest], key, ..., [restKeys], [block] * This must be sorted out after parsing, since the various declaration forms * are impossible to tell apart without backtracking. */ parameterDeclarationList {Token first = LT(1);} : ( parameterDeclaration ( COMMA! nls! parameterDeclaration )* )? {#parameterDeclarationList = #(create(PARAMETERS,"PARAMETERS",first,LT(1)), #parameterDeclarationList);} ; /** A formal parameter for a method or closure. */ parameterDeclaration! { Token first = LT(1);boolean spreadParam = false; } : pm:parameterModifiersOpt ( options {greedy=true;} : t:typeSpec[false] )? // TODO: What do formal parameters for keyword arguments look like? // Java-style var args ( TRIPLE_DOT! { spreadParam = true; } )? id:IDENT // allow an optional default value expression (exp:varInitializer)? /*OBS*pd:declaratorBrackets[#t]*/ { if (spreadParam) { #parameterDeclaration = #(create(VARIABLE_PARAMETER_DEF,"VARIABLE_PARAMETER_DEF",first,LT(1)), pm, #(create(TYPE,"TYPE",first,LT(1)),t), id, exp); } else { #parameterDeclaration = #(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1)), pm, #(create(TYPE,"TYPE",first,LT(1)),t), id, exp); } } ; /*OBS* variableLengthParameterDeclaration! {Token first = LT(1);} : pm:parameterModifier t:typeSpec[false] TRIPLE_DOT! id:IDENT /*OBS* pd:declaratorBrackets[#t]* / {#variableLengthParameterDeclaration = #(create(VARIABLE_PARAMETER_DEF,"VARIABLE_PARAMETER_DEF",first,LT(1)), pm, #(create(TYPE,"TYPE",first,LT(1)),t), id);} ; *OBS*/ parameterModifiersOpt { Token first = LT(1);int seenDef = 0; } //final and/or def can appear amongst annotations in any order : ( {seenDef++ == 0}? // do not allow multiple "def" tokens "def"! nls! // redundant, but allowed for symmetry | "final" nls! | annotation nls! )* {#parameterModifiersOpt = #(create(MODIFIERS,"MODIFIERS",first,LT(1)), #parameterModifiersOpt);} ; /** Closure parameters are exactly like method parameters, * except that they are not enclosed in parentheses, but rather * are prepended to the front of a block, just after the brace. * They are separated from the closure body by a CLOSABLE_BLOCK_OP token '->'. */ // With '|' there would be restrictions on bitwise-or expressions. closableBlockParamsOpt[boolean addImplicit] : (parameterDeclarationList nls CLOSABLE_BLOCK_OP)=> parameterDeclarationList nls! CLOSABLE_BLOCK_OP! nls! | {addImplicit}? implicitParameters | /* else do not parse any parameters at all */ ; /** Lookahead to check whether a block begins with explicit closure arguments. */ closableBlockParamsStart! : nls parameterDeclarationList nls CLOSABLE_BLOCK_OP ; /** Simple names, as in {x|...}, are completely equivalent to {(def x)|...}. Build the right AST. */ closableBlockParam! {Token first = LT(1);} : id:IDENT! {#closableBlockParam = #(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1)), #(create(MODIFIERS,"MODIFIERS",first,LT(1))), #(create(TYPE,"TYPE",first,LT(1))), id);} ; // Compound statement. This is used in many contexts: // Inside a class definition prefixed with "static": // it is a class initializer // Inside a class definition without "static": // it is an instance initializer // As the body of a method // As a completely independent braced block of code inside a method // it starts a new scope for variable definitions // In Groovy, this is called an "open block". It cannot have closure arguments. compoundStatement : openBlock ; /** An open block is not allowed to have closure arguments. */ openBlock {Token first = LT(1);} : LCURLY! nls! // AST type of SLIST means "never gonna be a closure" bb:blockBody[EOF]! RCURLY! {#openBlock = #(create(SLIST,"{",first,LT(1)),bb);} ; /** A block body is a parade of zero or more statements or expressions. */ blockBody[int prevToken] : (statement[prevToken])? (sep! (statement[sepToken])?)* ; /** A block which is known to be a closure, even if it has no apparent arguments. * A block inside an expression or after a method call is always assumed to be a closure. * Only labeled, unparameterized blocks which occur directly as substatements are kept open. */ closableBlock {Token first = LT(1);} : LCURLY! nls! cbp:closableBlockParamsOpt[true]! bb:blockBody[EOF]! RCURLY! {#closableBlock = #(create(CLOSABLE_BLOCK,"{",first,LT(1)),cbp,bb);} ; /** A block known to be a closure, but which omits its arguments, is given this placeholder. * A subsequent pass is responsible for deciding if there is an implicit 'it' parameter, * or if the parameter list should be empty. */ implicitParameters {Token first = LT(1);} : { #implicitParameters = #(create(IMPLICIT_PARAMETERS,"IMPLICIT_PARAMETERS",first,LT(1))); } ; /** A sub-block of a block can be either open or closable. * It is closable if and only if there are explicit closure arguments. * Compare this to a block which is appended to a method call, * which is given closure arguments, even if they are not explicit in the code. */ openOrClosableBlock {Token first = LT(1);} : LCURLY! nls! cp:closableBlockParamsOpt[false]! bb:blockBody[EOF]! RCURLY! { if (#cp == null) #openOrClosableBlock = #(create(SLIST,"{",first,LT(1)),bb); else #openOrClosableBlock = #(create(CLOSABLE_BLOCK,"{",first,LT(1)),cp,bb); } ; /** A statement is an element of a block. * Typical statements are declarations (which are scoped to the block) * and expressions. */ statement[int prevToken] {boolean sce=false; Token first = LT(1); AST casesGroup_AST = null;} // prevToken is NLS if previous statement is separated only by a newline : (genericMethodStart)=> genericMethod | (multipleAssignmentDeclarationStart)=> multipleAssignmentDeclaration // declarations are ambiguous with "ID DOT" relative to expression // statements. Must backtrack to be sure. Could use a semantic // predicate to test symbol table to see what the type was coming // up, but that's pretty hard without a symbol table ;) | (declarationStart)=> declaration // Attach a label to the front of a statement // This block is executed for effect, unless it has an explicit closure argument. | (IDENT COLON)=> pfx:statementLabelPrefix! {#statement = #pfx;} // nest it all under the label prefix ( (LCURLY) => openOrClosableBlock | statement[COLON] ) // An expression statement. This could be a method call, // assignment statement, or any other expression evaluated for // side-effects. // The prevToken is used to check for dumb expressions like +1. | es:expressionStatement[prevToken] //{#statement = #(create(EXPR,"EXPR",first,LT(1)),es);} // If-else statement | "if"! LPAREN! ale:assignmentLessExpression! RPAREN! nlsWarn! ifCbs:compatibleBodyStatement! ( // CONFLICT: the old "dangling-else" problem... // ANTLR generates proper code matching // as soon as possible. Hush warning. options { warnWhenFollowAmbig = false; } : // lookahead to check if we're entering an 'else' clause ( (sep!)? "else"! )=> (sep!)? // allow SEMI here for compatibility with Java "else"! nlsWarn! elseCbs:compatibleBodyStatement! )? {#statement = #(create(LITERAL_if,"if",first,LT(1)),ale,ifCbs,elseCbs);} // For statement | forStatement // While statement | "while"! LPAREN! sce=while_sce:strictContextExpression[false]! RPAREN! nlsWarn! (s:SEMI! | while_cbs:compatibleBodyStatement!) { if (#s != null) #statement = #(create(LITERAL_while,"Literal_while",first,LT(1)),while_sce,s); else #statement = #(create(LITERAL_while,"Literal_while",first,LT(1)),while_sce,while_cbs); } /*OBS* no do-while statement in Groovy (too ambiguous) // do-while statement | "do"^ statement "while"! LPAREN! strictContextExpression RPAREN! SEMI! *OBS*/ // Import statement. Can be used in any scope. Has "import x as y" also. | (annotationsOpt "import") => importStatement // class definition | m:modifiersOpt! typeDefinitionInternal[#m] // switch/case statement | "switch"! LPAREN! sce=switchSce:strictContextExpression[false]! RPAREN! nlsWarn! LCURLY! nls! ( cg:casesGroup! //expand the list of nodes for each catch statement {casesGroup_AST = #(null,casesGroup_AST,cg);})* RCURLY! {#statement = #(create(LITERAL_switch,"switch",first,LT(1)),switchSce,casesGroup_AST);} // exception try-catch block | tryBlock // synchronize a statement | "synchronized"! LPAREN! sce=synch_sce:strictContextExpression[false]! RPAREN! nlsWarn! synch_cs:compoundStatement! {#statement = #(create(LITERAL_synchronized,"synchronized",first,LT(1)),synch_sce,synch_cs);} /*OBS* // empty statement | s:SEMI {#s.setType(EMPTY_STAT);} *OBS*/ | branchStatement ; forStatement {Token first = LT(1);} : "for"! LPAREN! ( (SEMI |(strictContextExpression[true] SEMI))=>cl:closureList! // *OBS* // There's no need at all for squeezing in the new Java 5 "for" // syntax, since Groovy's is a suitable alternative. // | (parameterDeclaration COLON)=> forEachClause // *OBS* | // the coast is clear; it's a modern Groovy for statement fic:forInClause! ) RPAREN! nls! (s:SEMI! | forCbs:compatibleBodyStatement!) // statement to loop over { if (#cl != null) { if (#s != null) #forStatement = #(create(LITERAL_for,"for",first,LT(1)),cl,s); else #forStatement = #(create(LITERAL_for,"for",first,LT(1)),cl,forCbs); } else { if (#s != null) #forStatement = #(create(LITERAL_for,"for",first,LT(1)),fic,s); else #forStatement = #(create(LITERAL_for,"for",first,LT(1)),fic,forCbs); } } ; closureList {Token first = LT(1); boolean sce=false;} : ( sce=strictContextExpression[true] | {astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT"));} ) ( SEMI! sce=strictContextExpression[true] | SEMI! {astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT"));} )+ {#closureList = #(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1)),#closureList);} ; /*OBS* forEachClause {Token first = LT(1);} : p:parameterDeclaration COLON! expression {#forEachClause = #(create(FOR_EACH_CLAUSE,"FOR_EACH_CLAUSE",first,LT(1)), #forEachClause);} ; *OBS*/ forInClause : ( (declarationStart)=> decl:singleDeclarationNoInit | IDENT ) ( i:"in"^ {#i.setType(FOR_IN_ITERABLE);} shiftExpression[0] | { addWarning( "A colon at this point is legal Java but not recommended in Groovy.", "Use the 'in' keyword." ); require(#decl != null, "Java-style for-each statement requires a type declaration." , "Use the 'in' keyword, as for (x in y) {...}" ); } c:COLON^ {#c.setType(FOR_IN_ITERABLE);} expression[0] ) ; /** In Java, "if", "while", and "for" statements can take random, non-braced statements as their bodies. * Support this practice, even though it isn't very Groovy. */ compatibleBodyStatement : (LCURLY)=> compoundStatement | statement[EOF] ; /** In Groovy, return, break, continue, throw, and assert can be used in a parenthesized expression context. * Example: println (x || (return)); println assert x, "won't print a false value!" * If an optional expression is missing, its value is void (this coerces to null when a value is required). */ branchStatement {Token first = LT(1);} : // Return an expression "return"! ( returnE:expression[0]! )? {#branchStatement = #(create(LITERAL_return,"return",first,LT(1)),returnE);} // break: get out of a loop, or switch, or method call // continue: do next iteration of a loop, or leave a closure | "break"! ( breakI:IDENT! )? {#branchStatement = #(create(LITERAL_break,"break",first,LT(1)),breakI);} | "continue"! ( contI:IDENT! )? {#branchStatement = #(create(LITERAL_continue,"continue",first,LT(1)),contI);} // throw an exception | "throw"! throwE:expression[0]! {#branchStatement = #(create(LITERAL_throw,"throw",first,LT(1)),throwE);} // TODO - decide on definitive 'assert' statement in groovy (1.4 and|or groovy) // asserts // 1.4+ ... // | "assert"^ expression[0] ( COLON! expression[0] )? // groovy assertion... | "assert"! assertAle: assignmentLessExpression! ( options {greedy=true;} : ( COMMA! nls! // TODO: gratuitous change caused failures | COLON! nls! // standard Java syntax, but looks funny in Groovy ) assertE:expression[0]! )? {#branchStatement = #(create(LITERAL_assert,"assert",first,LT(1)),assertAle,assertE);} ; /** A labeled statement, consisting of a vanilla identifier followed by a colon. */ // Note: Always use this lookahead, to keep antlr from panicking: (IDENT COLON)=> statementLabelPrefix : IDENT c:COLON^ {#c.setType(LABELED_STAT);} nls! ; /** An expression statement can be any general expression. *

      * An expression statement can also be a command, * which is a simple method call in which the outermost parentheses are omitted. *

      * Certain "suspicious" looking forms are flagged for the user to disambiguate. */ // DECIDE: A later semantic pass can flag dumb expressions that don't occur in // positions where their value is not used, e.g., {1+1;println} expressionStatement[int prevToken] { Token first = LT(1); } : ( (suspiciousExpressionStatementStart) => checkSuspiciousExpressionStatement[prevToken] )? esn:expressionStatementNoCheck { #expressionStatement = #(create(EXPR, "EXPR", first, LT(1)), #esn); } ; expressionStatementNoCheck { boolean isPathExpr = true; } : // Checks are now out of the way; here's the real rule: head:expression[LC_STMT] { isPathExpr = (#head == lastPathExpression); } ( // A path expression (e.g., System.out.print) can take arguments. {LA(1)!=LITERAL_else && isPathExpr /*&& #head.getType()==METHOD_CALL*/}? cmd:commandArgumentsGreedy[#head]! { #expressionStatementNoCheck = #cmd; } )? ; /** * If two statements are separated by newline (not SEMI), the second had * better not look like the latter half of an expression. If it does, issue a warning. *

      * Also, if the expression starts with a closure, it needs to * have an explicit parameter list, in order to avoid the appearance of a * compound statement. This is a hard error. *

      * These rules are different from Java's "dumb expression" restriction. * Unlike Java, Groovy blocks can end with arbitrary (even dumb) expressions, * as a consequence of optional 'return' and 'continue' tokens. *

      * To make the programmer's intention clear, a leading closure must have an * explicit parameter list, and must not follow a previous statement separated * only by newlines. */ checkSuspiciousExpressionStatement[int prevToken] : (~LCURLY | LCURLY closableBlockParamsStart)=> //FIXME too much lookahead // Either not a block, or a block with an explicit closure parameter list. ( {prevToken == NLS}? { addWarning( "Expression statement looks like it may continue a previous statement", "Either remove the previous newline, or add an explicit semicolon ';'."); } )? | // Else we have a block without any visible closure parameters. {prevToken == NLS}? // if prevToken is NLS, we have double trouble; issue a double warning // Example: obj.foo \n {println x} // Might be appended block: obj.foo {println x} // Might be closure expression: obj.foo ; {x->println x} // Might be open block: obj.foo ; L:{println x} { require(false, "Ambiguous expression could be a parameterless closure expression, "+ "an isolated open code block, or it may continue a previous statement", "Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated "+ "as an open block by giving it a label, e.g. L:{...}, "+ "and also either remove the previous newline, or add an explicit semicolon ';'" ); } | {prevToken != NLS}? // If prevToken is SEMI or something else, issue a single warning: // Example: obj.foo ; {println x} // Might be closure expression: obj.foo ; {x->println x} // Might be open block: obj.foo ; L:{println x} { require(false, "Ambiguous expression could be either a parameterless closure expression or "+ "an isolated open code block", "Add an explicit closure parameter list, e.g. {it -> ...}, or force it to "+ "be treated as an open block by giving it a label, e.g. L:{...}"); } ; /** Lookahead for suspicious statement warnings and errors. */ suspiciousExpressionStatementStart : ( (PLUS | MINUS) | (LBRACK | LPAREN | LCURLY) ) // TODO: Expand this set? ; // Support for switch/case: casesGroup {Token first = LT(1);} : ( // CONFLICT: to which case group do the statements bind? // ANTLR generates proper code: it groups the // many "case"/"default" labels together then // follows them with the statements options { greedy = true; } : aCase )+ caseSList {#casesGroup = #(create(CASE_GROUP, "CASE_GROUP",first,LT(1)), #casesGroup);} ; aCase : ("case"^ expression[0] | "default") COLON! nls! ; caseSList {Token first = LT(1);} : statement[COLON] (sep! (statement[sepToken])?)* {#caseSList = #(create(SLIST,"SLIST",first,LT(1)),#caseSList);} ; // The initializer for a for loop forInit {Token first = LT(1);} : // if it looks like a declaration, it is (declarationStart)=> declaration | // else it's a comma-separated list of expressions (controlExpressionList)? {#forInit = #(create(FOR_INIT,"FOR_INIT",first,LT(1)),#forInit);} ; forCond {Token first = LT(1); boolean sce=false;} : (sce=strictContextExpression[false])? {#forCond = #(create(FOR_CONDITION,"FOR_CONDITION",first,LT(1)),#forCond);} ; forIter {Token first = LT(1);} : (controlExpressionList)? {#forIter = #(create(FOR_ITERATOR,"FOR_ITERATOR",first,LT(1)),#forIter);} ; // an exception handler try/catch block tryBlock {Token first = LT(1);List catchNodes = new ArrayList();AST newHandler_AST = null;} : "try"! nlsWarn! tryCs:compoundStatement! ( options {greedy=true;} : {!(LA(1) == NLS && LA(2) == LPAREN)}? nls! h:handler! //expand the list of nodes for each catch statement {newHandler_AST = #(null,newHandler_AST,h);} )* ( options {greedy=true;} : nls! fc:finallyClause!)? {#tryBlock = #(create(LITERAL_try,"try",first,LT(1)),tryCs,newHandler_AST,fc);} ; finallyClause {Token first = LT(1);} : "finally"! nlsWarn! finallyCs:compoundStatement! {#finallyClause = #(create(LITERAL_finally,"finally",first,LT(1)),finallyCs);} ; // an exception handler handler {Token first = LT(1);} : "catch"! LPAREN! pd:parameterDeclaration! RPAREN! nlsWarn! handlerCs:compoundStatement! {#handler = #(create(LITERAL_catch,"catch",first,LT(1)),pd,handlerCs);} ; /** A member name (x.y) or element name (x[y]) can serve as a command name, * which may be followed by a list of arguments. * Unlike parenthesized arguments, these must be plain expressions, * without labels or spread operators. */ commandArguments[AST head] { Token first = LT(1); } : commandArgument ( options {greedy=true;}: COMMA! nls! commandArgument )* // println 2+2 //OK // println(2+2) //OK // println (2)+2 //BAD // println((2)+2) //OK // (println(2)+2) //OK // compare (2), 2 //BAD // compare( (2), 2 ) //OK // foo.bar baz{bat}, bang{boz} //OK { AST elist = #(create(ELIST,"ELIST",first,LT(1)), #commandArguments); AST headid = #(create(METHOD_CALL,"",first,LT(1)), head, elist); #commandArguments = headid; } ; commandArgumentsGreedy[AST head] { AST prev = #head; } : // argument to the already existing method name ( ({#prev==null || #prev.getType()!=METHOD_CALL}? commandArgument)=> ( first : commandArguments[head]! { #prev = #first; } ) | ) // we start a series of methods and arguments ( options { greedy = true; } : ( options { greedy = true; } : // method name pre:primaryExpression! { #prev = #(create(DOT, ".", #prev), #prev, #pre); } // what follows is either a normal argument, parens, // an appended block, an index operation, or nothing // parens (a b already processed): // a b c() d e -> a(b).c().d(e) // a b c()() d e -> a(b).c().call().d(e) // index (a b already processed): // a b c[x] d e -> a(b).c[x].d(e) // a b c[x][y] d e -> a(b).c[x][y].d(e) // block (a b already processed): // a b c {x} d e -> a(b).c({x}).d(e) // // parens/block completes method call // index makes method call to property get with index // (options {greedy=true;}: (pathElementStart)=> ( pc:pathChain[LC_STMT,#prev]! { #prev = #pc; } ) | ( ca:commandArguments[#prev]! { #prev = #ca; }) )? )* ) { #commandArgumentsGreedy = prev; } ; commandArgument : (argumentLabel COLON nls!) => ( argumentLabel c:COLON^ nls! expression[0] { #c.setType(LABELED_ARG); } ) | expression[0] ; // expressions // Note that most of these expressions follow the pattern // thisLevelExpression : // nextHigherPrecedenceExpression // (OPERATOR nextHigherPrecedenceExpression)* // which is a standard recursive definition for a parsing an expression. // The operators in java have the following precedences: // lowest ( 15) = **= *= /= %= += -= <<= >>= >>>= &= ^= |= // ( 14) ?: (conditional expression and elvis) // ( 13) || // ( 12) && // ( 11) | // ( 10) ^ // ( 9) & // (8.5) =~ ==~ // ( 8) == != <=> === !== // ( 7) < <= > >= instanceof as in // ( 6) << >> .. ..< // ( 5) +(binary) -(binary) // ( 4) * / % // ( 3) **(power) // ( 2) ++(pre) --(pre) +(unary) -(unary) // ( 1) ~ ! $ (type) ++(post) --(post) // . ?. *. (dot -- identifier qualification) // [] () (method call) {} (closableBlock) [] (list/map) // new () (explicit parenthesis) // $x (scope escape) // // the last two are not usually on a precedence chart; I put them in // to point out that new has a higher precedence than '.', so you // can validly use // new Frame().show() // // Note that the above precedence levels map to the rules below... // Once you have a precedence chart, writing the appropriate rules as below // is usually very straightforward // the mother of all expressions // This nonterminal is not used for expression statements, which have a more restricted syntax // due to possible ambiguities with other kinds of statements. This nonterminal is used only // in contexts where we know we have an expression. It allows general Java-type expressions. expression[int lc_stmt] : (LPAREN typeSpec[true] RPAREN expression[lc_stmt])=> lp:LPAREN^ {#lp.setType(TYPECAST);} typeSpec[true] RPAREN! expression[lc_stmt] | (LPAREN nls IDENT (COMMA nls IDENT)* RPAREN ASSIGN) => m:multipleAssignment[lc_stmt] {#expression=#m;} | assignmentExpression[lc_stmt] ; multipleAssignment[int lc_stmt] {Token first = cloneToken(LT(1));} : LPAREN^ nls! listOfVariables[null,null,first] RPAREN! ASSIGN^ nls! assignmentExpression[lc_stmt] ; // This is a list of expressions. // Used for backward compatibility, in a few places where // comma-separated lists of Java expression statements and declarations are required. controlExpressionList {Token first = LT(1); boolean sce=false;} : sce=strictContextExpression[false] (COMMA! nls! sce=strictContextExpression[false])* {#controlExpressionList = #(create(ELIST,"ELIST",first,LT(1)), controlExpressionList);} ; pathChain[int lc_stmt, AST prefix] : ( options { // \n{foo} could match here or could begin a new statement // We do want to match here. Turn off warning. greedy=true; // This turns the ambiguity warning of the second alternative // off. See below. (The "ANTLR_LOOP_EXIT" predicate makes it non-issue) //@@ warnWhenFollowAmbig=false; } // Parsing of this chain is greedy. For example, a pathExpression may be a command name // followed by a command argument, but that command argument cannot begin with an LPAREN, // since a parenthesized expression is greedily attached to the pathExpression as a method argument. // The lookahead is also necessary to reach across newline in foo \n {bar}. // (Apparently antlr's basic approximate LL(k) lookahead is too weak for this.) : (pathElementStart)=> nls! pe:pathElement[prefix]! { prefix = #pe; } | {lc_stmt == LC_STMT || lc_stmt == LC_INIT}? (nls LCURLY)=> nlsWarn! apb:appendedBlock[prefix]! { prefix = #apb; } )+ { #pathChain = prefix; } ; /** A "path expression" is a name or other primary, possibly qualified by various * forms of dot, and/or followed by various kinds of brackets. * It can be used for value or assigned to, or else further qualified, indexed, or called. * It is called a "path" because it looks like a linear path through a data structure. * Examples: x.y, x?.y, x*.y, x.@y; x[], x[y], x[y,z]; x(), x(y), x(y,z); x{s}; a.b[n].c(x).d{s} * (Compare to a C lvalue, or LeftHandSide in the JLS section 15.26.) * General expressions are built up from path expressions, using operators like '+' and '='. */ pathExpression[int lc_stmt] { AST prefix = null; } : pre:primaryExpression! { prefix = #pre; } ( options { // \n{foo} could match here or could begin a new statement // We do want to match here. Turn off warning. greedy=true; // This turns the ambiguity warning of the second alternative // off. See below. (The "ANTLR_LOOP_EXIT" predicate makes it non-issue) //@@ warnWhenFollowAmbig=false; } // Parsing of this chain is greedy. For example, a pathExpression may be a command name // followed by a command argument, but that command argument cannot begin with an LPAREN, // since a parenthesized expression is greedily attached to the pathExpression as a method argument. // The lookahead is also necessary to reach across newline in foo \n {bar}. // (Apparently antlr's basic approximate LL(k) lookahead is too weak for this.) : (pathElementStart)=> nls! pe:pathElement[prefix]! { prefix = #pe; } | {lc_stmt == LC_STMT || lc_stmt == LC_INIT}? (nls LCURLY)=> nlsWarn! apb:appendedBlock[prefix]! { prefix = #apb; } )* { #pathExpression = prefix; lastPathExpression = #pathExpression; } ; pathElement[AST prefix] {Token operator = LT(1);} // The primary can then be followed by a chain of .id, (a), [a], and {...} : { #pathElement = prefix; } ( // Spread operator: x*.y === x?.collect{it.y} SPREAD_DOT! | // Optional-null operator: x?.y === (x==null)?null:x.y OPTIONAL_DOT! | // Member pointer operator: foo.&y == foo.metaClass.getMethodPointer(foo, "y") MEMBER_POINTER! | // The all-powerful dot. (nls! DOT!) ) nls! (ta:typeArguments!)? np:namePart! { #pathElement = #(create(operator.getType(),operator.getText(),prefix,LT(1)),prefix,ta,np); } | mca:methodCallArgs[prefix]! { #pathElement = #mca; } | // Can always append a block, as foo{bar} apb:appendedBlock[prefix]! { #pathElement = #apb; } | // Element selection is always an option, too. // In Groovy, the stuff between brackets is a general argument list, // since the bracket operator is transformed into a method call. ipa:indexPropertyArgs[prefix]! { #pathElement = #ipa; } /* | (DOT nls "this") => DOT! nls! thisPart:"this"! { #pathElement = #(create(operator.getType(),operator.getText(),prefix,LT(1)),prefix,thisPart); } /*NYI* | DOT^ nls! "this" | DOT^ nls! "super" ( // (new Outer()).super() (create enclosing instance) lp3:LPAREN^ argList RPAREN! {#lp3.setType(SUPER_CTOR_CALL);} | DOT^ IDENT ( lps:LPAREN^ {#lps.setType(METHOD_CALL);} argList RPAREN! )? ) | DOT^ nls! newExpression *NYI*/ ; pathElementStart! : (nls! DOT) | SPREAD_DOT | OPTIONAL_DOT | MEMBER_POINTER | LBRACK | LPAREN | LCURLY ; /** This is the grammar for what can follow a dot: x.a, x.@a, x.&a, x.'a', etc. * Note: typeArguments is handled by the caller of namePart. */ namePart {Token first = LT(1);} : ( ats:AT^ {#ats.setType(SELECT_SLOT);} )? // foo.@bar selects the field (or attribute), not property ( IDENT | sl:STRING_LITERAL {#sl.setType(IDENT);} // foo.'bar' is in all ways same as foo.bar, except that bar can have an arbitrary spelling | dynamicMemberName | openBlock // PROPOSAL, DECIDE: Is this inline form of the 'with' statement useful? // Definition: a.{foo} === {with(a) {foo}} // May cover some path expression use-cases previously handled by dynamic scoping (closure delegates). // let's allow common keywords as property names | keywordPropertyNames ) // (No, x.&@y is not needed; just say x.&y as Slot or some such.) ; /* * Allowed keywords after dot (as a member name) and before colon (as a label). * Includes all Java keywords plus "in" and "as". */ keywordPropertyNames : ( "as" | "assert" | "break" | "case" | "catch" | "class" | "const" | "continue" | "def" | "default" | "do" | "else" | "enum" | "extends" | "false" | "finally" | "for" | "goto" | "if" | "implements" | "import" | "in" | "instanceof" | "interface" | "new" | "null" | "package" | "return" | "super" | "switch" | "this" | "throw" | "throws" | "true" | "try" | "while" | modifier | builtInType ) { #keywordPropertyNames.setType(IDENT); } ; /** If a dot is followed by a parenthesized or quoted expression, the member is computed dynamically, * and the member selection is done only at runtime. This forces a statically unchecked member access. */ dynamicMemberName {Token first = LT(1);} : ( pe:parenthesizedExpression! {#dynamicMemberName = #(create(EXPR,"EXPR",first,LT(1)),pe);} | stringConstructorExpression ) { #dynamicMemberName = #(create(DYNAMIC_MEMBER, "DYNAMIC_MEMBER",first,LT(1)), #dynamicMemberName); } ; /** An expression may be followed by one or both of (...) and {...}. * Note: If either is (...) or {...} present, it is a method call. * The {...} is appended to the argument list, and matches a formal of type Closure. * If there is no method member, a property (or field) is used instead, and must itself be callable. *

      * If the methodCallArgs are absent, it is a property reference. * If there is no property, it is treated as a field reference, but never a method reference. *

      * Arguments in the (...) can be labeled, and the appended block can be labeled also. * If there is a mix of unlabeled and labeled arguments, * all the labeled arguments must follow the unlabeled arguments, * except that the closure (labeled or not) is always a separate final argument. * Labeled arguments are collected up and passed as a single argument to a formal of type Map. *

      * Therefore, f(x,y, a:p, b:q) {s} is equivalent in all ways to f(x,y, [a:p,b:q], {s}). * Spread arguments of sequence type count as unlabeled arguments, * while spread arguments of map type count as labeled arguments. * (This distinction must sometimes be checked dynamically.) * * A plain unlabeled argument is allowed to match a trailing Map or Closure argument: * f(x, a:p) {s} === f(*[ x, [a:p], {s} ]) */ // AST is [METHOD_CALL, callee, ELIST? CLOSABLE_BLOCK?]. // Note that callee is often of the form x.y but not always. // If the callee is not of the form x.y, then an implicit .call is needed. // Parameter callee is only "null" when called from newExpression methodCallArgs[AST callee] : LPAREN! al:argList! RPAREN! { if (callee != null && callee.getFirstChild() != null) { //method call like obj.method() #methodCallArgs = #(create(METHOD_CALL, "(",callee.getFirstChild(),LT(1)), callee, al); } else { //method call like method() or new Expr(), in the latter case "callee" is null #methodCallArgs = #(create(METHOD_CALL, "(",callee, LT(1)), callee, al); } } ; /** An appended block follows any expression. * If the expression is not a method call, it is given an empty argument list. */ appendedBlock[AST callee] : /* FIXME DECIDE: should appended blocks accept labels? ( (IDENT COLON nls LCURLY)=> IDENT c:COLON^ {#c.setType(LABELED_ARG);} nls! )? */ cb:closableBlock! { // If the callee is itself a call, flatten the AST. if (callee != null && callee.getType() == METHOD_CALL) { #appendedBlock = #(create(METHOD_CALL, "(",callee,LT(1)), callee.getFirstChild(), cb); } else { #appendedBlock = #(create(METHOD_CALL, "{",callee,LT(1)), callee, cb); } } ; /** An expression may be followed by [...]. * Unlike Java, these brackets may contain a general argument list, * which is passed to the array element operator, which can make of it what it wants. * The brackets may also be empty, as in T[]. This is how Groovy names array types. *

      Returned AST is [INDEX_OP, indexee, ELIST]. */ indexPropertyArgs[AST indexee] : lb:LBRACK al:argList! RBRACK! { if (indexee != null && indexee.getFirstChild() != null) { //expression like obj.index[] #indexPropertyArgs = #(create(INDEX_OP, "INDEX_OP",indexee.getFirstChild(),LT(1)), lb, indexee, al); } else { //expression like obj[] #indexPropertyArgs = #(create(INDEX_OP, "INDEX_OP",indexee,LT(1)), lb, indexee, al); } } ; // assignment expression (level 15) assignmentExpression[int lc_stmt] : conditionalExpression[lc_stmt] ( ( ASSIGN^ | PLUS_ASSIGN^ | MINUS_ASSIGN^ | STAR_ASSIGN^ | DIV_ASSIGN^ | MOD_ASSIGN^ | SR_ASSIGN^ | BSR_ASSIGN^ | SL_ASSIGN^ | BAND_ASSIGN^ | BXOR_ASSIGN^ | BOR_ASSIGN^ | STAR_STAR_ASSIGN^ //| USEROP_13^ //DECIDE: This is how user-define ops would show up. ) nls! expressionStatementNoCheck // If left-context of {x = y} is a statement boundary, // define the left-context of y as an initializer. )? ; // conditional test (level 14) conditionalExpression[int lc_stmt] : logicalOrExpression[lc_stmt] ( (ELVIS_OPERATOR)=> ELVIS_OPERATOR^ nls! conditionalExpression[0] | QUESTION^ nls! assignmentExpression[0] nls! COLON! nls! conditionalExpression[0] )? ; // logical or (||) (level 13) logicalOrExpression[int lc_stmt] : logicalAndExpression[lc_stmt] (LOR^ nls! logicalAndExpression[0])* ; // logical and (&&) (level 12) logicalAndExpression[int lc_stmt] : inclusiveOrExpression[lc_stmt] (LAND^ nls! inclusiveOrExpression[0])* ; // bitwise or non-short-circuiting or (|) (level 11) inclusiveOrExpression[int lc_stmt] : exclusiveOrExpression[lc_stmt] (BOR^ nls! exclusiveOrExpression[0])* ; // exclusive or (^) (level 10) exclusiveOrExpression[int lc_stmt] : andExpression[lc_stmt] (BXOR^ nls! andExpression[0])* ; // bitwise or non-short-circuiting and (&) (level 9) andExpression[int lc_stmt] : regexExpression[lc_stmt] (BAND^ nls! regexExpression[0])* ; // regex find and match (=~ and ==~) (level 8.5) // jez: moved =~ closer to precedence of == etc, as... // 'if (foo =~ "a.c")' is very close in intent to 'if (foo == "abc")' regexExpression[int lc_stmt] : equalityExpression[lc_stmt] ((REGEX_FIND^ | REGEX_MATCH^) nls! equalityExpression[0])* ; // equality/inequality (==/!=) (level 8) equalityExpression[int lc_stmt] : relationalExpression[lc_stmt] ((NOT_EQUAL^ | EQUAL^ |IDENTICAL^ |NOT_IDENTICAL^ | COMPARE_TO^) nls! relationalExpression[0])* ; // boolean relational expressions (level 7) relationalExpression[int lc_stmt] : shiftExpression[lc_stmt] ( options {greedy=true;} : ( ( LT^ | GT^ | LE^ | GE^ | "in"^ ) nls! shiftExpression[0] ) | "instanceof"^ nls! typeSpec[true] | "as"^ nls! typeSpec[true] //TODO: Rework to allow type expression? )? ; // bit shift expressions (level 6) shiftExpression[int lc_stmt] : additiveExpression[lc_stmt] ( ((SL^ | SR^ | BSR^) | RANGE_INCLUSIVE^ | RANGE_EXCLUSIVE^ ) nls! additiveExpression[0] )* ; // binary addition/subtraction (level 5) additiveExpression[int lc_stmt] : multiplicativeExpression[lc_stmt] ( options {greedy=true;} : // Be greedy here, to favor {x+y} instead of {print +value} (PLUS^ | MINUS^) nls! multiplicativeExpression[0] )* ; // multiplication/division/modulo (level 4) multiplicativeExpression[int lc_stmt] : ( INC^ nls! powerExpressionNotPlusMinus[0] ((STAR^ | DIV^ | MOD^ ) nls! powerExpression[0])* ) | ( DEC^ nls! powerExpressionNotPlusMinus[0] ((STAR^ | DIV^ | MOD^ ) nls! powerExpression[0])* ) | ( MINUS^ {#MINUS.setType(UNARY_MINUS);} nls! powerExpressionNotPlusMinus[0] ((STAR^ | DIV^ | MOD^ ) nls! powerExpression[0])* ) | ( PLUS^ {#PLUS.setType(UNARY_PLUS);} nls! powerExpressionNotPlusMinus[0] ((STAR^ | DIV^ | MOD^ ) nls! powerExpression[0])* ) | ( powerExpressionNotPlusMinus[lc_stmt] ((STAR^ | DIV^ | MOD^ ) nls! powerExpression[0])* ) ; // math power operator (**) (level 3) powerExpression[int lc_stmt] : unaryExpression[lc_stmt] (STAR_STAR^ nls! unaryExpression[0])* ; // math power operator (**) (level 3) // (without ++(prefix)/--(prefix)/+(unary)/-(unary)) // The different rules are needed to avoid ambiguous selection // of alternatives. powerExpressionNotPlusMinus[int lc_stmt] : unaryExpressionNotPlusMinus[lc_stmt] (STAR_STAR^ nls! unaryExpression[0])* ; // ++(prefix)/--(prefix)/+(unary)/-(unary) (level 2) unaryExpression[int lc_stmt] : INC^ nls! unaryExpression[0] | DEC^ nls! unaryExpression[0] | MINUS^ {#MINUS.setType(UNARY_MINUS);} nls! unaryExpression[0] | PLUS^ {#PLUS.setType(UNARY_PLUS);} nls! unaryExpression[0] | unaryExpressionNotPlusMinus[lc_stmt] ; // ~(BNOT)/!(LNOT)/(type casting) (level 1) unaryExpressionNotPlusMinus[int lc_stmt] : //BAND^ {#BAND.setType(MEMBER_POINTER_DEFAULT);} nls! namePart //| BNOT^ nls! unaryExpression[0] | LNOT^ nls! unaryExpression[0] | ( // subrule allows option to shut off warnings options { // "(int" ambig with postfixExpr due to lack of sequence // info in linear approximate LL(k). It's ok. Shut up. generateAmbigWarnings=false; } : // If typecast is built in type, must be numeric operand // Have to backtrack to see if operator follows // FIXME: DECIDE: This syntax is wormy. Can we deprecate or remove? (LPAREN builtInTypeSpec[true] RPAREN unaryExpression[0])=> lpb:LPAREN^ {#lpb.setType(TYPECAST);} builtInTypeSpec[true] RPAREN! unaryExpression[0] // Have to backtrack to see if operator follows. If no operator // follows, it's a typecast. No semantic checking needed to parse. // if it _looks_ like a cast, it _is_ a cast; else it's a "(expr)" // FIXME: DECIDE: This syntax is wormy. Can we deprecate or remove? // TODO: Rework this mess for Groovy. | (LPAREN classTypeSpec[true] RPAREN unaryExpressionNotPlusMinus[0])=> lp:LPAREN^ {#lp.setType(TYPECAST);} classTypeSpec[true] RPAREN! unaryExpressionNotPlusMinus[0] | postfixExpression[lc_stmt] ) ; // qualified names, array expressions, method invocation, post inc/dec postfixExpression[int lc_stmt] : pathExpression[lc_stmt] ( options {greedy=true;} : // possibly add on a post-increment or post-decrement. // allows INC/DEC on too much, but semantics can check in:INC^ {#in.setType(POST_INC);} | de:DEC^ {#de.setType(POST_DEC);} )? ; // TODO: Move pathExpression to this point in the file. // the basic element of an expression primaryExpression {Token first = LT(1);} : IDENT /*OBS* //keywords can follow dot in Groovy; no need for this special case ( options {greedy=true;} : DOT^ "class" )? *OBS*/ | constant | newExpression | "this" | "super" | pe:parenthesizedExpression! // (general stuff...) {#primaryExpression = #(create(EXPR,"EXPR",first,LT(1)),pe);} | closableBlockConstructorExpression | listOrMapConstructorExpression | stringConstructorExpression // "foo $bar baz"; presented as multiple tokens //deprecated | scopeEscapeExpression // $x | builtInType /*OBS* //class names work fine as expressions // look for int.class and int[].class | bt:builtInType! declaratorBrackets[bt] DOT^ nls! "class" *OBS*/ ; // Note: This is guaranteed to be an EXPR AST. // That is, parentheses are preserved, in case the walker cares about them. // They are significant sometimes, as in (f(x)){y} vs. f(x){y}. parenthesizedExpression { Token first = LT(1); Token declaration = null; boolean hasClosureList=false; boolean firstContainsDeclaration=false; boolean sce=false; } : LPAREN! { declaration=LT(1); } firstContainsDeclaration = strictContextExpression[true] (SEMI! {hasClosureList=true;} (sce=strictContextExpression[true] | { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); }) )* // if the first expression contained a declaration, // but we are having only one expression at all, then // the first declaration is of the kind (def a=b) // which is invalid. Therefore if there was no closure // list we let the compiler throw an error if the // the first declaration exists { if (firstContainsDeclaration && !hasClosureList) throw new NoViableAltException(declaration, getFilename()); } RPAREN! { if (hasClosureList) { #parenthesizedExpression = #(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1)),#parenthesizedExpression); } } ; /** Things that can show up as expressions, but only in strict * contexts like inside parentheses, argument lists, and list constructors. */ strictContextExpression[boolean allowDeclaration] returns [boolean hasDeclaration=false] {Token first = LT(1);} : ( ({allowDeclaration}? declarationStart)=> {hasDeclaration=true;} singleDeclaration // used for both binding and value, as: while (String xx = nextln()) { println xx } | expression[0] | branchStatement // useful to embed inside expressions (cf. C++ throw) | annotation // creates an annotation value ) // For the sake of the AST walker, mark nodes like this very clearly. {#strictContextExpression = #(create(EXPR,"EXPR",first,LT(1)),#strictContextExpression);} ; assignmentLessExpression {Token first = LT(1);} : ( conditionalExpression[0] ) // For the sake of the AST walker, mark nodes like this very clearly. {#assignmentLessExpression = #(create(EXPR,"EXPR",first,LT(1)),#assignmentLessExpression);} ; closableBlockConstructorExpression : closableBlock ; // Groovy syntax for "$x $y" or /$x $y/. stringConstructorExpression {Token first = LT(1);} : cs:STRING_CTOR_START { #cs.setType(STRING_LITERAL); } stringConstructorValuePart ( cm:STRING_CTOR_MIDDLE { #cm.setType(STRING_LITERAL); } stringConstructorValuePart )* ce:STRING_CTOR_END { #ce.setType(STRING_LITERAL); #stringConstructorExpression = #(create(STRING_CONSTRUCTOR,"STRING_CONSTRUCTOR",first,LT(1)), stringConstructorExpression); } ; stringConstructorValuePart : ( identifier | "this" | "super" | openOrClosableBlock ) ; /** * A list constructor is a argument list enclosed in square brackets, without labels. * Any argument can be decorated with a spread operator (*x), but not a label (a:x). * Examples: [], [1], [1,2], [1,*l1,2], [*l1,*l2]. * (The l1, l2 must be a sequence or null.) *

      * A map constructor is an argument list enclosed in square brackets, with labels everywhere, * except on spread arguments, which stand for whole maps spliced in. * A colon alone between the brackets also forces the expression to be an empty map constructor. * Examples: [:], [a:1], [a:1,b:2], [a:1,*:m1,b:2], [*:m1,*:m2] * (The m1, m2 must be a map or null.) * Values associated with identical keys overwrite from left to right: * [a:1,a:2] === [a:2] *

      * Some malformed constructor expressions are not detected in the parser, but in a post-pass. * Bad examples: [1,b:2], [a:1,2], [:1]. * (Note that method call arguments, by contrast, can be a mix of keyworded and non-keyworded arguments.) */ // The parser allows a mix of labeled and unlabeled arguments, but there must be a semantic check that // the arguments are all labeled (or SPREAD_MAP_ARG) or all unlabeled (and not SPREAD_MAP_ARG). listOrMapConstructorExpression { boolean hasLabels = false; } : lcon:LBRACK! args:argList { hasLabels |= argListHasLabels; } // any argument label implies a map RBRACK! { int type = hasLabels ? MAP_CONSTRUCTOR : LIST_CONSTRUCTOR; #listOrMapConstructorExpression = #(create(type,"[",lcon,LT(1)),args); } | /* Special case: [:] is an empty map constructor. */ emcon:LBRACK^ COLON! RBRACK! {#emcon.setType(MAP_CONSTRUCTOR);} ; /*OBS* /** Match a, a.b.c refs, a.b.c(...) refs, a.b.c[], a.b.c[].class, * and a.b.c.class refs. Also this(...) and super(...). Match * this or super. */ /*OBS* identPrimary : (ta1:typeArguments!)? IDENT // Syntax for method invocation with type arguments is // foo("blah") ( options { // .ident could match here or in postfixExpression. // We do want to match here. Turn off warning. greedy=true; // This turns the ambiguity warning of the second alternative // off. See below. (The "ANTLR_LOOP_EXIT" predicate makes it non-issue) warnWhenFollowAmbig=false; } // we have a new nondeterminism because of // typeArguments... only a syntactic predicate will help... // The problem is that this loop here conflicts with // DOT typeArguments "super" in postfixExpression (k=2) // A proper solution would require a lot of refactoring... : (DOT (typeArguments)? IDENT) => DOT^ (ta2:typeArguments!)? IDENT | {ANTLR_LOOP_EXIT}? //(see documentation above) )* ( options { // ARRAY_DECLARATOR here conflicts with INDEX_OP in // postfixExpression on LBRACK RBRACK. // We want to match [] here, so greedy. This overcomes // limitation of linear approximate lookahead. greedy=true; } : ( lp:LPAREN^ {#lp.setType(METHOD_CALL);} // if the input is valid, only the last IDENT may // have preceding typeArguments... rather hacky, this is... {if (#ta2 != null) astFactory.addASTChild(currentAST, #ta2);} {if (#ta2 == null) astFactory.addASTChild(currentAST, #ta1);} argList RPAREN! ) | ( options {greedy=true;} : lbc:LBRACK^ {#lbc.setType(ARRAY_DECLARATOR);} RBRACK! )+ )? ; *OBS*/ /** object instantiation. * Trees are built as illustrated by the following input/tree pairs: * * new T() * * new * | * T -- ELIST * | * arg1 -- arg2 -- .. -- argn * * new int[] * * new * | * int -- ARRAY_DECLARATOR * * new int[] {1,2} * * new * | * int -- ARRAY_DECLARATOR -- ARRAY_INIT * | * EXPR -- EXPR * | | * 1 2 * * new int[3] * new * | * int -- ARRAY_DECLARATOR * | * EXPR * | * 3 * * new int[1][2] * * new * | * int -- ARRAY_DECLARATOR * | * ARRAY_DECLARATOR -- EXPR * | | * EXPR 1 * | * 2 * */ newExpression {Token first = LT(1);} : "new"! nls! (ta:typeArguments!)? t:type! ( nls! mca:methodCallArgs[null]! ( options { greedy=true; }: cb:classBlock )? {#mca = #mca.getFirstChild(); #newExpression = #(create(LITERAL_new,"new",first,LT(1)),#ta,#t,#mca,#cb);} //java 1.1 // Note: This will allow bad constructs like // new int[4][][3] {exp,exp}. // There needs to be a semantic check here... // to make sure: // a) [ expr ] and [ ] are not mixed // b) [ expr ] and an init are not used together | ad:newArrayDeclarator! //(arrayInitializer)? // Groovy does not support Java syntax for initialized new arrays. // Use sequence constructors instead. {#newExpression = #(create(LITERAL_new,"new",first,LT(1)),#ta,#t,#ad);} ) ; argList { Token first = LT(1); Token lastComma = null; int hls=0, hls2=0; boolean hasClosureList=false; boolean trailingComma=false; boolean sce=false; } : // Note: nls not needed, since we are inside parens, // and those insignificant newlines are suppressed by the lexer. (hls=argument (( ( SEMI! {hasClosureList=true;} ( sce=strictContextExpression[true] | { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); } ) )+ {#argList = #(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1)),#argList);} ) | ( ( {lastComma = LT(1);} COMMA! ( (hls2=argument {hls |= hls2;}) | ( { if (trailingComma) throw new NoViableAltException(lastComma, getFilename()); trailingComma=true; } ) ) )* {#argList = #(create(ELIST,"ELIST",first,LT(1)), argList);} ) ) | ( {#argList = create(ELIST,"ELIST",first,LT(1));} ) ) {argListHasLabels = (hls&1)!=0; } ; /** A single argument in (...) or [...]. Corresponds to to a method or closure parameter. * May be labeled. May be modified by the spread operator '*' ('*:' for keywords). */ argument returns [byte hasLabelOrSpread = 0] {boolean sce=false;} : // Optional argument label. // Usage: Specifies a map key, or a keyworded argument. ( (argumentLabelStart) => argumentLabel c:COLON^ {#c.setType(LABELED_ARG);} { hasLabelOrSpread |= 1; } // signal to caller the presence of a label | // Spread operator: f(*[a,b,c]) === f(a,b,c); f(1,*null,2) === f(1,2). sp:STAR^ {#sp.setType(SPREAD_ARG);} { hasLabelOrSpread |= 2; } // signal to caller the presence of a spread operator // spread maps are marked, as f(*:m) for f(a:x, b:y) if m==[a:x, b:y] ( COLON! {#sp.setType(SPREAD_MAP_ARG);} { hasLabelOrSpread |= 1; } // signal to caller the presence of a label )? )? sce=strictContextExpression[true] { require(LA(1) != COLON, "illegal colon after argument expression", "a complex label expression before a colon must be parenthesized"); } ; /** A label for an argument is of the form a:b, 'a':b, "a":b, (a):b, etc.. * The labels in (a:b), ('a':b), and ("a":b) are in all ways equivalent, * except that the quotes allow more spellings. * Equivalent dynamically computed labels are (('a'):b) and ("${'a'}":b) * but not ((a):b) or "$a":b, since the latter cases evaluate (a) as a normal identifier. * Bottom line: If you want a truly variable label, use parens and say ((a):b). */ argumentLabel : (IDENT) => id:IDENT {#id.setType(STRING_LITERAL);} // identifiers are self-quoting in this context | (keywordPropertyNames) => kw:keywordPropertyNames {#kw.setType(STRING_LITERAL);} // identifiers are self-quoting in this context | primaryExpression // dynamic expression ; /** For lookahead only. Fast approximate parse of an argumentLabel followed by a colon. */ argumentLabelStart! // allow number and string literals as labels for maps : ( IDENT | keywordPropertyNames | constantNumber | STRING_LITERAL | (LPAREN | STRING_CTOR_START)=> balancedBrackets ) COLON ; newArrayDeclarator : ( // CONFLICT: // newExpression is a primaryExpression which can be // followed by an array index reference. This is ok, // as the generated code will stay in this loop as // long as it sees an LBRACK (proper behavior) options { warnWhenFollowAmbig = false; } : lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} (expression[0])? RBRACK! )+ ; /** Numeric, string, regexp, boolean, or null constant. */ constant : constantNumber | STRING_LITERAL | "true" | "false" | "null" ; /** Numeric constant. */ constantNumber : NUM_INT | NUM_FLOAT | NUM_LONG | NUM_DOUBLE | NUM_BIG_INT | NUM_BIG_DECIMAL ; /** Fast lookahead across balanced brackets of all sorts. */ balancedBrackets! : LPAREN balancedTokens RPAREN | LBRACK balancedTokens RBRACK | LCURLY balancedTokens RCURLY | STRING_CTOR_START balancedTokens STRING_CTOR_END ; balancedTokens! : ( balancedBrackets | ~(LPAREN|LBRACK|LCURLY | STRING_CTOR_START |RPAREN|RBRACK|RCURLY | STRING_CTOR_END) )* ; /** A statement separator is either a semicolon or a significant newline. * Any number of additional (insignificant) newlines may accompany it. */ // (All the '!' signs simply suppress the default AST building.) // Returns the type of the separator in this.sepToken, in case it matters. sep! : SEMI! (options { greedy=true; }: NLS!)* { sepToken = SEMI; } | NLS! // this newline is significant! { sepToken = NLS; } ( options { greedy=true; }: SEMI! // this superfluous semicolon is gobbled (options { greedy=true; }: NLS!)* { sepToken = SEMI; } )* ; /** Zero or more insignificant newlines, all gobbled up and thrown away. */ nls! : (options { greedy=true; }: NLS!)? // Note: Use '?' rather than '*', relying on the fact that the lexer collapses // adjacent NLS tokens, always. This lets the parser use its LL(3) lookahead // to "see through" sequences of newlines. If there were a '*' here, the lookahead // would be weaker, since the parser would have to be prepared for long sequences // of NLS tokens. ; /** Zero or more insignificant newlines, all gobbled up and thrown away, * but a warning message is left for the user, if there was a newline. */ nlsWarn! : ( (NLS)=> { addWarning( "A newline at this point does not follow the Groovy Coding Conventions.", "Keep this statement on one line, or use curly braces to break across multiple lines." ); } )? nls! ; //---------------------------------------------------------------------------- // The Groovy scanner //---------------------------------------------------------------------------- class GroovyLexer extends Lexer; options { exportVocab=Groovy; // call the vocabulary "Groovy" testLiterals=false; // don't automatically test for literals k=4; // four characters of lookahead charVocabulary='\u0000'..'\uFFFF'; // without inlining some bitset tests, couldn't do unicode; // I need to make ANTLR generate smaller bitsets; see // bottom of GroovyLexer.java codeGenBitsetTestThreshold=20; } { /** flag for enabling the "assert" keyword */ private boolean assertEnabled = true; /** flag for enabling the "enum" keyword */ private boolean enumEnabled = true; /** flag for including whitespace tokens (for IDE preparsing) */ private boolean whitespaceIncluded = false; /** Enable the "assert" keyword */ public void enableAssert(boolean shouldEnable) { assertEnabled = shouldEnable; } /** Query the "assert" keyword state */ public boolean isAssertEnabled() { return assertEnabled; } /** Enable the "enum" keyword */ public void enableEnum(boolean shouldEnable) { enumEnabled = shouldEnable; } /** Query the "enum" keyword state */ public boolean isEnumEnabled() { return enumEnabled; } /** Include whitespace tokens. Note that this breaks the parser. */ public void setWhitespaceIncluded(boolean z) { whitespaceIncluded = z; } /** Are whitespace tokens included? */ public boolean isWhitespaceIncluded() { return whitespaceIncluded; } { // Initialization actions performed on construction. setTabSize(1); // get rid of special tab interpretation, for IDEs and general clarity } /** Bumped when inside '[x]' or '(x)', reset inside '{x}'. See ONE_NL. */ protected int parenLevel = 0; protected int suppressNewline = 0; // be really mean to newlines inside strings protected static final int SCS_TYPE = 3, SCS_VAL = 4, SCS_LIT = 8, SCS_LIMIT = 16; protected static final int SCS_SQ_TYPE = 0, SCS_TQ_TYPE = 1, SCS_RE_TYPE = 2, SCS_DRE_TYPE = 3; protected int stringCtorState = 0; // hack string and regexp constructor boundaries /** Push parenLevel here and reset whenever inside '{x}'. */ protected ArrayList parenLevelStack = new ArrayList(); protected int lastSigTokenType = EOF; // last returned non-whitespace token public void setTokenObjectClass(String name) {/*ignore*/} protected Token makeToken(int t) { GroovySourceToken tok = new GroovySourceToken(t); tok.setColumn(inputState.getTokenStartColumn()); tok.setLine(inputState.getTokenStartLine()); tok.setColumnLast(inputState.getColumn()); tok.setLineLast(inputState.getLine()); return tok; } protected void pushParenLevel() { parenLevelStack.add(Integer.valueOf(parenLevel*SCS_LIMIT + stringCtorState)); parenLevel = 0; stringCtorState = 0; } protected void popParenLevel() { int npl = parenLevelStack.size(); if (npl == 0) return; int i = ((Integer) parenLevelStack.remove(--npl)).intValue(); parenLevel = i / SCS_LIMIT; stringCtorState = i % SCS_LIMIT; } protected void restartStringCtor(boolean expectLiteral) { if (stringCtorState != 0) { stringCtorState = (expectLiteral? SCS_LIT: SCS_VAL) + (stringCtorState & SCS_TYPE); } } protected boolean allowRegexpLiteral() { return !isExpressionEndingToken(lastSigTokenType); } /** Return true for an operator or punctuation which can end an expression. * Return true for keywords, identifiers, and literals. * Return true for tokens which can end expressions (right brackets, ++, --). * Return false for EOF and all other operator and punctuation tokens. * Used to suppress the recognition of /foo/ as opposed to the simple division operator '/'. */ // Cf. 'constant' and 'balancedBrackets' rules in the grammar.) protected static boolean isExpressionEndingToken(int ttype) { switch (ttype) { case INC: // x++ / y case DEC: // x-- / y case RPAREN: // (x) / y case RBRACK: // f[x] / y case RCURLY: // f{x} / y case STRING_LITERAL: // "x" / y case STRING_CTOR_END: // "$x" / y case NUM_INT: // 0 / y case NUM_FLOAT: // 0f / y case NUM_LONG: // 0l / y case NUM_DOUBLE: // 0.0 / y case NUM_BIG_INT: // 0g / y case NUM_BIG_DECIMAL: // 0.0g / y case IDENT: // x / y // and a bunch of keywords (all of them; no sense picking and choosing): case LITERAL_as: case LITERAL_assert: case LITERAL_boolean: case LITERAL_break: case LITERAL_byte: case LITERAL_case: case LITERAL_catch: case LITERAL_char: case LITERAL_class: case LITERAL_continue: case LITERAL_def: case LITERAL_default: case LITERAL_double: case LITERAL_else: case LITERAL_enum: case LITERAL_extends: case LITERAL_false: case LITERAL_finally: case LITERAL_float: case LITERAL_for: case LITERAL_if: case LITERAL_implements: case LITERAL_import: case LITERAL_in: case LITERAL_instanceof: case LITERAL_int: case LITERAL_interface: case LITERAL_long: case LITERAL_native: case LITERAL_new: case LITERAL_null: case LITERAL_package: case LITERAL_private: case LITERAL_protected: case LITERAL_public: case LITERAL_return: case LITERAL_short: case LITERAL_static: case LITERAL_super: case LITERAL_switch: case LITERAL_synchronized: case LITERAL_this: case LITERAL_threadsafe: case LITERAL_throw: case LITERAL_throws: case LITERAL_transient: case LITERAL_true: case LITERAL_try: case LITERAL_void: case LITERAL_volatile: case LITERAL_while: return true; default: return false; } } protected void newlineCheck(boolean check) throws RecognitionException { if (check && suppressNewline > 0) { require(suppressNewline == 0, "end of line reached within a simple string 'x' or \"x\" or /x/", "for multi-line literals, use triple quotes '''x''' or \"\"\"x\"\"\" or /x/ or $/x/$"); suppressNewline = 0; // shut down any flood of errors } newline(); } protected boolean atValidDollarEscape() throws CharStreamException { // '$' (('*')? ('{' | LETTER)) => int k = 1; char lc = LA(k++); if (lc != '$') return false; lc = LA(k++); if (lc == '*') lc = LA(k++); return (lc == '{' || (lc != '$' && Character.isJavaIdentifierStart(lc))); } protected boolean atDollarDollarEscape() throws CharStreamException { return LA(1) == '$' && LA(2) == '$'; } protected boolean atDollarSlashEscape() throws CharStreamException { return LA(1) == '$' && LA(2) == '/'; } /** This is a bit of plumbing which resumes collection of string constructor bodies, * after an embedded expression has been parsed. * Usage: new GroovyRecognizer(new GroovyLexer(in).plumb()). */ public TokenStream plumb() { return new TokenStream() { public Token nextToken() throws TokenStreamException { if (stringCtorState >= SCS_LIT) { // This goo is modeled upon the ANTLR code for nextToken: int quoteType = (stringCtorState & SCS_TYPE); stringCtorState = 0; // get out of this mode, now resetText(); try { switch (quoteType) { case SCS_SQ_TYPE: mSTRING_CTOR_END(true, /*fromStart:*/false, false); break; case SCS_TQ_TYPE: mSTRING_CTOR_END(true, /*fromStart:*/false, true); break; case SCS_RE_TYPE: mREGEXP_CTOR_END(true, /*fromStart:*/false); break; case SCS_DRE_TYPE: mDOLLAR_REGEXP_CTOR_END(true, /*fromStart:*/false); break; default: throw new AssertionError(false); } lastSigTokenType = _returnToken.getType(); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } Token token = GroovyLexer.this.nextToken(); int lasttype = token.getType(); if (whitespaceIncluded) { switch (lasttype) { // filter out insignificant types case WS: case ONE_NL: case SL_COMMENT: case ML_COMMENT: lasttype = lastSigTokenType; // back up! } } lastSigTokenType = lasttype; return token; } }; } // stuff to adjust ANTLR's tracing machinery public static boolean tracing = false; // only effective if antlr.Tool is run with -traceLexer public void traceIn(String rname) throws CharStreamException { if (!GroovyLexer.tracing) return; super.traceIn(rname); } public void traceOut(String rname) throws CharStreamException { if (!GroovyLexer.tracing) return; if (_returnToken != null) rname += tokenStringOf(_returnToken); super.traceOut(rname); } private static java.util.HashMap ttypes; private static String tokenStringOf(Token t) { if (ttypes == null) { java.util.HashMap map = new java.util.HashMap(); java.lang.reflect.Field[] fields = GroovyTokenTypes.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getType() != int.class) continue; try { map.put(fields[i].get(null), fields[i].getName()); } catch (IllegalAccessException ee) { } } ttypes = map; } Integer tt = Integer.valueOf(t.getType()); Object ttn = ttypes.get(tt); if (ttn == null) ttn = "<"+tt+">"; return "["+ttn+",\""+t.getText()+"\"]"; } protected GroovyRecognizer parser; // little-used link; TODO: get rid of private void require(boolean z, String problem, String solution) throws SemanticException { // TODO: Direct to a common error handler, rather than through the parser. if (!z) parser.requireFailed(problem, solution); } } // TODO: Borneo-style ops. // OPERATORS QUESTION options {paraphrase="'?'";} : '?' ; LPAREN options {paraphrase="'('";} : '(' {++parenLevel;}; RPAREN options {paraphrase="')'";} : ')' {--parenLevel;}; LBRACK options {paraphrase="'['";} : '[' {++parenLevel;}; RBRACK options {paraphrase="']'";} : ']' {--parenLevel;}; LCURLY options {paraphrase="'{'";} : '{' {pushParenLevel();}; RCURLY options {paraphrase="'}'";} : '}' {popParenLevel(); if(stringCtorState!=0) restartStringCtor(true);}; COLON options {paraphrase="':'";} : ':' ; COMMA options {paraphrase="','";} : ',' ; DOT options {paraphrase="'.'";} : '.' ; ASSIGN options {paraphrase="'='";} : '=' ; COMPARE_TO options {paraphrase="'<=>'";} : "<=>" ; EQUAL options {paraphrase="'=='";} : "==" ; IDENTICAL options {paraphrase="'==='";} : "===" ; LNOT options {paraphrase="'!'";} : '!' ; BNOT options {paraphrase="'~'";} : '~' ; NOT_EQUAL options {paraphrase="'!='";} : "!=" ; NOT_IDENTICAL options {paraphrase="'!=='";} : "!==" ; protected //switched from combined rule DIV options {paraphrase="'/'";} : '/' ; protected //switched from combined rule DIV_ASSIGN options {paraphrase="'/='";} : "/=" ; PLUS options {paraphrase="'+'";} : '+' ; PLUS_ASSIGN options {paraphrase="'+='";} : "+=" ; INC options {paraphrase="'++'";} : "++" ; MINUS options {paraphrase="'-'";} : '-' ; MINUS_ASSIGN options {paraphrase="'-='";} : "-=" ; DEC options {paraphrase="'--'";} : "--" ; STAR options {paraphrase="'*'";} : '*' ; STAR_ASSIGN options {paraphrase="'*='";} : "*=" ; MOD options {paraphrase="'%'";} : '%' ; MOD_ASSIGN options {paraphrase="'%='";} : "%=" ; SR options {paraphrase="'>>'";} : ">>" ; SR_ASSIGN options {paraphrase="'>>='";} : ">>=" ; BSR options {paraphrase="'>>>'";} : ">>>" ; BSR_ASSIGN options {paraphrase="'>>>='";} : ">>>=" ; GE options {paraphrase="'>='";} : ">=" ; GT options {paraphrase="'>'";} : ">" ; SL options {paraphrase="'<<'";} : "<<" ; SL_ASSIGN options {paraphrase="'<<='";} : "<<=" ; LE options {paraphrase="'<='";} : "<=" ; LT options {paraphrase="'<'";} : '<' ; BXOR options {paraphrase="'^'";} : '^' ; BXOR_ASSIGN options {paraphrase="'^='";} : "^=" ; BOR options {paraphrase="'|'";} : '|' ; BOR_ASSIGN options {paraphrase="'|='";} : "|=" ; LOR options {paraphrase="'||'";} : "||" ; BAND options {paraphrase="'&'";} : '&' ; BAND_ASSIGN options {paraphrase="'&='";} : "&=" ; LAND options {paraphrase="'&&'";} : "&&" ; SEMI options {paraphrase="';'";} : ';' ; protected DOLLAR options {paraphrase="'$'";} : '$' ; RANGE_INCLUSIVE options {paraphrase="'..'";} : ".." ; RANGE_EXCLUSIVE options {paraphrase="'..<'";} : "..<" ; TRIPLE_DOT options {paraphrase="'...'";} : "..." ; SPREAD_DOT options {paraphrase="'*.'";} : "*." ; OPTIONAL_DOT options {paraphrase="'?.'";} : "?." ; ELVIS_OPERATOR options {paraphrase="'?:'";} : "?:" ; MEMBER_POINTER options {paraphrase="'.&'";} : ".&" ; REGEX_FIND options {paraphrase="'=~'";} : "=~" ; REGEX_MATCH options {paraphrase="'==~'";} : "==~" ; STAR_STAR options {paraphrase="'**'";} : "**" ; STAR_STAR_ASSIGN options {paraphrase="'**='";} : "**=" ; CLOSABLE_BLOCK_OP options {paraphrase="'->'";} : "->" ; // Whitespace -- ignored WS options { paraphrase="whitespace"; } : ( options { greedy=true; }: ' ' | '\t' | '\f' | '\\' ONE_NL[false] )+ { if (!whitespaceIncluded) _ttype = Token.SKIP; } ; protected ONE_NL![boolean check] options { paraphrase="a newline"; } : // handle newlines, which are significant in Groovy ( options {generateAmbigWarnings=false;} : "\r\n" // Evil DOS | '\r' // Macintosh | '\n' // Unix (the right way) ) { // update current line number for error reporting newlineCheck(check); } ; // Group any number of newlines (with comments and whitespace) into a single token. // This reduces the amount of parser lookahead required to parse around newlines. // It is an invariant that the parser never sees NLS tokens back-to-back. NLS options { paraphrase="some newlines, whitespace or comments"; } : ONE_NL[true] ( {!whitespaceIncluded}? (ONE_NL[true] | WS | SL_COMMENT | ML_COMMENT)+ // (gobble, gobble)* )? // Inside (...) and [...] but not {...}, ignore newlines. { if (whitespaceIncluded) { // keep the token as-is } else if (parenLevel != 0) { // when directly inside parens, all newlines are ignored here $setType(Token.SKIP); } else { // inside {...}, newlines must be explicitly matched as 'nls!' $setText(""); } } ; // Single-line comments SL_COMMENT options { paraphrase="a single line comment"; } : "//" ( options { greedy = true; }: // '\uffff' means the EOF character. // This will fix the issue GROOVY-766 (infinite loop). ~('\n'|'\r'|'\uffff') )* { if (!whitespaceIncluded) $setType(Token.SKIP); } //This might be significant, so don't swallow it inside the comment: //ONE_NL ; // Script-header comments SH_COMMENT options { paraphrase="a script header"; } : {getLine() == 1 && getColumn() == 1}? "#!" ( options { greedy = true; }: // '\uffff' means the EOF character. // This will fix the issue GROOVY-766 (infinite loop). ~('\n'|'\r'|'\uffff') )* { if (!whitespaceIncluded) $setType(Token.SKIP); } //ONE_NL //Never a significant newline, but might as well separate it. ; // multiple-line comments ML_COMMENT options { paraphrase="a comment"; } : "/*" ( /* '\r' '\n' can be matched in one alternative or by matching '\r' in one iteration and '\n' in another. I am trying to handle any flavor of newline that comes in, but the language that allows both "\r\n" and "\r" and "\n" to all be valid newline is ambiguous. Consequently, the resulting grammar must be ambiguous. I'm shutting this warning off. */ options { generateAmbigWarnings=false; } : ( '*' ~'/' ) => '*' | ONE_NL[true] | ~('*'|'\n'|'\r'|'\uffff') )* "*/" { if (!whitespaceIncluded) $setType(Token.SKIP); } ; // string literals STRING_LITERAL options { paraphrase="a string literal"; } {int tt=0;} : ("'''") => //...shut off ambiguity warning "'''"! ( STRING_CH | ESC | '"' | '$' | STRING_NL[true] | ('\'' (~'\'' | '\'' ~'\'')) => '\'' // allow 1 or 2 close quotes )* "'''"! | '\''! {++suppressNewline;} ( STRING_CH | ESC | '"' | '$' )* {--suppressNewline;} '\''! | ("\"\"\"") => //...shut off ambiguity warning "\"\"\""! tt=STRING_CTOR_END[true, /*tripleQuote:*/ true] {$setType(tt);} | '"'! {++suppressNewline;} tt=STRING_CTOR_END[true, /*tripleQuote:*/ false] {$setType(tt);} ; protected STRING_CTOR_END[boolean fromStart, boolean tripleQuote] returns [int tt=STRING_CTOR_END] options { paraphrase="a string literal end"; } { boolean dollarOK = false; } : ( options { greedy = true; }: STRING_CH | ESC | '\'' | STRING_NL[tripleQuote] | ('"' (~'"' | '"' ~'"'))=> {tripleQuote}? '"' // allow 1 or 2 close quotes )* ( ( { !tripleQuote }? "\""! | { tripleQuote }? "\"\"\""! ) { if (fromStart) tt = STRING_LITERAL; // plain string literal! if (!tripleQuote) {--suppressNewline;} // done with string constructor! //assert(stringCtorState == 0); } | {dollarOK = atValidDollarEscape();} '$'! { require(dollarOK, "illegal string body character after dollar sign", "either escape a literal dollar sign \"\\$5\" or bracket the value expression \"${5}\""); // Yes, it's a string constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + (tripleQuote? SCS_TQ_TYPE: SCS_SQ_TYPE); } ) { $setType(tt); } ; protected STRING_CH options { paraphrase="a string character"; } : ~('"'|'\''|'\\'|'$'|'\n'|'\r'|'\uffff') ; REGEXP_LITERAL options { paraphrase="a multiline regular expression literal"; } {int tt=0;} : {allowRegexpLiteral()}? '/'! {++suppressNewline;} //Do this, but require it to be non-trivial: REGEXP_CTOR_END[true] // There must be at least one symbol or $ escape, lest the regexp collapse to '//'. // (This should be simpler, but I don't know how to do it w/o ANTLR warnings vs. '//' comments.) ( REGEXP_SYMBOL tt=REGEXP_CTOR_END[true] | {!atValidDollarEscape()}? '$' tt=REGEXP_CTOR_END[true] | '$'! { // Yes, it's a regexp constructor, and we've got a value part. tt = STRING_CTOR_START; stringCtorState = SCS_VAL + SCS_RE_TYPE; } ) {$setType(tt);} | DIV {$setType(DIV);} | DIV_ASSIGN {$setType(DIV_ASSIGN);} ; DOLLAR_REGEXP_LITERAL options { paraphrase="a multiline dollar escaping regular expression literal"; } {int tt=0;} : {allowRegexpLiteral()}? "$/"! // Do this, but require it to be non-trivial: DOLLAR_REGEXP_CTOR_END[true] // There must be at least one symbol or $ escape, otherwise the regexp collapses. ( DOLLAR_REGEXP_SYMBOL tt=DOLLAR_REGEXP_CTOR_END[true] | {!atValidDollarEscape()}? '$' tt=DOLLAR_REGEXP_CTOR_END[true] | '$'! { // Yes, it's a regexp constructor, and we've got a value part. tt = STRING_CTOR_START; stringCtorState = SCS_VAL + SCS_DRE_TYPE; } ) {$setType(tt);} ; protected REGEXP_CTOR_END[boolean fromStart] returns [int tt=STRING_CTOR_END] options { paraphrase="a multiline regular expression literal end"; } : ( options { greedy = true; }: REGEXP_SYMBOL | {!atValidDollarEscape()}? '$' )* ( '/'! { if (fromStart) tt = STRING_LITERAL; // plain regexp literal! {--suppressNewline;} // done with regexp constructor! //assert(stringCtorState == 0); } | '$'! { // Yes, it's a regexp constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + SCS_RE_TYPE; } ) { $setType(tt); } ; protected DOLLAR_REGEXP_CTOR_END[boolean fromStart] returns [int tt=STRING_CTOR_END] options { paraphrase="a multiline dollar escaping regular expression literal end"; } : ( options { greedy = true; }: { !(LA(1) == '/' && LA(2) == '$') }? DOLLAR_REGEXP_SYMBOL | ('$' '/') => ESCAPED_SLASH | ('$' '$') => ESCAPED_DOLLAR | {!atValidDollarEscape() && !atDollarSlashEscape() && !atDollarDollarEscape()}? '$' )* ( "/$"! { if (fromStart) tt = STRING_LITERAL; // plain regexp literal! } | '$'! { // Yes, it's a regexp constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + SCS_DRE_TYPE; } ) { $setType(tt); } ; protected ESCAPED_SLASH : '$' '/' { $setText('/'); }; protected ESCAPED_DOLLAR : '$' '$' { $setText('$'); }; protected REGEXP_SYMBOL options { paraphrase="a multiline regular expression character"; } : ( ~('*'|'/'|'$'|'\\'|'\n'|'\r'|'\uffff') | { LA(2)!='/' && LA(2)!='\n' && LA(2)!='\r' }? '\\' // backslash only escapes '/' and EOL | '\\' '/' { $setText('/'); } | STRING_NL[true] |! '\\' ONE_NL[false] ) ('*')* // stars handled specially to avoid ambig. on /**/ ; protected DOLLAR_REGEXP_SYMBOL options { paraphrase="a multiline dollar escaping regular expression character"; } : ( ~('$' | '\\' | '/' | '\n' | '\r' | '\uffff') | { LA(2)!='\n' && LA(2)!='\r' }? '\\' // backslash only escapes EOL | ('/' ~'$') => '/' // allow a slash if not followed by a $ | STRING_NL[true] |! '\\' ONE_NL[false] ) ; // escape sequence -- note that this is protected; it can only be called // from another lexer rule -- it will not ever directly return a token to // the parser // There are various ambiguities hushed in this rule. The optional // '0'...'9' digit matches should be matched here rather than letting // them go back to STRING_LITERAL to be matched. ANTLR does the // right thing by matching immediately; hence, it's ok to shut off // the FOLLOW ambig warnings. protected ESC options { paraphrase="an escape sequence"; } : '\\'! ( 'n' {$setText("\n");} | 'r' {$setText("\r");} | 't' {$setText("\t");} | 'b' {$setText("\b");} | 'f' {$setText("\f");} | '"' | '\'' | '\\' | '$' //escape Groovy $ operator uniformly also | ('u')+ {$setText("");} HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT {char ch = (char)Integer.parseInt($getText,16); $setText(ch);} | '0'..'3' ( options { warnWhenFollowAmbig = false; } : '0'..'7' ( options { warnWhenFollowAmbig = false; } : '0'..'7' )? )? {char ch = (char)Integer.parseInt($getText,8); $setText(ch);} | '4'..'7' ( options { warnWhenFollowAmbig = false; } : '0'..'7' )? {char ch = (char)Integer.parseInt($getText,8); $setText(ch);} ) |! '\\' ONE_NL[false] ; protected STRING_NL[boolean allowNewline] options { paraphrase="a newline inside a string"; } : {if (!allowNewline) throw new MismatchedCharException('\n', '\n', true, this); } ONE_NL[false] { $setText('\n'); } ; // hexadecimal digit (again, note it's protected!) protected HEX_DIGIT options { paraphrase="a hexadecimal digit"; } : ('0'..'9'|'A'..'F'|'a'..'f') ; // a dummy rule to force vocabulary to be all characters (except special // ones that ANTLR uses internally (0 to 2) protected VOCAB options { paraphrase="a character"; } : '\3'..'\377' ; // an identifier. Note that testLiterals is set to true! This means // that after we match the rule, we look in the literals table to see // if it's a literal or really an identifier IDENT options { paraphrase="an identifier"; } //options {testLiterals=true;} // Actually, this is done manually in the actions below. : ( {stringCtorState == 0}? (DOLLAR|LETTER) (LETTER|DIGIT|DOLLAR)* | LETTER (LETTER|DIGIT)* ) { if (stringCtorState != 0) { if (LA(1) == '.' && LA(2) != '$' && Character.isJavaIdentifierStart(LA(2))) { // pick up another name component before going literal again: restartStringCtor(false); } else { // go back to the string restartStringCtor(true); } } int ttype = testLiteralsTable(IDENT); // Java doesn't have the keywords 'as', 'in' or 'def so we make some allowances // for them in package names for better integration with existing Java packages if ((ttype == LITERAL_as || ttype == LITERAL_def || ttype == LITERAL_in) && (LA(1) == '.' || lastSigTokenType == DOT || lastSigTokenType == LITERAL_package)) { ttype = IDENT; } if (ttype == LITERAL_static && LA(1) == '.') { ttype = IDENT; } /* The grammar allows a few keywords to follow dot. * TODO: Reinstate this logic if we change or remove keywordPropertyNames. if (ttype != IDENT && lastSigTokenType == DOT) { // A few keywords can follow a dot: switch (ttype) { case LITERAL_this: case LITERAL_super: case LITERAL_class: break; default: ttype = LITERAL_in; // the poster child for bad dotted names } } */ $setType(ttype); // check if "assert" keyword is enabled if (assertEnabled && "assert".equals($getText)) { $setType(LITERAL_assert); // set token type for the rule in the parser } // check if "enum" keyword is enabled if (enumEnabled && "enum".equals($getText)) { $setType(LITERAL_enum); // set token type for the rule in the parser } } ; protected LETTER options { paraphrase="a letter"; } : 'a'..'z'|'A'..'Z'|'\u00C0'..'\u00D6'|'\u00D8'..'\u00F6'|'\u00F8'..'\u00FF'|'\u0100'..'\uFFFE'|'_' // TODO: Recognize all the Java identifier starts here (except '$'). ; protected DIGIT options { paraphrase="a digit"; } : '0'..'9' // TODO: Recognize all the Java identifier parts here (except '$'). ; // a numeric literal NUM_INT options { paraphrase="a numeric literal"; } {boolean isDecimal=false; Token t=null;} : /*OBS* '.' {_ttype = DOT;} ( (('0'..'9')+ (EXPONENT)? (f1:FLOAT_SUFFIX {t=f1;})? { if (t != null && t.getText().toUpperCase().indexOf('F')>=0) { _ttype = NUM_FLOAT; } else { _ttype = NUM_DOUBLE; // assume double } }) | // JDK 1.5 token for variable length arguments (".." {_ttype = TRIPLE_DOT;}) )? | *OBS*/ // TODO: This complex pattern seems wrong. Verify or fix. ( '0' {isDecimal = true;} // special case for just '0' ( ('x'|'X') {isDecimal = false;} ( // hex // the 'e'|'E' and float suffix stuff look // like hex digits, hence the (...)+ doesn't // know when to stop: ambig. ANTLR resolves // it correctly by matching immediately. It // is therefor ok to hush warning. options { warnWhenFollowAmbig=false; } : HEX_DIGIT )+ | //float or double with leading zero (('0'..'9')+ ('.'('0'..'9')|EXPONENT|FLOAT_SUFFIX)) => ('0'..'9')+ | ('0'..'7')+ // octal {isDecimal = false;} )? | ('1'..'9') ('0'..'9')* {isDecimal=true;} // non-zero decimal ) ( ('l'|'L') { _ttype = NUM_LONG; } | ('i'|'I') { _ttype = NUM_INT; } | BIG_SUFFIX { _ttype = NUM_BIG_INT; } // only check to see if it's a float if looks like decimal so far | (~'.' | '.' ('0'..'9')) => {isDecimal}? ( '.' ('0'..'9')+ (EXPONENT)? (f2:FLOAT_SUFFIX {t=f2;} | g2:BIG_SUFFIX {t=g2;})? | EXPONENT (f3:FLOAT_SUFFIX {t=f3;} | g3:BIG_SUFFIX {t=g3;})? | f4:FLOAT_SUFFIX {t=f4;} ) { String txt = (t == null ? "" : t.getText().toUpperCase()); if (txt.indexOf('F') >= 0) { _ttype = NUM_FLOAT; } else if (txt.indexOf('G') >= 0) { _ttype = NUM_BIG_DECIMAL; } else { _ttype = NUM_DOUBLE; // assume double } } )? ; // JDK 1.5 token for annotations and their declarations // also a groovy operator for actual field access e.g. 'telson.@age' AT options { paraphrase="'@'"; } : '@' ; // a couple protected methods to assist in matching floating point numbers protected EXPONENT options { paraphrase="an exponent"; } : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; protected FLOAT_SUFFIX options { paraphrase="a float or double suffix"; } : 'f'|'F'|'d'|'D' ; protected BIG_SUFFIX options { paraphrase="a big decimal suffix"; } : 'g'|'G' ; // Note: Please don't use physical tabs. Logical tabs for indent are width 4. // Here's a little hint for you, Emacs: // Local Variables: // tab-width: 4 // mode: antlr-mode // indent-tabs-mode: nil // End: groovy-1.8.6/src/main/org/codehaus/groovy/antlr/AntlrASTProcessSnippets.java0000644001501200150120000000615111707612044026520 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; /** * Process to decorate antlr AST with ending line/col info, and if * possible the snipppet of source from the start/end line/col for each node. * * @author Jeremy Rayner * @version $Revision$ */ import antlr.collections.AST; import java.util.*; public class AntlrASTProcessSnippets implements AntlrASTProcessor{ public AntlrASTProcessSnippets() { } /** * decorate antlr AST with ending line/col info, and if * possible the snipppet of source from the start/end line/col for each node. * @param t the AST to decorate * @return the decorated AST */ public AST process(AST t) { // first visit List l = new ArrayList(); traverse((GroovySourceAST)t,l,null); //System.out.println("l:" + l); // second visit Iterator itr = l.iterator(); if (itr.hasNext()) { itr.next(); /* discard first */ } traverse((GroovySourceAST)t,null,itr); return t; } /** * traverse an AST node * @param t the AST node to traverse * @param l A list to add line/col info to * @param itr An iterator over a list of line/col * @return A decorated AST node */ private void traverse(GroovySourceAST t,List l,Iterator itr) { while (t != null) { // first visit of node if (l != null) { l.add(new LineColumn(t.getLine(),t.getColumn())); } // second visit of node if (itr != null && itr.hasNext()) { LineColumn lc = (LineColumn)itr.next(); if (t.getLineLast() == 0) { int nextLine = lc.getLine(); int nextColumn = lc.getColumn(); if (nextLine < t.getLine() || (nextLine == t.getLine() && nextColumn < t.getColumn())) { nextLine = t.getLine(); nextColumn = t.getColumn(); } t.setLineLast(nextLine); t.setColumnLast(nextColumn); // This is a good point to call t.setSnippet(), // but it bulks up the AST too much for production code. } } GroovySourceAST child = (GroovySourceAST)t.getFirstChild(); if (child != null) { traverse(child,l,itr); } t = (GroovySourceAST)t.getNextSibling(); } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/LineColumn.java0000644001501200150120000000322311627206700024044 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; /** * An object representing a line and column position * * @author Jeremy Rayner * @version $Revision$ */ public class LineColumn { private int line; private int column; public LineColumn(int line, int column) { this.line = line; this.column = column; } public int getLine() { return line; } public int getColumn() { return column; } public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; final LineColumn lineColumn = (LineColumn) that; if (column != lineColumn.column) return false; if (line != lineColumn.line) return false; return true; } public int hashCode() { int result; result = line; result = 29 * result + column; return result; } public String toString() { return "[" + line + "," + column + "]"; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/SourceBuffer.java0000644001501200150120000000752311627206700024400 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import java.util.List; import java.util.ArrayList; /** * A simple buffer that provides line/col access to chunks of source code * held within itself. * * @author Jeremy Rayner * @version $Revision$ */ public class SourceBuffer { private final List lines; private StringBuffer current; public SourceBuffer() { lines = new ArrayList(); //lines.add(new StringBuffer()); // dummy row for position [0] in the List current = new StringBuffer(); lines.add(current); } /** * Obtains a snippet of the source code within the bounds specified * @param start (inclusive line/ inclusive column) * @param end (inclusive line / exclusive column) * @return specified snippet of source code as a String, or null if no source available */ public String getSnippet(LineColumn start, LineColumn end) { // preconditions if (start == null || end == null) { return null; } // no text to return if (start.equals(end)) { return null; } // no text to return if (lines.size() == 1 && current.length() == 0) { return null; } // buffer hasn't been filled yet // working variables int startLine = start.getLine(); int startColumn = start.getColumn(); int endLine = end.getLine(); int endColumn = end.getColumn(); // reset any out of bounds requests if (startLine < 1) { startLine = 1;} if (endLine < 1) { endLine = 1;} if (startColumn < 1) { startColumn = 1;} if (endColumn < 1) { endColumn = 1;} if (startLine > lines.size()) { startLine = lines.size(); } if (endLine > lines.size()) { endLine = lines.size(); } // obtain the snippet from the buffer within specified bounds StringBuffer snippet = new StringBuffer(); for (int i = startLine - 1; i < endLine;i++) { String line = ((StringBuffer)lines.get(i)).toString(); if (startLine == endLine) { // reset any out of bounds requests (again) if (startColumn > line.length()) { startColumn = line.length();} if (startColumn < 1) { startColumn = 1;} if (endColumn > line.length()) { endColumn = line.length() + 1;} if (endColumn < 1) { endColumn = 1;} line = line.substring(startColumn - 1, endColumn - 1); } else { if (i == startLine - 1) { if (startColumn - 1 < line.length()) { line = line.substring(startColumn - 1); } } if (i == endLine - 1) { if (endColumn - 1 < line.length()) { line = line.substring(0,endColumn - 1); } } } snippet.append(line); } return snippet.toString(); } /** * Writes the specified character into the buffer * @param c */ public void write(int c) { if (c != -1) { current.append((char)c); } if (c == '\n') { current = new StringBuffer(); lines.add(current); } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/Main.java0000644001501200150120000001654011627206700022671 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileReader; import org.codehaus.groovy.antlr.parser.GroovyLexer; import org.codehaus.groovy.antlr.parser.GroovyRecognizer; import antlr.ASTFactory; import antlr.CommonAST; import antlr.Token; import antlr.collections.AST; import antlr.debug.misc.ASTFrame; class Main { static boolean whitespaceIncluded = false; static boolean showTree = false; //static boolean xml = false; static boolean verbose = false; public static void main(String[] args) { // Use a try/catch block for parser exceptions try { // if we have at least one command-line argument if (args.length > 0 ) { System.err.println("Parsing..."); // for each directory/file specified on the command line for(int i=0; i< args.length;i++) { if ( args[i].equals("-showtree") ) { showTree = true; } //else if ( args[i].equals("-xml") ) { // xml = true; //} else if ( args[i].equals("-verbose") ) { verbose = true; } else if ( args[i].equals("-trace") ) { GroovyRecognizer.tracing = true; GroovyLexer.tracing = true; } else if ( args[i].equals("-traceParser") ) { GroovyRecognizer.tracing = true; } else if ( args[i].equals("-traceLexer") ) { GroovyLexer.tracing = true; } else if ( args[i].equals("-whitespaceIncluded") ) { whitespaceIncluded = true; } else { doFile(new File(args[i])); // parse it } } } else System.err.println("Usage: java -jar groovyc.jar [-showtree] [-verbose] [-trace{,Lexer,Parser}]"+ ""); } catch(Exception e) { System.err.println("exception: "+e); e.printStackTrace(System.err); // so we can get stack trace } } // This method decides what action to take based on the type of // file we are looking at public static void doFile(File f) throws Exception { // If this is a directory, walk each file/dir in that directory if (f.isDirectory()) { String files[] = f.list(); for(int i=0; i < files.length; i++) doFile(new File(f, files[i])); } // otherwise, if this is a groovy file, parse it! else if (f.getName().endsWith(".groovy")) { System.err.println(" --- "+f.getAbsolutePath()); // parseFile(f.getName(), new FileInputStream(f)); SourceBuffer sourceBuffer = new SourceBuffer(); UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new FileReader(f),sourceBuffer); GroovyLexer lexer = new GroovyLexer(unicodeReader); unicodeReader.setLexer(lexer); parseFile(f.getName(),lexer,sourceBuffer); } } // Here's where we do the real work... public static void parseFile(String f, GroovyLexer l, SourceBuffer sourceBuffer) throws Exception { try { // Create a parser that reads from the scanner GroovyRecognizer parser = GroovyRecognizer.make(l); parser.setSourceBuffer(sourceBuffer); parser.setFilename(f); if (whitespaceIncluded) { GroovyLexer lexer = parser.getLexer(); lexer.setWhitespaceIncluded(true); while (true) { Token t = lexer.nextToken(); System.out.println(t); if (t == null || t.getType() == Token.EOF_TYPE) break; } return; } // start parsing at the compilationUnit rule parser.compilationUnit(); System.out.println("parseFile "+f+" => "+parser.getAST()); // do something with the tree doTreeAction(f, parser.getAST(), parser.getTokenNames()); } catch (Exception e) { System.err.println("parser exception: "+e); e.printStackTrace(); // so we can get stack trace } } public static void doTreeAction(String f, AST t, String[] tokenNames) { if ( t==null ) return; if ( showTree ) { CommonAST.setVerboseStringConversion(true, tokenNames); ASTFactory factory = new ASTFactory(); AST r = factory.create(0,"AST ROOT"); r.setFirstChild(t); final ASTFrame frame = new ASTFrame("Groovy AST", r); frame.setVisible(true); frame.addWindowListener( new WindowAdapter() { public void windowClosing (WindowEvent e) { frame.setVisible(false); // hide the Frame frame.dispose(); System.exit(0); } } ); if (verbose) System.out.println(t.toStringList()); } /*if ( xml ) { ((CommonAST)t).setVerboseStringConversion(true, tokenNames); ASTFactory factory = new ASTFactory(); AST r = factory.create(0,"AST ROOT"); r.setFirstChild(t); XStream xstream = new XStream(); xstream.alias("ast", CommonAST.class); try { xstream.toXML(r,new FileWriter(f + ".xml")); System.out.println("Written AST to " + f + ".xml"); } catch (Exception e) { System.out.println("couldn't write to " + f + ".xml"); e.printStackTrace(); } //if (verbose) System.out.println(t.toStringList()); }*/ /*@todo GroovyTreeParser tparse = new GroovyTreeParser(); try { tparse.compilationUnit(t); if (verbose) System.out.println("successful walk of result AST for "+f); } catch (RecognitionException e) { System.err.println(e.getMessage()); e.printStackTrace(); } @todo*/ } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/UnicodeLexerSharedInputState.java0000644001501200150120000000276111645141222027540 0ustar miguelmiguel/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.LexerSharedInputState; /** * GRECLIPSE-805 Support for unicode escape sequences * @author Andrew Eisenberg */ public class UnicodeLexerSharedInputState extends LexerSharedInputState { private final UnicodeEscapingReader escapingReader; private int prevUnescape; public UnicodeLexerSharedInputState(UnicodeEscapingReader in) { super(in); escapingReader = in; } @Override public int getColumn() { prevUnescape = escapingReader.getUnescapedUnicodeColumnCount(); return super.getColumn() + prevUnescape; } @Override public int getTokenStartColumn() { if (line == tokenStartLine) { return super.getTokenStartColumn() + escapingReader.getUnescapedUnicodeColumnCount(); } else { return super.getTokenStartColumn() + prevUnescape; } } }groovy-1.8.6/src/main/org/codehaus/groovy/antlr/AntlrParserPluginFactory.java0000644001501200150120000000167511627206700026754 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import org.codehaus.groovy.control.ParserPlugin; import org.codehaus.groovy.control.ParserPluginFactory; /** * @version $Revision$ */ public class AntlrParserPluginFactory extends ParserPluginFactory { public ParserPlugin createParserPlugin() { return new AntlrParserPlugin(); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/0000755001501200150120000000000011715044504022055 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/Java2GroovyConverter.java0000644001501200150120000003504711713765676027014 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import org.codehaus.groovy.antlr.treewalker.VisitorAdapter; public class Java2GroovyConverter extends VisitorAdapter{ private String[] tokenNames; private int[] typeMapping; public Java2GroovyConverter(String[] tokenNames) { this.tokenNames = tokenNames; typeMapping = new int[400]; // magic number, much greater than current number of java tokens typeMapping[JavaTokenTypes.ABSTRACT] = GroovyTokenTypes.ABSTRACT; typeMapping[JavaTokenTypes.EOF] = GroovyTokenTypes.EOF; typeMapping[JavaTokenTypes.NULL_TREE_LOOKAHEAD] = GroovyTokenTypes.NULL_TREE_LOOKAHEAD; typeMapping[JavaTokenTypes.BLOCK] = GroovyTokenTypes.BLOCK; typeMapping[JavaTokenTypes.MODIFIERS] = GroovyTokenTypes.MODIFIERS; typeMapping[JavaTokenTypes.OBJBLOCK] = GroovyTokenTypes.OBJBLOCK; typeMapping[JavaTokenTypes.SLIST] = GroovyTokenTypes.SLIST; typeMapping[JavaTokenTypes.METHOD_DEF] = GroovyTokenTypes.METHOD_DEF; typeMapping[JavaTokenTypes.VARIABLE_DEF] = GroovyTokenTypes.VARIABLE_DEF; typeMapping[JavaTokenTypes.INSTANCE_INIT] = GroovyTokenTypes.INSTANCE_INIT; typeMapping[JavaTokenTypes.STATIC_INIT] = GroovyTokenTypes.STATIC_INIT; typeMapping[JavaTokenTypes.TYPE] = GroovyTokenTypes.TYPE; typeMapping[JavaTokenTypes.CLASS_DEF] = GroovyTokenTypes.CLASS_DEF; typeMapping[JavaTokenTypes.INTERFACE_DEF] = GroovyTokenTypes.INTERFACE_DEF; typeMapping[JavaTokenTypes.PACKAGE_DEF] = GroovyTokenTypes.PACKAGE_DEF; typeMapping[JavaTokenTypes.ARRAY_DECLARATOR] = GroovyTokenTypes.ARRAY_DECLARATOR; typeMapping[JavaTokenTypes.EXTENDS_CLAUSE] = GroovyTokenTypes.EXTENDS_CLAUSE; typeMapping[JavaTokenTypes.IMPLEMENTS_CLAUSE] = GroovyTokenTypes.IMPLEMENTS_CLAUSE; typeMapping[JavaTokenTypes.PARAMETERS] = GroovyTokenTypes.PARAMETERS; typeMapping[JavaTokenTypes.PARAMETER_DEF] = GroovyTokenTypes.PARAMETER_DEF; typeMapping[JavaTokenTypes.LABELED_STAT] = GroovyTokenTypes.LABELED_STAT; typeMapping[JavaTokenTypes.TYPECAST] = GroovyTokenTypes.TYPECAST; typeMapping[JavaTokenTypes.INDEX_OP] = GroovyTokenTypes.INDEX_OP; typeMapping[JavaTokenTypes.POST_INC] = GroovyTokenTypes.POST_INC; typeMapping[JavaTokenTypes.POST_DEC] = GroovyTokenTypes.POST_DEC; typeMapping[JavaTokenTypes.METHOD_CALL] = GroovyTokenTypes.METHOD_CALL; typeMapping[JavaTokenTypes.EXPR] = GroovyTokenTypes.EXPR; typeMapping[JavaTokenTypes.ARRAY_INIT] = GroovyTokenTypes.LIST_CONSTRUCTOR; // this assumes LIST_CONSTRUCTOR set by PreJava2GroovyConvertor typeMapping[JavaTokenTypes.IMPORT] = GroovyTokenTypes.IMPORT; typeMapping[JavaTokenTypes.UNARY_MINUS] = GroovyTokenTypes.UNARY_MINUS; typeMapping[JavaTokenTypes.UNARY_PLUS] = GroovyTokenTypes.UNARY_PLUS; typeMapping[JavaTokenTypes.CASE_GROUP] = GroovyTokenTypes.CASE_GROUP; typeMapping[JavaTokenTypes.ELIST] = GroovyTokenTypes.ELIST; typeMapping[JavaTokenTypes.FOR_INIT] = GroovyTokenTypes.FOR_INIT; typeMapping[JavaTokenTypes.FOR_CONDITION] = GroovyTokenTypes.FOR_CONDITION; typeMapping[JavaTokenTypes.FOR_ITERATOR] = GroovyTokenTypes.FOR_ITERATOR; typeMapping[JavaTokenTypes.EMPTY_STAT] = GroovyTokenTypes.EMPTY_STAT; typeMapping[JavaTokenTypes.FINAL] = GroovyTokenTypes.FINAL; typeMapping[JavaTokenTypes.ABSTRACT] = GroovyTokenTypes.ABSTRACT; typeMapping[JavaTokenTypes.STRICTFP] = GroovyTokenTypes.STRICTFP; typeMapping[JavaTokenTypes.SUPER_CTOR_CALL] = GroovyTokenTypes.SUPER_CTOR_CALL; typeMapping[JavaTokenTypes.CTOR_CALL] = GroovyTokenTypes.CTOR_CALL; typeMapping[JavaTokenTypes.VARIABLE_PARAMETER_DEF] = GroovyTokenTypes.VARIABLE_PARAMETER_DEF; typeMapping[JavaTokenTypes.STATIC_IMPORT] = GroovyTokenTypes.STATIC_IMPORT; typeMapping[JavaTokenTypes.ENUM_DEF] = GroovyTokenTypes.ENUM_DEF; typeMapping[JavaTokenTypes.ENUM_CONSTANT_DEF] = GroovyTokenTypes.ENUM_CONSTANT_DEF; typeMapping[JavaTokenTypes.FOR_EACH_CLAUSE] = GroovyTokenTypes.FOR_EACH_CLAUSE; typeMapping[JavaTokenTypes.ANNOTATION_DEF] = GroovyTokenTypes.ANNOTATION_DEF; typeMapping[JavaTokenTypes.ANNOTATIONS] = GroovyTokenTypes.ANNOTATIONS; typeMapping[JavaTokenTypes.ANNOTATION] = GroovyTokenTypes.ANNOTATION; typeMapping[JavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR] = GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR; typeMapping[JavaTokenTypes.ANNOTATION_FIELD_DEF] = GroovyTokenTypes.ANNOTATION_FIELD_DEF; typeMapping[JavaTokenTypes.ANNOTATION_ARRAY_INIT] = GroovyTokenTypes.ANNOTATION_ARRAY_INIT; typeMapping[JavaTokenTypes.TYPE_ARGUMENTS] = GroovyTokenTypes.TYPE_ARGUMENTS; typeMapping[JavaTokenTypes.TYPE_ARGUMENT] = GroovyTokenTypes.TYPE_ARGUMENT; typeMapping[JavaTokenTypes.TYPE_PARAMETERS] = GroovyTokenTypes.TYPE_PARAMETERS; typeMapping[JavaTokenTypes.TYPE_PARAMETER] = GroovyTokenTypes.TYPE_PARAMETER; typeMapping[JavaTokenTypes.WILDCARD_TYPE] = GroovyTokenTypes.WILDCARD_TYPE; typeMapping[JavaTokenTypes.TYPE_UPPER_BOUNDS] = GroovyTokenTypes.TYPE_UPPER_BOUNDS; typeMapping[JavaTokenTypes.TYPE_LOWER_BOUNDS] = GroovyTokenTypes.TYPE_LOWER_BOUNDS; typeMapping[JavaTokenTypes.LITERAL_package] = GroovyTokenTypes.LITERAL_package; typeMapping[JavaTokenTypes.SEMI] = GroovyTokenTypes.SEMI; typeMapping[JavaTokenTypes.LITERAL_import] = GroovyTokenTypes.LITERAL_import; typeMapping[JavaTokenTypes.LITERAL_static] = GroovyTokenTypes.LITERAL_static; typeMapping[JavaTokenTypes.LBRACK] = GroovyTokenTypes.LBRACK; typeMapping[JavaTokenTypes.RBRACK] = GroovyTokenTypes.RBRACK; typeMapping[JavaTokenTypes.IDENT] = GroovyTokenTypes.IDENT; typeMapping[JavaTokenTypes.DOT] = GroovyTokenTypes.DOT; typeMapping[JavaTokenTypes.QUESTION] = GroovyTokenTypes.QUESTION; typeMapping[JavaTokenTypes.LITERAL_extends] = GroovyTokenTypes.LITERAL_extends; typeMapping[JavaTokenTypes.LITERAL_super] = GroovyTokenTypes.LITERAL_super; typeMapping[JavaTokenTypes.LT] = GroovyTokenTypes.LT; typeMapping[JavaTokenTypes.COMMA] = GroovyTokenTypes.COMMA; typeMapping[JavaTokenTypes.GT] = GroovyTokenTypes.GT; typeMapping[JavaTokenTypes.SR] = GroovyTokenTypes.SR; typeMapping[JavaTokenTypes.BSR] = GroovyTokenTypes.BSR; typeMapping[JavaTokenTypes.LITERAL_void] = GroovyTokenTypes.LITERAL_void; typeMapping[JavaTokenTypes.LITERAL_boolean] = GroovyTokenTypes.LITERAL_boolean; typeMapping[JavaTokenTypes.LITERAL_byte] = GroovyTokenTypes.LITERAL_byte; typeMapping[JavaTokenTypes.LITERAL_char] = GroovyTokenTypes.LITERAL_char; typeMapping[JavaTokenTypes.LITERAL_short] = GroovyTokenTypes.LITERAL_short; typeMapping[JavaTokenTypes.LITERAL_int] = GroovyTokenTypes.LITERAL_int; typeMapping[JavaTokenTypes.LITERAL_float] = GroovyTokenTypes.LITERAL_float; typeMapping[JavaTokenTypes.LITERAL_long] = GroovyTokenTypes.LITERAL_long; typeMapping[JavaTokenTypes.LITERAL_double] = GroovyTokenTypes.LITERAL_double; typeMapping[JavaTokenTypes.STAR] = GroovyTokenTypes.STAR; typeMapping[JavaTokenTypes.LITERAL_private] = GroovyTokenTypes.LITERAL_private; typeMapping[JavaTokenTypes.LITERAL_public] = GroovyTokenTypes.LITERAL_public; typeMapping[JavaTokenTypes.LITERAL_protected] = GroovyTokenTypes.LITERAL_protected; typeMapping[JavaTokenTypes.LITERAL_transient] = GroovyTokenTypes.LITERAL_transient; typeMapping[JavaTokenTypes.LITERAL_native] = GroovyTokenTypes.LITERAL_native; typeMapping[JavaTokenTypes.LITERAL_threadsafe] = GroovyTokenTypes.LITERAL_threadsafe; typeMapping[JavaTokenTypes.LITERAL_synchronized] = GroovyTokenTypes.LITERAL_synchronized; typeMapping[JavaTokenTypes.LITERAL_volatile] = GroovyTokenTypes.LITERAL_volatile; typeMapping[JavaTokenTypes.AT] = GroovyTokenTypes.AT; typeMapping[JavaTokenTypes.LPAREN] = GroovyTokenTypes.LPAREN; typeMapping[JavaTokenTypes.RPAREN] = GroovyTokenTypes.RPAREN; typeMapping[JavaTokenTypes.ASSIGN] = GroovyTokenTypes.ASSIGN; typeMapping[JavaTokenTypes.LCURLY] = GroovyTokenTypes.LCURLY; typeMapping[JavaTokenTypes.RCURLY] = GroovyTokenTypes.RCURLY; typeMapping[JavaTokenTypes.LITERAL_class] = GroovyTokenTypes.LITERAL_class; typeMapping[JavaTokenTypes.LITERAL_interface] = GroovyTokenTypes.LITERAL_interface; typeMapping[JavaTokenTypes.LITERAL_enum] = GroovyTokenTypes.LITERAL_enum; typeMapping[JavaTokenTypes.BAND] = GroovyTokenTypes.BAND; typeMapping[JavaTokenTypes.LITERAL_default] = GroovyTokenTypes.LITERAL_default; typeMapping[JavaTokenTypes.LITERAL_implements] = GroovyTokenTypes.LITERAL_implements; typeMapping[JavaTokenTypes.LITERAL_this] = GroovyTokenTypes.LITERAL_this; typeMapping[JavaTokenTypes.LITERAL_throws] = GroovyTokenTypes.LITERAL_throws; typeMapping[JavaTokenTypes.TRIPLE_DOT] = GroovyTokenTypes.TRIPLE_DOT; typeMapping[JavaTokenTypes.COLON] = GroovyTokenTypes.COLON; typeMapping[JavaTokenTypes.LITERAL_if] = GroovyTokenTypes.LITERAL_if; typeMapping[JavaTokenTypes.LITERAL_else] = GroovyTokenTypes.LITERAL_else; typeMapping[JavaTokenTypes.LITERAL_while] = GroovyTokenTypes.LITERAL_while; typeMapping[JavaTokenTypes.LITERAL_do] = GroovyTokenTypes.LITERAL_while; // warning - do...while... ignored typeMapping[JavaTokenTypes.LITERAL_break] = GroovyTokenTypes.LITERAL_break; typeMapping[JavaTokenTypes.LITERAL_continue] = GroovyTokenTypes.LITERAL_continue; typeMapping[JavaTokenTypes.LITERAL_return] = GroovyTokenTypes.LITERAL_return; typeMapping[JavaTokenTypes.LITERAL_switch] = GroovyTokenTypes.LITERAL_switch; typeMapping[JavaTokenTypes.LITERAL_throw] = GroovyTokenTypes.LITERAL_throw; typeMapping[JavaTokenTypes.LITERAL_assert] = GroovyTokenTypes.LITERAL_assert; typeMapping[JavaTokenTypes.LITERAL_for] = GroovyTokenTypes.LITERAL_for; typeMapping[JavaTokenTypes.LITERAL_case] = GroovyTokenTypes.LITERAL_case; typeMapping[JavaTokenTypes.LITERAL_try] = GroovyTokenTypes.LITERAL_try; typeMapping[JavaTokenTypes.LITERAL_finally] = GroovyTokenTypes.LITERAL_finally; typeMapping[JavaTokenTypes.LITERAL_catch] = GroovyTokenTypes.LITERAL_catch; typeMapping[JavaTokenTypes.PLUS_ASSIGN] = GroovyTokenTypes.PLUS_ASSIGN; typeMapping[JavaTokenTypes.MINUS_ASSIGN] = GroovyTokenTypes.MINUS_ASSIGN; typeMapping[JavaTokenTypes.STAR_ASSIGN] = GroovyTokenTypes.STAR_ASSIGN; typeMapping[JavaTokenTypes.DIV_ASSIGN] = GroovyTokenTypes.DIV_ASSIGN; typeMapping[JavaTokenTypes.MOD_ASSIGN] = GroovyTokenTypes.MOD_ASSIGN; typeMapping[JavaTokenTypes.SR_ASSIGN] = GroovyTokenTypes.SR_ASSIGN; typeMapping[JavaTokenTypes.BSR_ASSIGN] = GroovyTokenTypes.BSR_ASSIGN; typeMapping[JavaTokenTypes.SL_ASSIGN] = GroovyTokenTypes.SL_ASSIGN; typeMapping[JavaTokenTypes.BAND_ASSIGN] = GroovyTokenTypes.BAND_ASSIGN; typeMapping[JavaTokenTypes.BXOR_ASSIGN] = GroovyTokenTypes.BXOR_ASSIGN; typeMapping[JavaTokenTypes.BOR_ASSIGN] = GroovyTokenTypes.BOR_ASSIGN; typeMapping[JavaTokenTypes.LOR] = GroovyTokenTypes.LOR; typeMapping[JavaTokenTypes.LAND] = GroovyTokenTypes.LAND; typeMapping[JavaTokenTypes.BOR] = GroovyTokenTypes.BOR; typeMapping[JavaTokenTypes.BXOR] = GroovyTokenTypes.BXOR; typeMapping[JavaTokenTypes.NOT_EQUAL] = GroovyTokenTypes.NOT_EQUAL; typeMapping[JavaTokenTypes.EQUAL] = GroovyTokenTypes.EQUAL; typeMapping[JavaTokenTypes.LE] = GroovyTokenTypes.LE; typeMapping[JavaTokenTypes.GE] = GroovyTokenTypes.GE; typeMapping[JavaTokenTypes.LITERAL_instanceof] = GroovyTokenTypes.LITERAL_instanceof; typeMapping[JavaTokenTypes.SL] = GroovyTokenTypes.SL; typeMapping[JavaTokenTypes.PLUS] = GroovyTokenTypes.PLUS; typeMapping[JavaTokenTypes.MINUS] = GroovyTokenTypes.MINUS; typeMapping[JavaTokenTypes.DIV] = GroovyTokenTypes.DIV; typeMapping[JavaTokenTypes.MOD] = GroovyTokenTypes.MOD; typeMapping[JavaTokenTypes.INC] = GroovyTokenTypes.INC; typeMapping[JavaTokenTypes.DEC] = GroovyTokenTypes.DEC; typeMapping[JavaTokenTypes.BNOT] = GroovyTokenTypes.BNOT; typeMapping[JavaTokenTypes.LNOT] = GroovyTokenTypes.LNOT; typeMapping[JavaTokenTypes.LITERAL_true] = GroovyTokenTypes.LITERAL_true; typeMapping[JavaTokenTypes.LITERAL_false] = GroovyTokenTypes.LITERAL_false; typeMapping[JavaTokenTypes.LITERAL_null] = GroovyTokenTypes.LITERAL_null; typeMapping[JavaTokenTypes.LITERAL_new] = GroovyTokenTypes.LITERAL_new; typeMapping[JavaTokenTypes.NUM_INT] = GroovyTokenTypes.NUM_INT; typeMapping[JavaTokenTypes.CHAR_LITERAL] = GroovyTokenTypes.STRING_LITERAL; // warning: treating Java chars as "String" in Groovy typeMapping[JavaTokenTypes.STRING_LITERAL] = GroovyTokenTypes.STRING_LITERAL; typeMapping[JavaTokenTypes.NUM_FLOAT] = GroovyTokenTypes.NUM_FLOAT; typeMapping[JavaTokenTypes.NUM_LONG] = GroovyTokenTypes.NUM_LONG; typeMapping[JavaTokenTypes.NUM_DOUBLE] = GroovyTokenTypes.NUM_DOUBLE; typeMapping[JavaTokenTypes.WS] = GroovyTokenTypes.WS; typeMapping[JavaTokenTypes.SL_COMMENT] = GroovyTokenTypes.SL_COMMENT; typeMapping[JavaTokenTypes.ML_COMMENT] = GroovyTokenTypes.ML_COMMENT; typeMapping[JavaTokenTypes.ESC] = GroovyTokenTypes.ESC; typeMapping[JavaTokenTypes.HEX_DIGIT] = GroovyTokenTypes.HEX_DIGIT; typeMapping[JavaTokenTypes.VOCAB] = GroovyTokenTypes.VOCAB; typeMapping[JavaTokenTypes.EXPONENT] = GroovyTokenTypes.EXPONENT; typeMapping[JavaTokenTypes.FLOAT_SUFFIX] = GroovyTokenTypes.FLOAT_SUFFIX; } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { // only want to do this once per node... t.setType(typeMapping[t.getType()]); // ---- // need to remove double quotes in string literals // as groovy AST doesn't expect to have them if (t.getType() == GroovyTokenTypes.STRING_LITERAL) { String text = t.getText(); if (isSingleQuoted(text)) { t.setText(text.substring(1, text.length() - 1)); // chop off the single quotes at start and end } else if (isDoubleQuoted(text)) { t.setText(text.substring(1, text.length() - 1)); // chop off the double quotes at start and end } } } } private boolean isSingleQuoted(String text) { return text != null && text.length() > 2 && text.charAt(0) == '\'' && text.charAt(text.length() - 1) == '\''; } private boolean isDoubleQuoted(String text) { return text != null && text.length() > 2 && text.charAt(0) == '"' && text.charAt(text.length() - 1) == '"'; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaLexer.smap0000644001501200150120000003135311715044504024625 0ustar miguelmiguelSMAP JavaLexer.java G *S G *F + 0 java.g java.g *L 0:195 0:201 0:207 0:213 0:219 0:225 0:231 0:237 0:243 0:249 0:255 0:262 0:268 0:274 0:293 0:301 0:307 0:313 0:317 0:321 0:325 0:329 0:333 0:337 0:341 0:345 0:349 0:353 0:357 0:361 0:365 0:369 0:373 0:377 0:381 0:385 0:389 0:393 0:397 0:401 0:405 0:409 0:413 0:417 0:421 0:425 0:429 0:433 0:437 0:441 0:445 0:449 0:453 2:3 2:4 2:5 2:6 2:7 2:8 2:9 2:10 1616:39 1617:40 1618:41 1619:42 1621:44 1622:45 1623:46 1624:47 1625:48 1626:49 1628:51 1629:52 1630:53 1631:54 1632:55 1633:56 1634:57 1635:58 1637:60 1638:61 1639:62 1640:63 1641:64 1642:65 1643:66 1644:67 1645:68 1646:69 1647:70 1648:71 1649:72 1650:73 1651:74 1652:75 1653:76 1654:77 1655:78 1656:79 1657:80 1658:81 1659:82 1660:83 1661:84 1662:85 1663:86 1664:87 1665:88 1666:89 1667:90 1668:91 1669:92 1670:93 1671:94 1672:95 1673:96 1674:97 1675:98 1676:99 1677:100 1678:101 1679:102 1680:103 1681:104 1682:105 1683:106 1684:107 1685:108 1686:109 1687:110 1688:111 1689:112 1691:114 1695:481 1695:482 1695:483 1695:484 1695:486 1695:487 1695:488 1695:489 1695:490 1695:491 1695:492 1696:494 1696:495 1696:496 1696:497 1696:499 1696:500 1696:501 1696:502 1696:503 1696:504 1696:505 1697:507 1697:508 1697:509 1697:510 1697:512 1697:513 1697:514 1697:515 1697:516 1697:517 1697:518 1698:520 1698:521 1698:522 1698:523 1698:525 1698:526 1698:527 1698:528 1698:529 1698:530 1698:531 1699:533 1699:534 1699:535 1699:536 1699:538 1699:539 1699:540 1699:541 1699:542 1699:543 1699:544 1700:546 1700:547 1700:548 1700:549 1700:551 1700:552 1700:553 1700:554 1700:555 1700:556 1700:557 1701:559 1701:560 1701:561 1701:562 1701:564 1701:565 1701:566 1701:567 1701:568 1701:569 1701:570 1702:572 1702:573 1702:574 1702:575 1702:577 1702:578 1702:579 1702:580 1702:581 1702:582 1702:583 1703:585 1703:586 1703:587 1703:588 1703:590 1703:591 1703:592 1703:593 1703:594 1703:595 1703:596 1705:598 1705:599 1705:600 1705:601 1705:603 1705:604 1705:605 1705:606 1705:607 1705:608 1705:609 1706:611 1706:612 1706:613 1706:614 1706:616 1706:617 1706:618 1706:619 1706:620 1706:621 1706:622 1707:624 1707:625 1707:626 1707:627 1707:629 1707:630 1707:631 1707:632 1707:633 1707:634 1707:635 1708:637 1708:638 1708:639 1708:640 1708:642 1708:643 1708:644 1708:645 1708:646 1708:647 1708:648 1709:650 1709:651 1709:652 1709:653 1709:655 1709:656 1709:657 1709:658 1709:659 1709:660 1709:661 1710:663 1710:664 1710:665 1710:666 1710:668 1710:669 1710:670 1710:671 1710:672 1710:673 1710:674 1711:676 1711:677 1711:678 1711:679 1711:681 1711:682 1711:683 1711:684 1711:685 1711:686 1711:687 1712:689 1712:690 1712:691 1712:692 1712:694 1712:695 1712:696 1712:697 1712:698 1712:699 1712:700 1713:702 1713:703 1713:704 1713:705 1713:707 1713:708 1713:709 1713:710 1713:711 1713:712 1713:713 1714:715 1714:716 1714:717 1714:718 1714:720 1714:721 1714:722 1714:723 1714:724 1714:725 1714:726 1715:728 1715:729 1715:730 1715:731 1715:733 1715:734 1715:735 1715:736 1715:737 1715:738 1715:739 1716:741 1716:742 1716:743 1716:744 1716:746 1716:747 1716:748 1716:749 1716:750 1716:751 1716:752 1717:754 1717:755 1717:756 1717:757 1717:759 1717:760 1717:761 1717:762 1717:763 1717:764 1717:765 1718:767 1718:768 1718:769 1718:770 1718:772 1718:773 1718:774 1718:775 1718:776 1718:777 1718:778 1719:780 1719:781 1719:782 1719:783 1719:785 1719:786 1719:787 1719:788 1719:789 1719:790 1719:791 1720:793 1720:794 1720:795 1720:796 1720:798 1720:799 1720:800 1720:801 1720:802 1720:803 1720:804 1721:806 1721:807 1721:808 1721:809 1721:811 1721:812 1721:813 1721:814 1721:815 1721:816 1721:817 1722:819 1722:820 1722:821 1722:822 1722:824 1722:825 1722:826 1722:827 1722:828 1722:829 1722:830 1723:832 1723:833 1723:834 1723:835 1723:837 1723:838 1723:839 1723:840 1723:841 1723:842 1723:843 1724:845 1724:846 1724:847 1724:848 1724:850 1724:851 1724:852 1724:853 1724:854 1724:855 1724:856 1725:858 1725:859 1725:860 1725:861 1725:863 1725:864 1725:865 1725:866 1725:867 1725:868 1725:869 1726:871 1726:872 1726:873 1726:874 1726:876 1726:877 1726:878 1726:879 1726:880 1726:881 1726:882 1727:884 1727:885 1727:886 1727:887 1727:889 1727:890 1727:891 1727:892 1727:893 1727:894 1727:895 1728:897 1728:898 1728:899 1728:900 1728:902 1728:903 1728:904 1728:905 1728:906 1728:907 1728:908 1729:910 1729:911 1729:912 1729:913 1729:915 1729:916 1729:917 1729:918 1729:919 1729:920 1729:921 1730:923 1730:924 1730:925 1730:926 1730:928 1730:929 1730:930 1730:931 1730:932 1730:933 1730:934 1731:936 1731:937 1731:938 1731:939 1731:941 1731:942 1731:943 1731:944 1731:945 1731:946 1731:947 1732:949 1732:950 1732:951 1732:952 1732:954 1732:955 1732:956 1732:957 1732:958 1732:959 1732:960 1733:962 1733:963 1733:964 1733:965 1733:967 1733:968 1733:969 1733:970 1733:971 1733:972 1733:973 1734:975 1734:976 1734:977 1734:978 1734:980 1734:981 1734:982 1734:983 1734:984 1734:985 1734:986 1735:988 1735:989 1735:990 1735:991 1735:993 1735:994 1735:995 1735:996 1735:997 1735:998 1735:999 1736:1001 1736:1002 1736:1003 1736:1004 1736:1006 1736:1007 1736:1008 1736:1009 1736:1010 1736:1011 1736:1012 1737:1014 1737:1015 1737:1016 1737:1017 1737:1019 1737:1020 1737:1021 1737:1022 1737:1023 1737:1024 1737:1025 1738:1027 1738:1028 1738:1029 1738:1030 1738:1032 1738:1033 1738:1034 1738:1035 1738:1036 1738:1037 1738:1038 1739:1040 1739:1041 1739:1042 1739:1043 1739:1045 1739:1046 1739:1047 1739:1048 1739:1049 1739:1050 1739:1051 1740:1053 1740:1054 1740:1055 1740:1056 1740:1058 1740:1059 1740:1060 1740:1061 1740:1062 1740:1063 1740:1064 1744:1066 1744:1067 1744:1068 1744:1069 1744:1072 1744:1073 1744:1074 1744:1075 1744:1076 1744:1077 1744:1078 1744:1113 1744:1114 1744:1115 1744:1116 1744:1117 1744:1118 1744:1119 1744:1120 1744:1124 1744:1125 1744:1126 1744:1127 1744:1128 1744:1129 1745:1081 1745:1082 1745:1083 1746:1086 1746:1087 1746:1088 1748:1091 1748:1092 1748:1096 1748:1099 1748:1102 1748:1103 1748:1104 1748:1105 1749:1094 1749:1095 1750:1097 1750:1098 1751:1100 1751:1101 1753:1108 1753:1109 1755:1121 1755:1122 1759:1131 1759:1132 1759:1133 1759:1134 1759:1180 1759:1181 1759:1182 1759:1183 1759:1184 1759:1185 1760:1136 1761:1137 1761:1138 1761:1139 1761:1140 1761:1142 1761:1144 1761:1145 1761:1146 1761:1147 1761:1149 1761:1150 1761:1152 1761:1153 1761:1154 1761:1155 1761:1158 1761:1159 1761:1160 1761:1162 1761:1163 1761:1164 1761:1166 1761:1171 1761:1172 1761:1173 1761:1174 1761:1175 1762:1177 1762:1178 1766:1187 1766:1188 1766:1189 1766:1190 1766:1233 1766:1234 1766:1235 1766:1236 1766:1237 1766:1238 1767:1192 1768:1193 1768:1194 1768:1195 1768:1202 1768:1205 1768:1211 1768:1217 1768:1222 1768:1223 1768:1224 1768:1225 1768:1227 1768:1228 1779:1203 1779:1204 1780:1196 1780:1197 1780:1198 1780:1199 1780:1200 1781:1206 1781:1207 1781:1208 1781:1209 1782:1212 1782:1213 1782:1214 1782:1215 1783:1218 1783:1220 1785:1229 1786:1230 1786:1231 1791:1240 1791:1241 1791:1242 1791:1243 1791:1261 1791:1262 1791:1263 1791:1264 1791:1265 1791:1266 1792:1245 1792:1247 1792:1248 1792:1249 1792:1250 1792:1252 1792:1254 1792:1255 1792:1256 1792:1257 1792:1260 1796:1394 1796:1395 1796:1396 1796:1397 1796:1418 1796:1419 1796:1420 1796:1421 1796:1422 1796:1423 1797:1399 1797:1400 1797:1401 1797:1402 1797:1403 1797:1404 1797:1405 1797:1406 1797:1408 1797:1410 1797:1411 1797:1412 1797:1413 1797:1415 1797:1416 1797:1417 1810:1268 1810:1269 1810:1270 1810:1271 1810:1387 1810:1388 1810:1389 1810:1390 1810:1391 1810:1392 1811:1273 1812:1275 1812:1276 1812:1277 1812:1278 1812:1381 1812:1382 1812:1383 1812:1384 1812:1385 1813:1281 1813:1282 1813:1283 1814:1286 1814:1287 1814:1288 1815:1291 1815:1292 1815:1293 1816:1296 1816:1297 1816:1298 1817:1301 1817:1302 1817:1303 1818:1306 1818:1307 1818:1308 1819:1311 1819:1312 1819:1313 1820:1316 1820:1317 1820:1319 1820:1320 1820:1321 1820:1322 1820:1323 1820:1324 1820:1325 1820:1326 1820:1327 1820:1329 1820:1330 1820:1331 1820:1332 1820:1333 1820:1334 1820:1335 1821:1338 1821:1339 1821:1340 1822:1355 1822:1357 1822:1358 1822:1359 1822:1360 1826:1342 1826:1343 1827:1347 1827:1349 1827:1350 1827:1351 1827:1352 1831:1345 1831:1346 1834:1365 1834:1366 1834:1367 1835:1371 1835:1373 1835:1374 1835:1375 1835:1376 1839:1369 1839:1370 1847:1425 1847:1426 1847:1427 1847:1428 1847:1457 1847:1458 1847:1459 1847:1460 1847:1461 1847:1462 1848:1431 1848:1432 1848:1433 1848:1434 1848:1435 1848:1436 1848:1439 1848:1440 1848:1441 1848:1442 1848:1445 1848:1446 1848:1447 1848:1448 1848:1451 1848:1452 1848:1453 1848:1454 1848:1455 1855:1464 1855:1465 1855:1466 1855:1467 1855:1470 1855:1471 1855:1472 1855:1473 1855:1474 1855:1475 1856:1469 1863:1477 1863:1478 1863:1479 1863:1480 1863:1584 1863:1585 1863:1586 1863:1587 1863:1588 1863:1589 1863:1590 1865:1483 1865:1484 1865:1485 1865:1486 1865:1487 1865:1488 1865:1489 1865:1490 1865:1491 1865:1492 1865:1495 1865:1496 1865:1497 1865:1498 1865:1499 1865:1500 1865:1501 1865:1502 1865:1503 1865:1506 1865:1507 1865:1508 1865:1511 1865:1512 1865:1513 1865:1516 1865:1517 1865:1518 1865:1519 1865:1520 1865:1522 1865:1523 1865:1524 1865:1525 1865:1526 1865:1527 1865:1528 1865:1529 1865:1530 1865:1531 1865:1532 1865:1533 1865:1534 1865:1537 1865:1538 1865:1539 1865:1540 1865:1541 1865:1542 1865:1543 1865:1544 1865:1545 1865:1548 1865:1549 1865:1550 1865:1553 1865:1554 1865:1555 1865:1556 1865:1557 1865:1560 1865:1561 1865:1562 1865:1565 1865:1566 1865:1567 1865:1568 1865:1569 1865:1570 1865:1571 1866:1572 1867:1574 1868:1575 1869:1576 1870:1577 1871:1578 1872:1579 1873:1580 1874:1581 1880:1592 1880:1593 1880:1594 1880:1595 1880:1600 1880:1602 1880:1961 1880:1962 1880:1963 1880:1964 1880:1965 1880:1966 1880:1967 1880:1968 1880:1969 1880:1970 1880:1971 1882:1603 1882:1604 1882:1605 1882:1606 1882:1607 1883:1610 1883:1673 1883:1675 1883:1676 1884:1596 1884:1611 1884:1612 1884:1613 1884:1614 1884:1617 1884:1618 1884:1619 1884:1620 1884:1621 1884:1622 1884:1623 1884:1624 1884:1625 1884:1627 1884:1628 1884:1629 1884:1631 1884:1632 1884:1633 1884:1635 1884:1639 1884:1640 1884:1641 1884:1642 1884:1643 1884:1645 1884:1647 1885:1650 1886:1652 1887:1653 1888:1654 1889:1655 1890:1656 1891:1657 1895:1663 1895:1664 1895:1666 1895:1667 1895:1668 1898:1680 1898:1681 1898:1682 1898:1683 1898:1685 1898:1686 1898:1687 1898:1688 1898:1689 1898:1690 1898:1842 1898:1843 1898:1844 1898:1845 1898:1846 1899:1693 1899:1695 1899:1696 1899:1697 1899:1698 1899:1701 1899:1702 1899:1703 1899:1706 1899:1707 1899:1708 1899:1709 1899:1710 1899:1726 1899:1795 1899:1811 1899:1813 1899:1814 1900:1713 1900:1714 1900:1715 1900:1718 1900:1719 1900:1720 1900:1721 1900:1723 1900:1724 1900:1725 1909:1716 1909:1717 1913:1727 1913:1728 1913:1729 1913:1730 1913:1731 1913:1732 1913:1733 1913:1736 1913:1737 1913:1738 1913:1739 1913:1740 1913:1741 1913:1742 1913:1743 1913:1744 1913:1746 1913:1747 1913:1748 1913:1750 1913:1751 1913:1752 1913:1753 1913:1756 1913:1757 1913:1758 1913:1761 1913:1762 1913:1763 1913:1766 1913:1767 1913:1768 1913:1769 1913:1770 1913:1773 1913:1774 1913:1775 1913:1776 1913:1777 1913:1778 1913:1779 1913:1780 1913:1782 1913:1783 1913:1784 1913:1785 1913:1786 1913:1787 1913:1788 1913:1789 1913:1790 1913:1792 1913:1793 1913:1794 1915:1796 1915:1798 1915:1799 1915:1800 1915:1801 1915:1802 1915:1803 1915:1804 1915:1805 1915:1806 1915:1808 1915:1809 1915:1810 1917:1818 1917:1819 1917:1820 1917:1821 1917:1823 1917:1825 1917:1826 1917:1827 1917:1828 1917:1829 1917:1830 1917:1831 1917:1832 1917:1833 1917:1835 1917:1836 1917:1837 1917:1838 1919:1849 1919:1851 1919:1852 1919:1853 1919:1854 1919:1857 1919:1858 1919:1859 1919:1862 1919:1863 1919:1864 1919:1865 1919:1866 1919:1868 1919:1869 1919:1871 1919:1954 1919:1956 1923:1597 1923:1872 1923:1874 1923:1875 1923:1876 1923:1877 1923:1878 1923:1879 1923:1880 1923:1881 1923:1882 1923:1883 1923:1884 1923:1885 1923:1886 1923:1888 1923:1889 1923:1891 1923:1892 1923:1893 1923:1895 1923:1899 1923:1900 1923:1901 1923:1902 1923:1903 1923:1905 1923:1907 1923:1938 1923:1939 1923:1940 1923:1941 1923:1942 1924:1598 1924:1912 1924:1913 1924:1914 1924:1916 1924:1917 1924:1918 1924:1919 1924:1920 1924:1922 1924:1924 1925:1599 1925:1929 1925:1930 1925:1931 1925:1932 1925:1933 1925:1934 1927:1944 1928:1946 1929:1947 1930:1948 1931:1949 1932:1950 1933:1951 1939:2079 1939:2080 1939:2081 1939:2082 1939:2085 1939:2086 1939:2087 1939:2088 1939:2089 1939:2090 1940:2084 1945:1973 1945:1974 1945:1975 1945:1976 1945:2034 1945:2035 1945:2036 1945:2037 1945:2038 1945:2039 1946:1979 1946:1980 1946:1981 1946:1982 1946:1985 1946:1986 1946:1987 1946:1990 1946:1991 1946:1992 1946:1993 1946:1994 1946:1997 1946:1998 1946:1999 1946:2000 1946:2003 1946:2004 1946:2005 1946:2014 1946:2015 1946:2016 1946:2017 1946:2018 1946:2021 1946:2022 1946:2023 1946:2024 1946:2025 1946:2026 1946:2027 1946:2028 1946:2029 1946:2031 1946:2032 1946:2033 1951:2041 1951:2042 1951:2043 1951:2044 1951:2046 1951:2067 1951:2068 1951:2069 1951:2070 1951:2071 1951:2072 1951:2073 1951:2074 1951:2075 1951:2076 1951:2077 1952:2047 1952:2048 1952:2049 1952:2052 1952:2053 1952:2054 1952:2057 1952:2058 1952:2059 1952:2062 1952:2063 1952:2064 *E groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaRecognizer.java0000644001501200150120000057167211715044502025651 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "java.g" -> "JavaRecognizer.java"$ package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.*; import org.codehaus.groovy.antlr.parser.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; import antlr.collections.AST; import java.util.Hashtable; import antlr.ASTFactory; import antlr.ASTPair; import antlr.collections.impl.ASTArray; /** Java 1.5 Recognizer * * Run 'java Main [-showtree] directory-full-of-java-files' * * [The -showtree option pops up a Swing frame that shows * the AST constructed from the parser.] * * Run 'java Main ' * * Contributing authors: * Jeremy Rayner groovy@ross-rayner.com * John Mitchell johnm@non.net * Terence Parr parrt@magelang.com * John Lilley jlilley@empathy.com * Scott Stanchfield thetick@magelang.com * Markus Mohnen mohnen@informatik.rwth-aachen.de * Peter Williams pete.williams@sun.com * Allan Jacobs Allan.Jacobs@eng.sun.com * Steve Messick messick@redhills.com * John Pybus john@pybus.org * * Version 1.00 December 9, 1997 -- initial release * Version 1.01 December 10, 1997 * fixed bug in octal def (0..7 not 0..8) * Version 1.10 August 1998 (parrt) * added tree construction * fixed definition of WS,comments for mac,pc,unix newlines * added unary plus * Version 1.11 (Nov 20, 1998) * Added "shutup" option to turn off last ambig warning. * Fixed inner class def to allow named class defs as statements * synchronized requires compound not simple statement * add [] after builtInType DOT class in primaryExpression * "const" is reserved but not valid..removed from modifiers * Version 1.12 (Feb 2, 1999) * Changed LITERAL_xxx to xxx in tree grammar. * Updated java.g to use tokens {...} now for 2.6.0 (new feature). * * Version 1.13 (Apr 23, 1999) * Didn't have (stat)? for else clause in tree parser. * Didn't gen ASTs for interface extends. Updated tree parser too. * Updated to 2.6.0. * Version 1.14 (Jun 20, 1999) * Allowed final/abstract on local classes. * Removed local interfaces from methods * Put instanceof precedence where it belongs...in relationalExpr * It also had expr not type as arg; fixed it. * Missing ! on SEMI in classBlock * fixed: (expr) + "string" was parsed incorrectly (+ as unary plus). * fixed: didn't like Object[].class in parser or tree parser * Version 1.15 (Jun 26, 1999) * Screwed up rule with instanceof in it. :( Fixed. * Tree parser didn't like (expr).something; fixed. * Allowed multiple inheritance in tree grammar. oops. * Version 1.16 (August 22, 1999) * Extending an interface built a wacky tree: had extra EXTENDS. * Tree grammar didn't allow multiple superinterfaces. * Tree grammar didn't allow empty var initializer: {} * Version 1.17 (October 12, 1999) * ESC lexer rule allowed 399 max not 377 max. * java.tree.g didn't handle the expression of synchronized * statements. * Version 1.18 (August 12, 2001) * Terence updated to Java 2 Version 1.3 by * observing/combining work of Allan Jacobs and Steve * Messick. Handles 1.3 src. Summary: * o primary didn't include boolean.class kind of thing * o constructor calls parsed explicitly now: * see explicitConstructorInvocation * o add strictfp modifier * o missing objBlock after new expression in tree grammar * o merged local class definition alternatives, moved after declaration * o fixed problem with ClassName.super.field * o reordered some alternatives to make things more efficient * o long and double constants were not differentiated from int/float * o whitespace rule was inefficient: matched only one char * o add an examples directory with some nasty 1.3 cases * o made Main.java use buffered IO and a Reader for Unicode support * o supports UNICODE? * Using Unicode charVocabulay makes code file big, but only * in the bitsets at the end. I need to make ANTLR generate * unicode bitsets more efficiently. * Version 1.19 (April 25, 2002) * Terence added in nice fixes by John Pybus concerning floating * constants and problems with super() calls. John did a nice * reorg of the primary/postfix expression stuff to read better * and makes f.g.super() parse properly (it was METHOD_CALL not * a SUPER_CTOR_CALL). Also: * * o "finally" clause was a root...made it a child of "try" * o Added stuff for asserts too for Java 1.4, but *commented out* * as it is not backward compatible. * * Version 1.20 (October 27, 2002) * * Terence ended up reorging John Pybus' stuff to * remove some nondeterminisms and some syntactic predicates. * Note that the grammar is stricter now; e.g., this(...) must * be the first statement. * * Trinary ?: operator wasn't working as array name: * (isBig ? bigDigits : digits)[i]; * * Checked parser/tree parser on source for * Resin-2.0.5, jive-2.1.1, jdk 1.3.1, Lucene, antlr 2.7.2a4, * and the 110k-line jGuru server source. * * Version 1.21 (October 17, 2003) * Fixed lots of problems including: * Ray Waldin: add typeDefinition to interfaceBlock in java.tree.g * He found a problem/fix with floating point that start with 0 * Ray also fixed problem that (int.class) was not recognized. * Thorsten van Ellen noticed that \n are allowed incorrectly in strings. * TJP fixed CHAR_LITERAL analogously. * * Version 1.21.2 (March, 2003) * Changes by Matt Quail to support generics (as per JDK1.5/JSR14) * Notes: * o We only allow the "extends" keyword and not the "implements" * keyword, since thats what JSR14 seems to imply. * o Thanks to Monty Zukowski for his help on the antlr-interest * mail list. * o Thanks to Alan Eliasen for testing the grammar over his * Fink source base * * Version 1.22 (July, 2004) * Changes by Michael Studman to support Java 1.5 language extensions * Notes: * o Added support for annotations types * o Finished off Matt Quail's generics enhancements to support bound type arguments * o Added support for new for statement syntax * o Added support for static import syntax * o Added support for enum types * o Tested against JDK 1.5 source base and source base of jdigraph project * o Thanks to Matt Quail for doing the hard part by doing most of the generics work * * Version 1.22.1 (July 28, 2004) * Bug/omission fixes for Java 1.5 language support * o Fixed tree structure bug with classOrInterface - thanks to Pieter Vangorpto for * spotting this * o Fixed bug where incorrect handling of SR and BSR tokens would cause type * parameters to be recognised as type arguments. * o Enabled type parameters on constructors, annotations on enum constants * and package definitions * o Fixed problems when parsing if ((char.class.equals(c))) {} - solution by Matt Quail at Cenqua * * Version 1.22.2 (July 28, 2004) * Slight refactoring of Java 1.5 language support * o Refactored for/"foreach" productions so that original literal "for" literal * is still used but the for sub-clauses vary by token type * o Fixed bug where type parameter was not included in generic constructor's branch of AST * * Version 1.22.3 (August 26, 2004) * Bug fixes as identified by Michael Stahl; clean up of tabs/spaces * and other refactorings * o Fixed typeParameters omission in identPrimary and newStatement * o Replaced GT reconcilliation code with simple semantic predicate * o Adapted enum/assert keyword checking support from Michael Stahl's java15 grammar * o Refactored typeDefinition production and field productions to reduce duplication * * Version 1.22.4 (October 21, 2004) * Small bux fixes * o Added typeArguments to explicitConstructorInvocation, e.g. new MyParameterised() * o Added typeArguments to postfixExpression productions for anonymous inner class super * constructor invocation, e.g. new Outer().super() * o Fixed bug in array declarations identified by Geoff Roy * * Version 1.22.4.j.1 * Changes by Jeremy Rayner to support java2groovy tool * o I have taken java.g for Java1.5 from Michael Studman (1.22.4) * and have made some changes to enable use by java2groovy tool (Jan 2007) * * This grammar is in the PUBLIC DOMAIN */ public class JavaRecognizer extends antlr.LLkParser implements JavaTokenTypes { /** This factory is the correct way to wire together a Groovy parser and lexer. */ public static JavaRecognizer make(JavaLexer lexer) { JavaRecognizer parser = new JavaRecognizer(lexer.plumb()); // TODO: set up a common error-handling control block, to avoid excessive tangle between these guys parser.lexer = lexer; lexer.parser = parser; parser.setASTNodeClass("org.codehaus.groovy.antlr.GroovySourceAST"); return parser; } // Create a scanner that reads from the input stream passed to us... public static JavaRecognizer make(InputStream in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(Reader in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(InputBuffer in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(LexerSharedInputState in) { return make(new JavaLexer(in)); } private static GroovySourceAST dummyVariableToforceClassLoaderToFindASTClass = new GroovySourceAST(); JavaLexer lexer; public JavaLexer getLexer() { return lexer; } public void setFilename(String f) { super.setFilename(f); lexer.setFilename(f); } private SourceBuffer sourceBuffer; public void setSourceBuffer(SourceBuffer sourceBuffer) { this.sourceBuffer = sourceBuffer; } /** Create an AST node with the token type and text passed in, but * with the same background information as another supplied Token (e.g. line numbers) * to be used in place of antlr tree construction syntax, * i.e. #[TOKEN,"text"] becomes create(TOKEN,"text",anotherToken) * * todo - change antlr.ASTFactory to do this instead... */ public AST create(int type, String txt, Token first, Token last) { AST t = astFactory.create(type,txt); if ( t != null && first != null) { // first copy details from first token t.initialize(first); // then ensure that type and txt are specific to this new node t.initialize(type,txt); } if ((t instanceof GroovySourceAST) && last != null) { GroovySourceAST node = (GroovySourceAST)t; node.setLast(last); // This is a good point to call node.setSnippet(), // but it bulks up the AST too much for production code. } return t; } /** * Counts the number of LT seen in the typeArguments production. * It is used in semantic predicates to ensure we have seen * enough closing '>' characters; which actually may have been * either GT, SR or BSR tokens. */ private int ltCounter = 0; protected JavaRecognizer(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public JavaRecognizer(TokenBuffer tokenBuf) { this(tokenBuf,2); } protected JavaRecognizer(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public JavaRecognizer(TokenStream lexer) { this(lexer,2); } public JavaRecognizer(ParserSharedInputState state) { super(state,2); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public final void compilationUnit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST compilationUnit_AST = null; { boolean synPredMatched4 = false; if (((LA(1)==LITERAL_package||LA(1)==AT) && (LA(2)==IDENT))) { int _m4 = mark(); synPredMatched4 = true; inputState.guessing++; try { { annotations(); match(LITERAL_package); } } catch (RecognitionException pe) { synPredMatched4 = false; } rewind(_m4); inputState.guessing--; } if ( synPredMatched4 ) { packageDefinition(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_0.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { _loop6: do { if ((LA(1)==LITERAL_import)) { importDefinition(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop6; } } while (true); } { _loop8: do { if ((_tokenSet_2.member(LA(1)))) { typeDefinition(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop8; } } while (true); } match(Token.EOF_TYPE); compilationUnit_AST = (AST)currentAST.root; returnAST = compilationUnit_AST; } public final void annotations() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotations_AST = null; Token first = LT(1); { _loop62: do { if ((LA(1)==AT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop62; } } while (true); } if ( inputState.guessing==0 ) { annotations_AST = (AST)currentAST.root; annotations_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(ANNOTATIONS,"ANNOTATIONS")).add(annotations_AST)); currentAST.root = annotations_AST; currentAST.child = annotations_AST!=null &&annotations_AST.getFirstChild()!=null ? annotations_AST.getFirstChild() : annotations_AST; currentAST.advanceChildToEnd(); } annotations_AST = (AST)currentAST.root; returnAST = annotations_AST; } public final void packageDefinition() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST packageDefinition_AST = null; Token p = null; AST p_AST = null; try { // for error handling annotations(); astFactory.addASTChild(currentAST, returnAST); p = LT(1); p_AST = astFactory.create(p); astFactory.makeASTRoot(currentAST, p_AST); match(LITERAL_package); if ( inputState.guessing==0 ) { p_AST.setType(PACKAGE_DEF); } identifier(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); packageDefinition_AST = (AST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_0); } else { throw ex; } } returnAST = packageDefinition_AST; } public final void importDefinition() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST importDefinition_AST = null; Token i = null; AST i_AST = null; boolean isStatic = false; try { // for error handling i = LT(1); i_AST = astFactory.create(i); astFactory.makeASTRoot(currentAST, i_AST); match(LITERAL_import); if ( inputState.guessing==0 ) { i_AST.setType(IMPORT); } { switch ( LA(1)) { case LITERAL_static: { match(LITERAL_static); if ( inputState.guessing==0 ) { i_AST.setType(STATIC_IMPORT); } break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } identifierStar(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); importDefinition_AST = (AST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_0); } else { throw ex; } } returnAST = importDefinition_AST; } public final void typeDefinition() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeDefinition_AST = null; AST m_AST = null; try { // for error handling switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { modifiers(); m_AST = (AST)returnAST; typeDefinitionInternal(m_AST); astFactory.addASTChild(currentAST, returnAST); typeDefinition_AST = (AST)currentAST.root; break; } case SEMI: { match(SEMI); typeDefinition_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_3); } else { throw ex; } } returnAST = typeDefinition_AST; } public final void identifier() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST identifier_AST = null; AST tmp6_AST = null; tmp6_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp6_AST); match(IDENT); { _loop48: do { if ((LA(1)==DOT)) { AST tmp7_AST = null; tmp7_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp7_AST); match(DOT); AST tmp8_AST = null; tmp8_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp8_AST); match(IDENT); } else { break _loop48; } } while (true); } identifier_AST = (AST)currentAST.root; returnAST = identifier_AST; } public final void identifierStar() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST identifierStar_AST = null; AST tmp9_AST = null; tmp9_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp9_AST); match(IDENT); { _loop51: do { if ((LA(1)==DOT) && (LA(2)==IDENT)) { AST tmp10_AST = null; tmp10_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp10_AST); match(DOT); AST tmp11_AST = null; tmp11_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp11_AST); match(IDENT); } else { break _loop51; } } while (true); } { switch ( LA(1)) { case DOT: { AST tmp12_AST = null; tmp12_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp12_AST); match(DOT); AST tmp13_AST = null; tmp13_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp13_AST); match(STAR); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } identifierStar_AST = (AST)currentAST.root; returnAST = identifierStar_AST; } public final void modifiers() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifiers_AST = null; Token first = LT(1); { _loop55: do { if ((_tokenSet_4.member(LA(1)))) { modifier(); astFactory.addASTChild(currentAST, returnAST); } else if (((LA(1)==AT) && (LA(2)==IDENT))&&(LA(1)==AT && !LT(2).getText().equals("interface"))) { annotation(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop55; } } while (true); } if ( inputState.guessing==0 ) { modifiers_AST = (AST)currentAST.root; modifiers_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))).add(modifiers_AST)); currentAST.root = modifiers_AST; currentAST.child = modifiers_AST!=null &&modifiers_AST.getFirstChild()!=null ? modifiers_AST.getFirstChild() : modifiers_AST; currentAST.advanceChildToEnd(); } modifiers_AST = (AST)currentAST.root; returnAST = modifiers_AST; } protected final void typeDefinitionInternal( AST mods ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeDefinitionInternal_AST = null; switch ( LA(1)) { case LITERAL_class: { classDefinition(mods); astFactory.addASTChild(currentAST, returnAST); typeDefinitionInternal_AST = (AST)currentAST.root; break; } case LITERAL_interface: { interfaceDefinition(mods); astFactory.addASTChild(currentAST, returnAST); typeDefinitionInternal_AST = (AST)currentAST.root; break; } case LITERAL_enum: { enumDefinition(mods); astFactory.addASTChild(currentAST, returnAST); typeDefinitionInternal_AST = (AST)currentAST.root; break; } case AT: { annotationDefinition(mods); astFactory.addASTChild(currentAST, returnAST); typeDefinitionInternal_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeDefinitionInternal_AST; } public final void classDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classDefinition_AST = null; AST tp_AST = null; AST sc_AST = null; AST ic_AST = null; AST cb_AST = null; Token first = LT(1); match(LITERAL_class); AST tmp15_AST = null; tmp15_AST = astFactory.create(LT(1)); match(IDENT); { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case LITERAL_extends: case LCURLY: case LITERAL_implements: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } superClassClause(); sc_AST = (AST)returnAST; implementsClause(); ic_AST = (AST)returnAST; classBlock(); cb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classDefinition_AST = (AST)currentAST.root; classDefinition_AST = (AST)astFactory.make( (new ASTArray(7)).add(create(CLASS_DEF,"CLASS_DEF",first,LT(1))).add(modifiers).add(tmp15_AST).add(tp_AST).add(sc_AST).add(ic_AST).add(cb_AST)); currentAST.root = classDefinition_AST; currentAST.child = classDefinition_AST!=null &&classDefinition_AST.getFirstChild()!=null ? classDefinition_AST.getFirstChild() : classDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = classDefinition_AST; } public final void interfaceDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceDefinition_AST = null; AST tp_AST = null; AST ie_AST = null; AST ib_AST = null; Token first = LT(1); match(LITERAL_interface); AST tmp17_AST = null; tmp17_AST = astFactory.create(LT(1)); match(IDENT); { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case LITERAL_extends: case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } interfaceExtends(); ie_AST = (AST)returnAST; interfaceBlock(); ib_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceDefinition_AST = (AST)currentAST.root; interfaceDefinition_AST = (AST)astFactory.make( (new ASTArray(6)).add(create(INTERFACE_DEF,"INTERFACE_DEF",first,LT(1))).add(modifiers).add(tmp17_AST).add(tp_AST).add(ie_AST).add(ib_AST)); currentAST.root = interfaceDefinition_AST; currentAST.child = interfaceDefinition_AST!=null &&interfaceDefinition_AST.getFirstChild()!=null ? interfaceDefinition_AST.getFirstChild() : interfaceDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = interfaceDefinition_AST; } public final void enumDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumDefinition_AST = null; AST ic_AST = null; AST eb_AST = null; Token first = LT(1); match(LITERAL_enum); AST tmp19_AST = null; tmp19_AST = astFactory.create(LT(1)); match(IDENT); implementsClause(); ic_AST = (AST)returnAST; enumBlock(); eb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumDefinition_AST = (AST)currentAST.root; enumDefinition_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(ENUM_DEF,"ENUM_DEF",first,LT(1))).add(modifiers).add(tmp19_AST).add(ic_AST).add(eb_AST)); currentAST.root = enumDefinition_AST; currentAST.child = enumDefinition_AST!=null &&enumDefinition_AST.getFirstChild()!=null ? enumDefinition_AST.getFirstChild() : enumDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = enumDefinition_AST; } public final void annotationDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationDefinition_AST = null; AST ab_AST = null; Token first = LT(1); AST tmp20_AST = null; tmp20_AST = astFactory.create(LT(1)); match(AT); match(LITERAL_interface); AST tmp22_AST = null; tmp22_AST = astFactory.create(LT(1)); match(IDENT); annotationBlock(); ab_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationDefinition_AST = (AST)currentAST.root; annotationDefinition_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(ANNOTATION_DEF,"ANNOTATION_DEF",first,LT(1))).add(modifiers).add(tmp22_AST).add(ab_AST)); currentAST.root = annotationDefinition_AST; currentAST.child = annotationDefinition_AST!=null &&annotationDefinition_AST.getFirstChild()!=null ? annotationDefinition_AST.getFirstChild() : annotationDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = annotationDefinition_AST; } public final void declaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST declaration_AST = null; AST m_AST = null; AST t_AST = null; AST v_AST = null; modifiers(); m_AST = (AST)returnAST; typeSpec(false); t_AST = (AST)returnAST; variableDefinitions(m_AST,t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { declaration_AST = (AST)currentAST.root; declaration_AST = v_AST; currentAST.root = declaration_AST; currentAST.child = declaration_AST!=null &&declaration_AST.getFirstChild()!=null ? declaration_AST.getFirstChild() : declaration_AST; currentAST.advanceChildToEnd(); } returnAST = declaration_AST; } public final void typeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeSpec_AST = null; switch ( LA(1)) { case IDENT: { classTypeSpec(addImagNode); astFactory.addASTChild(currentAST, returnAST); typeSpec_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInTypeSpec(addImagNode); astFactory.addASTChild(currentAST, returnAST); typeSpec_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeSpec_AST; } public final void variableDefinitions( AST mods, AST t ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableDefinitions_AST = null; variableDeclarator(getASTFactory().dupTree(mods), getASTFactory().dupTree(t)); astFactory.addASTChild(currentAST, returnAST); { _loop155: do { if ((LA(1)==COMMA)) { match(COMMA); variableDeclarator(getASTFactory().dupTree(mods), getASTFactory().dupTree(t)); astFactory.addASTChild(currentAST, returnAST); } else { break _loop155; } } while (true); } variableDefinitions_AST = (AST)currentAST.root; returnAST = variableDefinitions_AST; } public final void classTypeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classTypeSpec_AST = null; Token lb = null; AST lb_AST = null; Token first = LT(1); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); { _loop18: do { if ((LA(1)==LBRACK) && (LA(2)==RBRACK)) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { break _loop18; } } while (true); } if ( inputState.guessing==0 ) { classTypeSpec_AST = (AST)currentAST.root; if ( addImagNode ) { classTypeSpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(classTypeSpec_AST)); } currentAST.root = classTypeSpec_AST; currentAST.child = classTypeSpec_AST!=null &&classTypeSpec_AST.getFirstChild()!=null ? classTypeSpec_AST.getFirstChild() : classTypeSpec_AST; currentAST.advanceChildToEnd(); } classTypeSpec_AST = (AST)currentAST.root; returnAST = classTypeSpec_AST; } public final void builtInTypeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInTypeSpec_AST = null; Token lb = null; AST lb_AST = null; Token first = LT(1); builtInType(); astFactory.addASTChild(currentAST, returnAST); { _loop43: do { if ((LA(1)==LBRACK)) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { break _loop43; } } while (true); } if ( inputState.guessing==0 ) { builtInTypeSpec_AST = (AST)currentAST.root; if ( addImagNode ) { builtInTypeSpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(builtInTypeSpec_AST)); } currentAST.root = builtInTypeSpec_AST; currentAST.child = builtInTypeSpec_AST!=null &&builtInTypeSpec_AST.getFirstChild()!=null ? builtInTypeSpec_AST.getFirstChild() : builtInTypeSpec_AST; currentAST.advanceChildToEnd(); } builtInTypeSpec_AST = (AST)currentAST.root; returnAST = builtInTypeSpec_AST; } public final void classOrInterfaceType( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classOrInterfaceType_AST = null; Token first = LT(1); AST tmp26_AST = null; tmp26_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp26_AST); match(IDENT); { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case LBRACK: case RBRACK: case IDENT: case DOT: case QUESTION: case LITERAL_extends: case LITERAL_super: case COMMA: case GT: case SR: case BSR: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case RPAREN: case ASSIGN: case LCURLY: case RCURLY: case BAND: case LITERAL_implements: case LITERAL_this: case TRIPLE_DOT: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop23: do { if ((LA(1)==DOT) && (LA(2)==IDENT)) { AST tmp27_AST = null; tmp27_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp27_AST); match(DOT); AST tmp28_AST = null; tmp28_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp28_AST); match(IDENT); { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case LBRACK: case RBRACK: case IDENT: case DOT: case QUESTION: case LITERAL_extends: case LITERAL_super: case COMMA: case GT: case SR: case BSR: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case RPAREN: case ASSIGN: case LCURLY: case RCURLY: case BAND: case LITERAL_implements: case LITERAL_this: case TRIPLE_DOT: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop23; } } while (true); } if ( inputState.guessing==0 ) { classOrInterfaceType_AST = (AST)currentAST.root; if ( addImagNode ) { classOrInterfaceType_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(classOrInterfaceType_AST)); } currentAST.root = classOrInterfaceType_AST; currentAST.child = classOrInterfaceType_AST!=null &&classOrInterfaceType_AST.getFirstChild()!=null ? classOrInterfaceType_AST.getFirstChild() : classOrInterfaceType_AST; currentAST.advanceChildToEnd(); } classOrInterfaceType_AST = (AST)currentAST.root; returnAST = classOrInterfaceType_AST; } public final void typeArguments() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArguments_AST = null; int currentLtLevel = 0; Token first = LT(1); if ( inputState.guessing==0 ) { currentLtLevel = ltCounter; } match(LT); if ( inputState.guessing==0 ) { ltCounter++; } typeArgument(); astFactory.addASTChild(currentAST, returnAST); { _loop33: do { if (((LA(1)==COMMA) && (_tokenSet_5.member(LA(2))))&&(inputState.guessing !=0 || ltCounter == currentLtLevel + 1)) { match(COMMA); typeArgument(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop33; } } while (true); } { if (((LA(1) >= GT && LA(1) <= BSR)) && (_tokenSet_6.member(LA(2)))) { typeArgumentsOrParametersEnd(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_6.member(LA(1))) && (_tokenSet_7.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if (!((currentLtLevel != 0) || ltCounter == currentLtLevel)) throw new SemanticException("(currentLtLevel != 0) || ltCounter == currentLtLevel"); if ( inputState.guessing==0 ) { typeArguments_AST = (AST)currentAST.root; typeArguments_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_ARGUMENTS,"TYPE_ARGUMENTS",first,LT(1))).add(typeArguments_AST)); currentAST.root = typeArguments_AST; currentAST.child = typeArguments_AST!=null &&typeArguments_AST.getFirstChild()!=null ? typeArguments_AST.getFirstChild() : typeArguments_AST; currentAST.advanceChildToEnd(); } typeArguments_AST = (AST)currentAST.root; returnAST = typeArguments_AST; } public final void typeArgumentSpec() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentSpec_AST = null; switch ( LA(1)) { case IDENT: { classTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); typeArgumentSpec_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInTypeArraySpec(true); astFactory.addASTChild(currentAST, returnAST); typeArgumentSpec_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeArgumentSpec_AST; } public final void builtInTypeArraySpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInTypeArraySpec_AST = null; Token lb = null; AST lb_AST = null; Token first = LT(1); builtInType(); astFactory.addASTChild(currentAST, returnAST); { int _cnt40=0; _loop40: do { if ((LA(1)==LBRACK) && (LA(2)==RBRACK)) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { if ( _cnt40>=1 ) { break _loop40; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt40++; } while (true); } if ( inputState.guessing==0 ) { builtInTypeArraySpec_AST = (AST)currentAST.root; if ( addImagNode ) { builtInTypeArraySpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(builtInTypeArraySpec_AST)); } currentAST.root = builtInTypeArraySpec_AST; currentAST.child = builtInTypeArraySpec_AST!=null &&builtInTypeArraySpec_AST.getFirstChild()!=null ? builtInTypeArraySpec_AST.getFirstChild() : builtInTypeArraySpec_AST; currentAST.advanceChildToEnd(); } builtInTypeArraySpec_AST = (AST)currentAST.root; returnAST = builtInTypeArraySpec_AST; } public final void typeArgument() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgument_AST = null; Token first = LT(1); { switch ( LA(1)) { case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeArgumentSpec(); astFactory.addASTChild(currentAST, returnAST); break; } case QUESTION: { wildcardType(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { typeArgument_AST = (AST)currentAST.root; typeArgument_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_ARGUMENT,"TYPE_ARGUMENT",first,LT(1))).add(typeArgument_AST)); currentAST.root = typeArgument_AST; currentAST.child = typeArgument_AST!=null &&typeArgument_AST.getFirstChild()!=null ? typeArgument_AST.getFirstChild() : typeArgument_AST; currentAST.advanceChildToEnd(); } typeArgument_AST = (AST)currentAST.root; returnAST = typeArgument_AST; } public final void wildcardType() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST wildcardType_AST = null; Token q = null; AST q_AST = null; q = LT(1); q_AST = astFactory.create(q); astFactory.makeASTRoot(currentAST, q_AST); match(QUESTION); if ( inputState.guessing==0 ) { q_AST.setType(WILDCARD_TYPE); } { boolean synPredMatched30 = false; if (((LA(1)==LITERAL_extends||LA(1)==LITERAL_super) && (LA(2)==IDENT))) { int _m30 = mark(); synPredMatched30 = true; inputState.guessing++; try { { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); break; } case LITERAL_super: { match(LITERAL_super); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException pe) { synPredMatched30 = false; } rewind(_m30); inputState.guessing--; } if ( synPredMatched30 ) { typeArgumentBounds(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_6.member(LA(1))) && (_tokenSet_7.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } wildcardType_AST = (AST)currentAST.root; returnAST = wildcardType_AST; } public final void typeArgumentBounds() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentBounds_AST = null; boolean isUpperBounds = false; Token first = LT(1); { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); if ( inputState.guessing==0 ) { isUpperBounds=true; } break; } case LITERAL_super: { match(LITERAL_super); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { typeArgumentBounds_AST = (AST)currentAST.root; if (isUpperBounds) { typeArgumentBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1))).add(typeArgumentBounds_AST)); } else { typeArgumentBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_LOWER_BOUNDS,"TYPE_LOWER_BOUNDS",first,LT(1))).add(typeArgumentBounds_AST)); } currentAST.root = typeArgumentBounds_AST; currentAST.child = typeArgumentBounds_AST!=null &&typeArgumentBounds_AST.getFirstChild()!=null ? typeArgumentBounds_AST.getFirstChild() : typeArgumentBounds_AST; currentAST.advanceChildToEnd(); } typeArgumentBounds_AST = (AST)currentAST.root; returnAST = typeArgumentBounds_AST; } protected final void typeArgumentsOrParametersEnd() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentsOrParametersEnd_AST = null; switch ( LA(1)) { case GT: { match(GT); if ( inputState.guessing==0 ) { ltCounter-=1; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } case SR: { match(SR); if ( inputState.guessing==0 ) { ltCounter-=2; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } case BSR: { match(BSR); if ( inputState.guessing==0 ) { ltCounter-=3; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeArgumentsOrParametersEnd_AST; } public final void builtInType() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInType_AST = null; switch ( LA(1)) { case LITERAL_void: { AST tmp37_AST = null; tmp37_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp37_AST); match(LITERAL_void); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_boolean: { AST tmp38_AST = null; tmp38_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp38_AST); match(LITERAL_boolean); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_byte: { AST tmp39_AST = null; tmp39_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp39_AST); match(LITERAL_byte); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_char: { AST tmp40_AST = null; tmp40_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp40_AST); match(LITERAL_char); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_short: { AST tmp41_AST = null; tmp41_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp41_AST); match(LITERAL_short); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_int: { AST tmp42_AST = null; tmp42_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp42_AST); match(LITERAL_int); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_float: { AST tmp43_AST = null; tmp43_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp43_AST); match(LITERAL_float); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_long: { AST tmp44_AST = null; tmp44_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp44_AST); match(LITERAL_long); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_double: { AST tmp45_AST = null; tmp45_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp45_AST); match(LITERAL_double); builtInType_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = builtInType_AST; } public final void type() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST type_AST = null; switch ( LA(1)) { case IDENT: { classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); type_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInType(); astFactory.addASTChild(currentAST, returnAST); type_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = type_AST; } public final void modifier() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifier_AST = null; switch ( LA(1)) { case LITERAL_private: { AST tmp46_AST = null; tmp46_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp46_AST); match(LITERAL_private); modifier_AST = (AST)currentAST.root; break; } case LITERAL_public: { AST tmp47_AST = null; tmp47_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp47_AST); match(LITERAL_public); modifier_AST = (AST)currentAST.root; break; } case LITERAL_protected: { AST tmp48_AST = null; tmp48_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp48_AST); match(LITERAL_protected); modifier_AST = (AST)currentAST.root; break; } case LITERAL_static: { AST tmp49_AST = null; tmp49_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp49_AST); match(LITERAL_static); modifier_AST = (AST)currentAST.root; break; } case LITERAL_transient: { AST tmp50_AST = null; tmp50_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp50_AST); match(LITERAL_transient); modifier_AST = (AST)currentAST.root; break; } case FINAL: { AST tmp51_AST = null; tmp51_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp51_AST); match(FINAL); modifier_AST = (AST)currentAST.root; break; } case ABSTRACT: { AST tmp52_AST = null; tmp52_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp52_AST); match(ABSTRACT); modifier_AST = (AST)currentAST.root; break; } case LITERAL_native: { AST tmp53_AST = null; tmp53_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp53_AST); match(LITERAL_native); modifier_AST = (AST)currentAST.root; break; } case LITERAL_threadsafe: { AST tmp54_AST = null; tmp54_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp54_AST); match(LITERAL_threadsafe); modifier_AST = (AST)currentAST.root; break; } case LITERAL_synchronized: { AST tmp55_AST = null; tmp55_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp55_AST); match(LITERAL_synchronized); modifier_AST = (AST)currentAST.root; break; } case LITERAL_volatile: { AST tmp56_AST = null; tmp56_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp56_AST); match(LITERAL_volatile); modifier_AST = (AST)currentAST.root; break; } case STRICTFP: { AST tmp57_AST = null; tmp57_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp57_AST); match(STRICTFP); modifier_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = modifier_AST; } public final void annotation() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotation_AST = null; AST i_AST = null; AST args_AST = null; Token first = LT(1); match(AT); identifier(); i_AST = (AST)returnAST; { switch ( LA(1)) { case LPAREN: { match(LPAREN); { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case AT: case LPAREN: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { annotationArguments(); args_AST = (AST)returnAST; break; } case RPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RPAREN); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_package: case SEMI: case LITERAL_static: case IDENT: case LT: case COMMA: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case RPAREN: case RCURLY: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { annotation_AST = (AST)currentAST.root; annotation_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(ANNOTATION,"ANNOTATION",first,LT(1))).add(i_AST).add(args_AST)); currentAST.root = annotation_AST; currentAST.child = annotation_AST!=null &&annotation_AST.getFirstChild()!=null ? annotation_AST.getFirstChild() : annotation_AST; currentAST.advanceChildToEnd(); } returnAST = annotation_AST; } public final void annotationArguments() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationArguments_AST = null; if ((_tokenSet_8.member(LA(1))) && (_tokenSet_9.member(LA(2)))) { annotationMemberValueInitializer(); astFactory.addASTChild(currentAST, returnAST); annotationArguments_AST = (AST)currentAST.root; } else if ((LA(1)==IDENT) && (LA(2)==ASSIGN)) { anntotationMemberValuePairs(); astFactory.addASTChild(currentAST, returnAST); annotationArguments_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = annotationArguments_AST; } public final void annotationMemberValueInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberValueInitializer_AST = null; switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { conditionalExpression(); astFactory.addASTChild(currentAST, returnAST); annotationMemberValueInitializer_AST = (AST)currentAST.root; break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); annotationMemberValueInitializer_AST = (AST)currentAST.root; break; } case LCURLY: { annotationMemberArrayInitializer(); astFactory.addASTChild(currentAST, returnAST); annotationMemberValueInitializer_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = annotationMemberValueInitializer_AST; } public final void anntotationMemberValuePairs() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST anntotationMemberValuePairs_AST = null; annotationMemberValuePair(); astFactory.addASTChild(currentAST, returnAST); { _loop66: do { if ((LA(1)==COMMA)) { match(COMMA); annotationMemberValuePair(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop66; } } while (true); } anntotationMemberValuePairs_AST = (AST)currentAST.root; returnAST = anntotationMemberValuePairs_AST; } public final void annotationMemberValuePair() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberValuePair_AST = null; Token i = null; AST i_AST = null; AST v_AST = null; Token first = LT(1); i = LT(1); i_AST = astFactory.create(i); match(IDENT); match(ASSIGN); annotationMemberValueInitializer(); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationMemberValuePair_AST = (AST)currentAST.root; annotationMemberValuePair_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",first,LT(1))).add(i_AST).add(v_AST)); currentAST.root = annotationMemberValuePair_AST; currentAST.child = annotationMemberValuePair_AST!=null &&annotationMemberValuePair_AST.getFirstChild()!=null ? annotationMemberValuePair_AST.getFirstChild() : annotationMemberValuePair_AST; currentAST.advanceChildToEnd(); } returnAST = annotationMemberValuePair_AST; } public final void conditionalExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST conditionalExpression_AST = null; logicalOrExpression(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case QUESTION: { AST tmp63_AST = null; tmp63_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp63_AST); match(QUESTION); assignmentExpression(); astFactory.addASTChild(currentAST, returnAST); match(COLON); conditionalExpression(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case RBRACK: case COMMA: case RPAREN: case ASSIGN: case RCURLY: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } conditionalExpression_AST = (AST)currentAST.root; returnAST = conditionalExpression_AST; } public final void annotationMemberArrayInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberArrayInitializer_AST = null; Token lc = null; AST lc_AST = null; lc = LT(1); lc_AST = astFactory.create(lc); astFactory.makeASTRoot(currentAST, lc_AST); match(LCURLY); if ( inputState.guessing==0 ) { lc_AST.setType(ANNOTATION_ARRAY_INIT); } { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case AT: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { annotationMemberArrayValueInitializer(); astFactory.addASTChild(currentAST, returnAST); { _loop72: do { if ((LA(1)==COMMA) && (_tokenSet_10.member(LA(2)))) { match(COMMA); annotationMemberArrayValueInitializer(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop72; } } while (true); } { switch ( LA(1)) { case COMMA: { match(COMMA); break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RCURLY); annotationMemberArrayInitializer_AST = (AST)currentAST.root; returnAST = annotationMemberArrayInitializer_AST; } public final void annotationMemberArrayValueInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberArrayValueInitializer_AST = null; switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { conditionalExpression(); astFactory.addASTChild(currentAST, returnAST); annotationMemberArrayValueInitializer_AST = (AST)currentAST.root; break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); annotationMemberArrayValueInitializer_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = annotationMemberArrayValueInitializer_AST; } public final void superClassClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST superClassClause_AST = null; AST c_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); classOrInterfaceType(false); c_AST = (AST)returnAST; break; } case LCURLY: case LITERAL_implements: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { superClassClause_AST = (AST)currentAST.root; superClassClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1))).add(c_AST)); currentAST.root = superClassClause_AST; currentAST.child = superClassClause_AST!=null &&superClassClause_AST.getFirstChild()!=null ? superClassClause_AST.getFirstChild() : superClassClause_AST; currentAST.advanceChildToEnd(); } returnAST = superClassClause_AST; } public final void typeParameters() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameters_AST = null; int currentLtLevel = 0; Token first = LT(1); if ( inputState.guessing==0 ) { currentLtLevel = ltCounter; } match(LT); if ( inputState.guessing==0 ) { ltCounter++; } typeParameter(); astFactory.addASTChild(currentAST, returnAST); { _loop85: do { if ((LA(1)==COMMA)) { match(COMMA); typeParameter(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop85; } } while (true); } { switch ( LA(1)) { case GT: case SR: case BSR: { typeArgumentsOrParametersEnd(); astFactory.addASTChild(currentAST, returnAST); break; } case IDENT: case LITERAL_extends: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_implements: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if (!((currentLtLevel != 0) || ltCounter == currentLtLevel)) throw new SemanticException("(currentLtLevel != 0) || ltCounter == currentLtLevel"); if ( inputState.guessing==0 ) { typeParameters_AST = (AST)currentAST.root; typeParameters_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_PARAMETERS,"TYPE_PARAMETERS",first,LT(1))).add(typeParameters_AST)); currentAST.root = typeParameters_AST; currentAST.child = typeParameters_AST!=null &&typeParameters_AST.getFirstChild()!=null ? typeParameters_AST.getFirstChild() : typeParameters_AST; currentAST.advanceChildToEnd(); } typeParameters_AST = (AST)currentAST.root; returnAST = typeParameters_AST; } public final void implementsClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST implementsClause_AST = null; Token i = null; AST i_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_implements: { i = LT(1); i_AST = astFactory.create(i); match(LITERAL_implements); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); { _loop133: do { if ((LA(1)==COMMA)) { match(COMMA); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); } else { break _loop133; } } while (true); } break; } case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { implementsClause_AST = (AST)currentAST.root; implementsClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE",first,LT(1))).add(implementsClause_AST)); currentAST.root = implementsClause_AST; currentAST.child = implementsClause_AST!=null &&implementsClause_AST.getFirstChild()!=null ? implementsClause_AST.getFirstChild() : implementsClause_AST; currentAST.advanceChildToEnd(); } implementsClause_AST = (AST)currentAST.root; returnAST = implementsClause_AST; } public final void classBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classBlock_AST = null; match(LCURLY); { _loop95: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LCURLY: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { match(SEMI); break; } default: { break _loop95; } } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { classBlock_AST = (AST)currentAST.root; classBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(OBJBLOCK,"OBJBLOCK")).add(classBlock_AST)); currentAST.root = classBlock_AST; currentAST.child = classBlock_AST!=null &&classBlock_AST.getFirstChild()!=null ? classBlock_AST.getFirstChild() : classBlock_AST; currentAST.advanceChildToEnd(); } classBlock_AST = (AST)currentAST.root; returnAST = classBlock_AST; } public final void interfaceExtends() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceExtends_AST = null; Token e = null; AST e_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_extends: { e = LT(1); e_AST = astFactory.create(e); match(LITERAL_extends); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); { _loop129: do { if ((LA(1)==COMMA)) { match(COMMA); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); } else { break _loop129; } } while (true); } break; } case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { interfaceExtends_AST = (AST)currentAST.root; interfaceExtends_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1))).add(interfaceExtends_AST)); currentAST.root = interfaceExtends_AST; currentAST.child = interfaceExtends_AST!=null &&interfaceExtends_AST.getFirstChild()!=null ? interfaceExtends_AST.getFirstChild() : interfaceExtends_AST; currentAST.advanceChildToEnd(); } interfaceExtends_AST = (AST)currentAST.root; returnAST = interfaceExtends_AST; } public final void interfaceBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceBlock_AST = null; match(LCURLY); { _loop98: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { interfaceField(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { match(SEMI); break; } default: { break _loop98; } } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { interfaceBlock_AST = (AST)currentAST.root; interfaceBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(OBJBLOCK,"OBJBLOCK")).add(interfaceBlock_AST)); currentAST.root = interfaceBlock_AST; currentAST.child = interfaceBlock_AST!=null &&interfaceBlock_AST.getFirstChild()!=null ? interfaceBlock_AST.getFirstChild() : interfaceBlock_AST; currentAST.advanceChildToEnd(); } interfaceBlock_AST = (AST)currentAST.root; returnAST = interfaceBlock_AST; } public final void enumBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumBlock_AST = null; match(LCURLY); { switch ( LA(1)) { case IDENT: case AT: { enumConstant(); astFactory.addASTChild(currentAST, returnAST); { _loop105: do { if ((LA(1)==COMMA) && (LA(2)==IDENT||LA(2)==AT)) { match(COMMA); enumConstant(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop105; } } while (true); } { switch ( LA(1)) { case COMMA: { match(COMMA); break; } case SEMI: case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case SEMI: case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case SEMI: { match(SEMI); { _loop109: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LCURLY: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { match(SEMI); break; } default: { break _loop109; } } } while (true); } break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RCURLY); if ( inputState.guessing==0 ) { enumBlock_AST = (AST)currentAST.root; enumBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(OBJBLOCK,"OBJBLOCK")).add(enumBlock_AST)); currentAST.root = enumBlock_AST; currentAST.child = enumBlock_AST!=null &&enumBlock_AST.getFirstChild()!=null ? enumBlock_AST.getFirstChild() : enumBlock_AST; currentAST.advanceChildToEnd(); } enumBlock_AST = (AST)currentAST.root; returnAST = enumBlock_AST; } public final void annotationBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationBlock_AST = null; match(LCURLY); { _loop101: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { annotationField(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { match(SEMI); break; } default: { break _loop101; } } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { annotationBlock_AST = (AST)currentAST.root; annotationBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(OBJBLOCK,"OBJBLOCK")).add(annotationBlock_AST)); currentAST.root = annotationBlock_AST; currentAST.child = annotationBlock_AST!=null &&annotationBlock_AST.getFirstChild()!=null ? annotationBlock_AST.getFirstChild() : annotationBlock_AST; currentAST.advanceChildToEnd(); } annotationBlock_AST = (AST)currentAST.root; returnAST = annotationBlock_AST; } public final void typeParameter() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameter_AST = null; Token id = null; AST id_AST = null; Token first = LT(1); { id = LT(1); id_AST = astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(IDENT); } { if ((LA(1)==LITERAL_extends) && (LA(2)==IDENT)) { typeParameterBounds(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_11.member(LA(1))) && (_tokenSet_12.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { typeParameter_AST = (AST)currentAST.root; typeParameter_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_PARAMETER,"TYPE_PARAMETER",first,LT(1))).add(typeParameter_AST)); currentAST.root = typeParameter_AST; currentAST.child = typeParameter_AST!=null &&typeParameter_AST.getFirstChild()!=null ? typeParameter_AST.getFirstChild() : typeParameter_AST; currentAST.advanceChildToEnd(); } typeParameter_AST = (AST)currentAST.root; returnAST = typeParameter_AST; } public final void typeParameterBounds() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameterBounds_AST = null; Token first = LT(1); match(LITERAL_extends); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); { _loop92: do { if ((LA(1)==BAND)) { match(BAND); classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); } else { break _loop92; } } while (true); } if ( inputState.guessing==0 ) { typeParameterBounds_AST = (AST)currentAST.root; typeParameterBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1))).add(typeParameterBounds_AST)); currentAST.root = typeParameterBounds_AST; currentAST.child = typeParameterBounds_AST!=null &&typeParameterBounds_AST.getFirstChild()!=null ? typeParameterBounds_AST.getFirstChild() : typeParameterBounds_AST; currentAST.advanceChildToEnd(); } typeParameterBounds_AST = (AST)currentAST.root; returnAST = typeParameterBounds_AST; } public final void classField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classField_AST = null; AST mods_AST = null; AST td_AST = null; AST tp_AST = null; AST h_AST = null; AST s_AST = null; AST t_AST = null; AST param_AST = null; AST rt_AST = null; AST tc_AST = null; AST s2_AST = null; AST v_AST = null; AST s3_AST = null; AST s4_AST = null; Token first = LT(1); if ((_tokenSet_13.member(LA(1))) && (_tokenSet_14.member(LA(2)))) { modifiers(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = td_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { if ((LA(1)==IDENT) && (LA(2)==LPAREN)) { ctorHead(); h_AST = (AST)returnAST; constructorBody(); s_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods_AST).add(tp_AST).add(h_AST).add(s_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else if ((_tokenSet_15.member(LA(1))) && (_tokenSet_16.member(LA(2)))) { typeSpec(false); t_AST = (AST)returnAST; { if ((LA(1)==IDENT) && (LA(2)==LPAREN)) { AST tmp90_AST = null; tmp90_AST = astFactory.create(LT(1)); match(IDENT); match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); declaratorBrackets(t_AST); rt_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_throws: { throwsClause(); tc_AST = (AST)returnAST; break; } case SEMI: case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LCURLY: { compoundStatement(); s2_AST = (AST)returnAST; break; } case SEMI: { AST tmp93_AST = null; tmp93_AST = astFactory.create(LT(1)); match(SEMI); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(8)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods_AST).add(tp_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(rt_AST))).add(tmp90_AST).add(param_AST).add(tc_AST).add(s2_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT) && (_tokenSet_17.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; AST tmp94_AST = null; tmp94_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = v_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((LA(1)==LITERAL_static) && (LA(2)==LCURLY)) { match(LITERAL_static); compoundStatement(); s3_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(STATIC_INIT,"STATIC_INIT",first,LT(1))).add(s3_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==LCURLY)) { compoundStatement(); s4_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1))).add(s4_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = classField_AST; } public final void interfaceField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceField_AST = null; AST mods_AST = null; AST td_AST = null; AST tp_AST = null; AST t_AST = null; AST param_AST = null; AST rt_AST = null; AST tc_AST = null; AST v_AST = null; Token first = LT(1); modifiers(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = td_AST; currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } typeSpec(false); t_AST = (AST)returnAST; { if ((LA(1)==IDENT) && (LA(2)==LPAREN)) { AST tmp96_AST = null; tmp96_AST = astFactory.create(LT(1)); match(IDENT); match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); declaratorBrackets(t_AST); rt_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_throws: { throwsClause(); tc_AST = (AST)returnAST; break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp99_AST = null; tmp99_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = (AST)astFactory.make( (new ASTArray(7)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods_AST).add(tp_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(rt_AST))).add(tmp96_AST).add(param_AST).add(tc_AST)); currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT) && (_tokenSet_17.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; AST tmp100_AST = null; tmp100_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = v_AST; currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } returnAST = interfaceField_AST; } public final void annotationField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationField_AST = null; AST mods_AST = null; AST td_AST = null; AST t_AST = null; Token i = null; AST i_AST = null; AST rt_AST = null; AST amvi_AST = null; AST v_AST = null; Token first = LT(1); modifiers(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = td_AST; currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeSpec(false); t_AST = (AST)returnAST; { if ((LA(1)==IDENT) && (LA(2)==LPAREN)) { i = LT(1); i_AST = astFactory.create(i); match(IDENT); match(LPAREN); match(RPAREN); declaratorBrackets(t_AST); rt_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_default: { match(LITERAL_default); annotationMemberValueInitializer(); amvi_AST = (AST)returnAST; break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp104_AST = null; tmp104_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(ANNOTATION_FIELD_DEF,"ANNOTATION_FIELD_DEF",first,LT(1))).add(mods_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(rt_AST))).add(i_AST).add(amvi_AST)); currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT) && (_tokenSet_17.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; AST tmp105_AST = null; tmp105_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = v_AST; currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } returnAST = annotationField_AST; } public final void enumConstant() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstant_AST = null; AST an_AST = null; Token i = null; AST i_AST = null; AST a_AST = null; AST b_AST = null; annotations(); an_AST = (AST)returnAST; i = LT(1); i_AST = astFactory.create(i); match(IDENT); { switch ( LA(1)) { case LPAREN: { match(LPAREN); argList(); a_AST = (AST)returnAST; match(RPAREN); break; } case SEMI: case COMMA: case LCURLY: case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LCURLY: { enumConstantBlock(); b_AST = (AST)returnAST; break; } case SEMI: case COMMA: case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { enumConstant_AST = (AST)currentAST.root; enumConstant_AST = (AST)astFactory.make( (new ASTArray(5)).add(astFactory.create(ENUM_CONSTANT_DEF,"ENUM_CONSTANT_DEF")).add(an_AST).add(i_AST).add(a_AST).add(b_AST)); currentAST.root = enumConstant_AST; currentAST.child = enumConstant_AST!=null &&enumConstant_AST.getFirstChild()!=null ? enumConstant_AST.getFirstChild() : enumConstant_AST; currentAST.advanceChildToEnd(); } returnAST = enumConstant_AST; } public final void declaratorBrackets( AST typ ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST declaratorBrackets_AST = null; Token lb = null; AST lb_AST = null; if ( inputState.guessing==0 ) { declaratorBrackets_AST = (AST)currentAST.root; declaratorBrackets_AST=typ; currentAST.root = declaratorBrackets_AST; currentAST.child = declaratorBrackets_AST!=null &&declaratorBrackets_AST.getFirstChild()!=null ? declaratorBrackets_AST.getFirstChild() : declaratorBrackets_AST; currentAST.advanceChildToEnd(); } { _loop159: do { if ((LA(1)==LBRACK)) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { break _loop159; } } while (true); } declaratorBrackets_AST = (AST)currentAST.root; returnAST = declaratorBrackets_AST; } public final void argList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST argList_AST = null; Token first = LT(1); { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expressionList(); astFactory.addASTChild(currentAST, returnAST); break; } case RPAREN: { if ( inputState.guessing==0 ) { argList_AST = (AST)currentAST.root; argList_AST = create(ELIST,"ELIST",first,LT(1)); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } argList_AST = (AST)currentAST.root; returnAST = argList_AST; } public final void enumConstantBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstantBlock_AST = null; match(LCURLY); { _loop119: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LCURLY: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { enumConstantField(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { match(SEMI); break; } default: { break _loop119; } } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { enumConstantBlock_AST = (AST)currentAST.root; enumConstantBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(OBJBLOCK,"OBJBLOCK")).add(enumConstantBlock_AST)); currentAST.root = enumConstantBlock_AST; currentAST.child = enumConstantBlock_AST!=null &&enumConstantBlock_AST.getFirstChild()!=null ? enumConstantBlock_AST.getFirstChild() : enumConstantBlock_AST; currentAST.advanceChildToEnd(); } enumConstantBlock_AST = (AST)currentAST.root; returnAST = enumConstantBlock_AST; } public final void enumConstantField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstantField_AST = null; AST mods_AST = null; AST td_AST = null; AST tp_AST = null; AST t_AST = null; AST param_AST = null; AST rt_AST = null; AST tc_AST = null; AST s2_AST = null; AST v_AST = null; AST s4_AST = null; Token first = LT(1); switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { modifiers(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case AT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = td_AST; currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } typeSpec(false); t_AST = (AST)returnAST; { if ((LA(1)==IDENT) && (LA(2)==LPAREN)) { AST tmp112_AST = null; tmp112_AST = astFactory.create(LT(1)); match(IDENT); match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); declaratorBrackets(t_AST); rt_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_throws: { throwsClause(); tc_AST = (AST)returnAST; break; } case SEMI: case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LCURLY: { compoundStatement(); s2_AST = (AST)returnAST; break; } case SEMI: { AST tmp115_AST = null; tmp115_AST = astFactory.create(LT(1)); match(SEMI); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = (AST)astFactory.make( (new ASTArray(8)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods_AST).add(tp_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(rt_AST))).add(tmp112_AST).add(param_AST).add(tc_AST).add(s2_AST)); currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT) && (_tokenSet_17.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; AST tmp116_AST = null; tmp116_AST = astFactory.create(LT(1)); match(SEMI); if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = v_AST; currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LCURLY: { compoundStatement(); s4_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1))).add(s4_AST)); currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = enumConstantField_AST; } public final void parameterDeclarationList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterDeclarationList_AST = null; Token first = LT(1); { boolean synPredMatched176 = false; if (((_tokenSet_18.member(LA(1))) && (_tokenSet_19.member(LA(2))))) { int _m176 = mark(); synPredMatched176 = true; inputState.guessing++; try { { parameterDeclaration(); } } catch (RecognitionException pe) { synPredMatched176 = false; } rewind(_m176); inputState.guessing--; } if ( synPredMatched176 ) { parameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); { _loop180: do { boolean synPredMatched179 = false; if (((LA(1)==COMMA) && (_tokenSet_18.member(LA(2))))) { int _m179 = mark(); synPredMatched179 = true; inputState.guessing++; try { { match(COMMA); parameterDeclaration(); } } catch (RecognitionException pe) { synPredMatched179 = false; } rewind(_m179); inputState.guessing--; } if ( synPredMatched179 ) { match(COMMA); parameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop180; } } while (true); } { switch ( LA(1)) { case COMMA: { match(COMMA); variableLengthParameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); break; } case RPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((_tokenSet_18.member(LA(1))) && (_tokenSet_20.member(LA(2)))) { variableLengthParameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==RPAREN)) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { parameterDeclarationList_AST = (AST)currentAST.root; parameterDeclarationList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(PARAMETERS,"PARAMETERS",first,LT(1))).add(parameterDeclarationList_AST)); currentAST.root = parameterDeclarationList_AST; currentAST.child = parameterDeclarationList_AST!=null &¶meterDeclarationList_AST.getFirstChild()!=null ? parameterDeclarationList_AST.getFirstChild() : parameterDeclarationList_AST; currentAST.advanceChildToEnd(); } parameterDeclarationList_AST = (AST)currentAST.root; returnAST = parameterDeclarationList_AST; } public final void throwsClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST throwsClause_AST = null; AST tmp119_AST = null; tmp119_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp119_AST); match(LITERAL_throws); identifier(); astFactory.addASTChild(currentAST, returnAST); { _loop172: do { if ((LA(1)==COMMA)) { match(COMMA); identifier(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop172; } } while (true); } throwsClause_AST = (AST)currentAST.root; returnAST = throwsClause_AST; } public final void compoundStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST compoundStatement_AST = null; Token lc = null; AST lc_AST = null; lc = LT(1); lc_AST = astFactory.create(lc); astFactory.makeASTRoot(currentAST, lc_AST); match(LCURLY); if ( inputState.guessing==0 ) { lc_AST.setType(SLIST); } { _loop192: do { if ((_tokenSet_21.member(LA(1)))) { statement(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop192; } } while (true); } match(RCURLY); compoundStatement_AST = (AST)currentAST.root; returnAST = compoundStatement_AST; } public final void ctorHead() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST ctorHead_AST = null; AST tmp122_AST = null; tmp122_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp122_AST); match(IDENT); match(LPAREN); parameterDeclarationList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); { switch ( LA(1)) { case LITERAL_throws: { throwsClause(); astFactory.addASTChild(currentAST, returnAST); break; } case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } ctorHead_AST = (AST)currentAST.root; returnAST = ctorHead_AST; } public final void constructorBody() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constructorBody_AST = null; Token lc = null; AST lc_AST = null; lc = LT(1); lc_AST = astFactory.create(lc); astFactory.makeASTRoot(currentAST, lc_AST); match(LCURLY); if ( inputState.guessing==0 ) { lc_AST.setType(SLIST); } { if ((_tokenSet_22.member(LA(1))) && (_tokenSet_23.member(LA(2)))) { explicitConstructorInvocation(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_24.member(LA(1))) && (_tokenSet_25.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { _loop149: do { if ((_tokenSet_21.member(LA(1)))) { statement(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop149; } } while (true); } match(RCURLY); constructorBody_AST = (AST)currentAST.root; returnAST = constructorBody_AST; } /** Catch obvious constructor calls, but not the expr.super(...) calls */ public final void explicitConstructorInvocation() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST explicitConstructorInvocation_AST = null; Token lp1 = null; AST lp1_AST = null; Token lp2 = null; AST lp2_AST = null; { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_super: case LITERAL_this: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LITERAL_this: { match(LITERAL_this); lp1 = LT(1); lp1_AST = astFactory.create(lp1); astFactory.makeASTRoot(currentAST, lp1_AST); match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); match(SEMI); if ( inputState.guessing==0 ) { lp1_AST.setType(CTOR_CALL); } break; } case LITERAL_super: { match(LITERAL_super); lp2 = LT(1); lp2_AST = astFactory.create(lp2); astFactory.makeASTRoot(currentAST, lp2_AST); match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); match(SEMI); if ( inputState.guessing==0 ) { lp2_AST.setType(SUPER_CTOR_CALL); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } explicitConstructorInvocation_AST = (AST)currentAST.root; returnAST = explicitConstructorInvocation_AST; } public final void statement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST statement_AST = null; AST m_AST = null; Token c = null; AST c_AST = null; Token s = null; AST s_AST = null; switch ( LA(1)) { case LCURLY: { compoundStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_if: { AST tmp132_AST = null; tmp132_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp132_AST); match(LITERAL_if); match(LPAREN); expression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); statement(); astFactory.addASTChild(currentAST, returnAST); { if ((LA(1)==LITERAL_else) && (_tokenSet_21.member(LA(2)))) { match(LITERAL_else); statement(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_26.member(LA(1))) && (_tokenSet_27.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } statement_AST = (AST)currentAST.root; break; } case LITERAL_for: { forStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_while: { AST tmp136_AST = null; tmp136_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp136_AST); match(LITERAL_while); match(LPAREN); expression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); statement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_do: { AST tmp139_AST = null; tmp139_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp139_AST); match(LITERAL_do); statement(); astFactory.addASTChild(currentAST, returnAST); match(LITERAL_while); match(LPAREN); expression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); match(SEMI); statement_AST = (AST)currentAST.root; break; } case LITERAL_break: { AST tmp144_AST = null; tmp144_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp144_AST); match(LITERAL_break); { switch ( LA(1)) { case IDENT: { AST tmp145_AST = null; tmp145_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp145_AST); match(IDENT); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(SEMI); statement_AST = (AST)currentAST.root; break; } case LITERAL_continue: { AST tmp147_AST = null; tmp147_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp147_AST); match(LITERAL_continue); { switch ( LA(1)) { case IDENT: { AST tmp148_AST = null; tmp148_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp148_AST); match(IDENT); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(SEMI); statement_AST = (AST)currentAST.root; break; } case LITERAL_return: { AST tmp150_AST = null; tmp150_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp150_AST); match(LITERAL_return); { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expression(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(SEMI); statement_AST = (AST)currentAST.root; break; } case LITERAL_switch: { AST tmp152_AST = null; tmp152_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp152_AST); match(LITERAL_switch); match(LPAREN); expression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); match(LCURLY); { _loop201: do { if ((LA(1)==LITERAL_default||LA(1)==LITERAL_case)) { casesGroup(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop201; } } while (true); } match(RCURLY); statement_AST = (AST)currentAST.root; break; } case LITERAL_try: { tryBlock(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_throw: { AST tmp157_AST = null; tmp157_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp157_AST); match(LITERAL_throw); expression(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); statement_AST = (AST)currentAST.root; break; } case LITERAL_assert: { AST tmp159_AST = null; tmp159_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp159_AST); match(LITERAL_assert); expression(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case COLON: { match(COLON); expression(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(SEMI); statement_AST = (AST)currentAST.root; break; } case SEMI: { s = LT(1); s_AST = astFactory.create(s); astFactory.addASTChild(currentAST, s_AST); match(SEMI); if ( inputState.guessing==0 ) { s_AST.setType(EMPTY_STAT); } statement_AST = (AST)currentAST.root; break; } default: boolean synPredMatched195 = false; if (((_tokenSet_28.member(LA(1))) && (_tokenSet_29.member(LA(2))))) { int _m195 = mark(); synPredMatched195 = true; inputState.guessing++; try { { declaration(); } } catch (RecognitionException pe) { synPredMatched195 = false; } rewind(_m195); inputState.guessing--; } if ( synPredMatched195 ) { declaration(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); statement_AST = (AST)currentAST.root; } else if ((_tokenSet_30.member(LA(1))) && (_tokenSet_31.member(LA(2)))) { expression(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); statement_AST = (AST)currentAST.root; } else if ((_tokenSet_32.member(LA(1))) && (_tokenSet_33.member(LA(2)))) { modifiers(); m_AST = (AST)returnAST; classDefinition(m_AST); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else if ((LA(1)==IDENT) && (LA(2)==COLON)) { AST tmp164_AST = null; tmp164_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp164_AST); match(IDENT); c = LT(1); c_AST = astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(LABELED_STAT); } statement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else if ((LA(1)==LITERAL_synchronized) && (LA(2)==LPAREN)) { AST tmp165_AST = null; tmp165_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp165_AST); match(LITERAL_synchronized); match(LPAREN); expression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); compoundStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = statement_AST; } /** Declaration of a variable. This can be a class/instance variable, * or a local variable in a method * It can also include possible initialization. */ public final void variableDeclarator( AST mods, AST t ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableDeclarator_AST = null; Token id = null; AST id_AST = null; AST d_AST = null; AST v_AST = null; Token first = LT(1); id = LT(1); id_AST = astFactory.create(id); match(IDENT); declaratorBrackets(t); d_AST = (AST)returnAST; varInitializer(); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { variableDeclarator_AST = (AST)currentAST.root; variableDeclarator_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1))).add(mods).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(d_AST))).add(id_AST).add(v_AST)); currentAST.root = variableDeclarator_AST; currentAST.child = variableDeclarator_AST!=null &&variableDeclarator_AST.getFirstChild()!=null ? variableDeclarator_AST.getFirstChild() : variableDeclarator_AST; currentAST.advanceChildToEnd(); } returnAST = variableDeclarator_AST; } public final void varInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST varInitializer_AST = null; { switch ( LA(1)) { case ASSIGN: { AST tmp168_AST = null; tmp168_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp168_AST); match(ASSIGN); initializer(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case COMMA: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } varInitializer_AST = (AST)currentAST.root; returnAST = varInitializer_AST; } public final void initializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST initializer_AST = null; switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expression(); astFactory.addASTChild(currentAST, returnAST); initializer_AST = (AST)currentAST.root; break; } case LCURLY: { arrayInitializer(); astFactory.addASTChild(currentAST, returnAST); initializer_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = initializer_AST; } public final void arrayInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST arrayInitializer_AST = null; Token lc = null; AST lc_AST = null; lc = LT(1); lc_AST = astFactory.create(lc); astFactory.makeASTRoot(currentAST, lc_AST); match(LCURLY); if ( inputState.guessing==0 ) { lc_AST.setType(ARRAY_INIT); } { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { initializer(); astFactory.addASTChild(currentAST, returnAST); { _loop165: do { if ((LA(1)==COMMA) && (_tokenSet_34.member(LA(2)))) { match(COMMA); initializer(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop165; } } while (true); } { switch ( LA(1)) { case COMMA: { match(COMMA); break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RCURLY); arrayInitializer_AST = (AST)currentAST.root; returnAST = arrayInitializer_AST; } public final void expression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST expression_AST = null; Token first = LT(1); assignmentExpression(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { expression_AST = (AST)currentAST.root; expression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(expression_AST)); currentAST.root = expression_AST; currentAST.child = expression_AST!=null &&expression_AST.getFirstChild()!=null ? expression_AST.getFirstChild() : expression_AST; currentAST.advanceChildToEnd(); } expression_AST = (AST)currentAST.root; returnAST = expression_AST; } public final void parameterDeclaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterDeclaration_AST = null; AST pm_AST = null; AST t_AST = null; Token id = null; AST id_AST = null; AST pd_AST = null; Token first = LT(1); parameterModifier(); pm_AST = (AST)returnAST; typeSpec(false); t_AST = (AST)returnAST; id = LT(1); id_AST = astFactory.create(id); match(IDENT); declaratorBrackets(t_AST); pd_AST = (AST)returnAST; if ( inputState.guessing==0 ) { parameterDeclaration_AST = (AST)currentAST.root; parameterDeclaration_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1))).add(pm_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(pd_AST))).add(id_AST)); currentAST.root = parameterDeclaration_AST; currentAST.child = parameterDeclaration_AST!=null &¶meterDeclaration_AST.getFirstChild()!=null ? parameterDeclaration_AST.getFirstChild() : parameterDeclaration_AST; currentAST.advanceChildToEnd(); } returnAST = parameterDeclaration_AST; } public final void variableLengthParameterDeclaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableLengthParameterDeclaration_AST = null; AST pm_AST = null; AST t_AST = null; Token id = null; AST id_AST = null; AST pd_AST = null; Token first = LT(1); parameterModifier(); pm_AST = (AST)returnAST; typeSpec(false); t_AST = (AST)returnAST; match(TRIPLE_DOT); id = LT(1); id_AST = astFactory.create(id); match(IDENT); declaratorBrackets(t_AST); pd_AST = (AST)returnAST; if ( inputState.guessing==0 ) { variableLengthParameterDeclaration_AST = (AST)currentAST.root; variableLengthParameterDeclaration_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(VARIABLE_PARAMETER_DEF,"VARIABLE_PARAMETER_DEF",first,LT(1))).add(pm_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(pd_AST))).add(id_AST)); currentAST.root = variableLengthParameterDeclaration_AST; currentAST.child = variableLengthParameterDeclaration_AST!=null &&variableLengthParameterDeclaration_AST.getFirstChild()!=null ? variableLengthParameterDeclaration_AST.getFirstChild() : variableLengthParameterDeclaration_AST; currentAST.advanceChildToEnd(); } returnAST = variableLengthParameterDeclaration_AST; } public final void parameterModifier() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterModifier_AST = null; Token f = null; AST f_AST = null; Token first = LT(1); { _loop186: do { if ((LA(1)==AT) && (LA(2)==IDENT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop186; } } while (true); } { switch ( LA(1)) { case FINAL: { f = LT(1); f_AST = astFactory.create(f); astFactory.addASTChild(currentAST, f_AST); match(FINAL); break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case AT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop189: do { if ((LA(1)==AT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop189; } } while (true); } if ( inputState.guessing==0 ) { parameterModifier_AST = (AST)currentAST.root; parameterModifier_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))).add(parameterModifier_AST)); currentAST.root = parameterModifier_AST; currentAST.child = parameterModifier_AST!=null &¶meterModifier_AST.getFirstChild()!=null ? parameterModifier_AST.getFirstChild() : parameterModifier_AST; currentAST.advanceChildToEnd(); } parameterModifier_AST = (AST)currentAST.root; returnAST = parameterModifier_AST; } public final void forStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forStatement_AST = null; Token f = null; AST f_AST = null; f = LT(1); f_AST = astFactory.create(f); astFactory.makeASTRoot(currentAST, f_AST); match(LITERAL_for); match(LPAREN); { boolean synPredMatched206 = false; if (((_tokenSet_35.member(LA(1))) && (_tokenSet_36.member(LA(2))))) { int _m206 = mark(); synPredMatched206 = true; inputState.guessing++; try { { forInit(); match(SEMI); } } catch (RecognitionException pe) { synPredMatched206 = false; } rewind(_m206); inputState.guessing--; } if ( synPredMatched206 ) { traditionalForClause(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_18.member(LA(1))) && (_tokenSet_19.member(LA(2)))) { forEachClause(); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } match(RPAREN); statement(); astFactory.addASTChild(currentAST, returnAST); forStatement_AST = (AST)currentAST.root; returnAST = forStatement_AST; } public final void casesGroup() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST casesGroup_AST = null; { int _cnt211=0; _loop211: do { if ((LA(1)==LITERAL_default||LA(1)==LITERAL_case) && (_tokenSet_37.member(LA(2)))) { aCase(); astFactory.addASTChild(currentAST, returnAST); } else { if ( _cnt211>=1 ) { break _loop211; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt211++; } while (true); } caseSList(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { casesGroup_AST = (AST)currentAST.root; casesGroup_AST = (AST)astFactory.make( (new ASTArray(2)).add(astFactory.create(CASE_GROUP,"CASE_GROUP")).add(casesGroup_AST)); currentAST.root = casesGroup_AST; currentAST.child = casesGroup_AST!=null &&casesGroup_AST.getFirstChild()!=null ? casesGroup_AST.getFirstChild() : casesGroup_AST; currentAST.advanceChildToEnd(); } casesGroup_AST = (AST)currentAST.root; returnAST = casesGroup_AST; } public final void tryBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST tryBlock_AST = null; AST tmp175_AST = null; tmp175_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp175_AST); match(LITERAL_try); compoundStatement(); astFactory.addASTChild(currentAST, returnAST); { _loop227: do { if ((LA(1)==LITERAL_catch)) { handler(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop227; } } while (true); } { switch ( LA(1)) { case LITERAL_finally: { finallyClause(); astFactory.addASTChild(currentAST, returnAST); break; } case FINAL: case ABSTRACT: case STRICTFP: case SEMI: case LITERAL_static: case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case AT: case LPAREN: case LCURLY: case RCURLY: case LITERAL_class: case LITERAL_default: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_do: case LITERAL_break: case LITERAL_continue: case LITERAL_return: case LITERAL_switch: case LITERAL_throw: case LITERAL_assert: case LITERAL_for: case LITERAL_case: case LITERAL_try: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } tryBlock_AST = (AST)currentAST.root; returnAST = tryBlock_AST; } public final void forInit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forInit_AST = null; Token first = LT(1); { boolean synPredMatched220 = false; if (((_tokenSet_28.member(LA(1))) && (_tokenSet_29.member(LA(2))))) { int _m220 = mark(); synPredMatched220 = true; inputState.guessing++; try { { declaration(); } } catch (RecognitionException pe) { synPredMatched220 = false; } rewind(_m220); inputState.guessing--; } if ( synPredMatched220 ) { declaration(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_30.member(LA(1))) && (_tokenSet_38.member(LA(2)))) { expressionList(); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==SEMI)) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { forInit_AST = (AST)currentAST.root; forInit_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_INIT,"FOR_INIT",first,LT(1))).add(forInit_AST)); currentAST.root = forInit_AST; currentAST.child = forInit_AST!=null &&forInit_AST.getFirstChild()!=null ? forInit_AST.getFirstChild() : forInit_AST; currentAST.advanceChildToEnd(); } forInit_AST = (AST)currentAST.root; returnAST = forInit_AST; } public final void traditionalForClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST traditionalForClause_AST = null; forInit(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); forCond(); astFactory.addASTChild(currentAST, returnAST); match(SEMI); forIter(); astFactory.addASTChild(currentAST, returnAST); traditionalForClause_AST = (AST)currentAST.root; returnAST = traditionalForClause_AST; } public final void forEachClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forEachClause_AST = null; AST p_AST = null; Token first = LT(1); parameterDeclaration(); p_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); match(COLON); expression(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { forEachClause_AST = (AST)currentAST.root; forEachClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_EACH_CLAUSE,"FOR_EACH_CLAUSE",first,LT(1))).add(forEachClause_AST)); currentAST.root = forEachClause_AST; currentAST.child = forEachClause_AST!=null &&forEachClause_AST.getFirstChild()!=null ? forEachClause_AST.getFirstChild() : forEachClause_AST; currentAST.advanceChildToEnd(); } forEachClause_AST = (AST)currentAST.root; returnAST = forEachClause_AST; } public final void forCond() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forCond_AST = null; Token first = LT(1); { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expression(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forCond_AST = (AST)currentAST.root; forCond_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_CONDITION,"FOR_CONDITION",first,LT(1))).add(forCond_AST)); currentAST.root = forCond_AST; currentAST.child = forCond_AST!=null &&forCond_AST.getFirstChild()!=null ? forCond_AST.getFirstChild() : forCond_AST; currentAST.advanceChildToEnd(); } forCond_AST = (AST)currentAST.root; returnAST = forCond_AST; } public final void forIter() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forIter_AST = null; Token first = LT(1); { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expressionList(); astFactory.addASTChild(currentAST, returnAST); break; } case RPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forIter_AST = (AST)currentAST.root; forIter_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_ITERATOR,"FOR_ITERATOR",first,LT(1))).add(forIter_AST)); currentAST.root = forIter_AST; currentAST.child = forIter_AST!=null &&forIter_AST.getFirstChild()!=null ? forIter_AST.getFirstChild() : forIter_AST; currentAST.advanceChildToEnd(); } forIter_AST = (AST)currentAST.root; returnAST = forIter_AST; } public final void aCase() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST aCase_AST = null; { switch ( LA(1)) { case LITERAL_case: { AST tmp179_AST = null; tmp179_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp179_AST); match(LITERAL_case); expression(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_default: { AST tmp180_AST = null; tmp180_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp180_AST); match(LITERAL_default); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(COLON); aCase_AST = (AST)currentAST.root; returnAST = aCase_AST; } public final void caseSList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST caseSList_AST = null; Token first = LT(1); { _loop216: do { if ((_tokenSet_21.member(LA(1)))) { statement(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop216; } } while (true); } if ( inputState.guessing==0 ) { caseSList_AST = (AST)currentAST.root; caseSList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(SLIST,"SLIST",first,LT(1))).add(caseSList_AST)); currentAST.root = caseSList_AST; currentAST.child = caseSList_AST!=null &&caseSList_AST.getFirstChild()!=null ? caseSList_AST.getFirstChild() : caseSList_AST; currentAST.advanceChildToEnd(); } caseSList_AST = (AST)currentAST.root; returnAST = caseSList_AST; } public final void expressionList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST expressionList_AST = null; Token first = LT(1); expression(); astFactory.addASTChild(currentAST, returnAST); { _loop234: do { if ((LA(1)==COMMA)) { match(COMMA); expression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop234; } } while (true); } if ( inputState.guessing==0 ) { expressionList_AST = (AST)currentAST.root; expressionList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(ELIST,"ELIST",first,LT(1))).add(expressionList_AST)); currentAST.root = expressionList_AST; currentAST.child = expressionList_AST!=null &&expressionList_AST.getFirstChild()!=null ? expressionList_AST.getFirstChild() : expressionList_AST; currentAST.advanceChildToEnd(); } expressionList_AST = (AST)currentAST.root; returnAST = expressionList_AST; } public final void handler() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST handler_AST = null; AST tmp183_AST = null; tmp183_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp183_AST); match(LITERAL_catch); match(LPAREN); parameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); compoundStatement(); astFactory.addASTChild(currentAST, returnAST); handler_AST = (AST)currentAST.root; returnAST = handler_AST; } public final void finallyClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST finallyClause_AST = null; AST tmp186_AST = null; tmp186_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp186_AST); match(LITERAL_finally); compoundStatement(); astFactory.addASTChild(currentAST, returnAST); finallyClause_AST = (AST)currentAST.root; returnAST = finallyClause_AST; } public final void assignmentExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST assignmentExpression_AST = null; conditionalExpression(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case ASSIGN: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: { { switch ( LA(1)) { case ASSIGN: { AST tmp187_AST = null; tmp187_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp187_AST); match(ASSIGN); break; } case PLUS_ASSIGN: { AST tmp188_AST = null; tmp188_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp188_AST); match(PLUS_ASSIGN); break; } case MINUS_ASSIGN: { AST tmp189_AST = null; tmp189_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp189_AST); match(MINUS_ASSIGN); break; } case STAR_ASSIGN: { AST tmp190_AST = null; tmp190_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp190_AST); match(STAR_ASSIGN); break; } case DIV_ASSIGN: { AST tmp191_AST = null; tmp191_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp191_AST); match(DIV_ASSIGN); break; } case MOD_ASSIGN: { AST tmp192_AST = null; tmp192_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp192_AST); match(MOD_ASSIGN); break; } case SR_ASSIGN: { AST tmp193_AST = null; tmp193_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp193_AST); match(SR_ASSIGN); break; } case BSR_ASSIGN: { AST tmp194_AST = null; tmp194_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp194_AST); match(BSR_ASSIGN); break; } case SL_ASSIGN: { AST tmp195_AST = null; tmp195_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp195_AST); match(SL_ASSIGN); break; } case BAND_ASSIGN: { AST tmp196_AST = null; tmp196_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp196_AST); match(BAND_ASSIGN); break; } case BXOR_ASSIGN: { AST tmp197_AST = null; tmp197_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp197_AST); match(BXOR_ASSIGN); break; } case BOR_ASSIGN: { AST tmp198_AST = null; tmp198_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp198_AST); match(BOR_ASSIGN); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } assignmentExpression(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case RBRACK: case COMMA: case RPAREN: case RCURLY: case COLON: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } assignmentExpression_AST = (AST)currentAST.root; returnAST = assignmentExpression_AST; } public final void logicalOrExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST logicalOrExpression_AST = null; logicalAndExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop242: do { if ((LA(1)==LOR)) { AST tmp199_AST = null; tmp199_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp199_AST); match(LOR); logicalAndExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop242; } } while (true); } logicalOrExpression_AST = (AST)currentAST.root; returnAST = logicalOrExpression_AST; } public final void logicalAndExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST logicalAndExpression_AST = null; inclusiveOrExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop245: do { if ((LA(1)==LAND)) { AST tmp200_AST = null; tmp200_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp200_AST); match(LAND); inclusiveOrExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop245; } } while (true); } logicalAndExpression_AST = (AST)currentAST.root; returnAST = logicalAndExpression_AST; } public final void inclusiveOrExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST inclusiveOrExpression_AST = null; exclusiveOrExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop248: do { if ((LA(1)==BOR)) { AST tmp201_AST = null; tmp201_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp201_AST); match(BOR); exclusiveOrExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop248; } } while (true); } inclusiveOrExpression_AST = (AST)currentAST.root; returnAST = inclusiveOrExpression_AST; } public final void exclusiveOrExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST exclusiveOrExpression_AST = null; andExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop251: do { if ((LA(1)==BXOR)) { AST tmp202_AST = null; tmp202_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp202_AST); match(BXOR); andExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop251; } } while (true); } exclusiveOrExpression_AST = (AST)currentAST.root; returnAST = exclusiveOrExpression_AST; } public final void andExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST andExpression_AST = null; equalityExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop254: do { if ((LA(1)==BAND)) { AST tmp203_AST = null; tmp203_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp203_AST); match(BAND); equalityExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop254; } } while (true); } andExpression_AST = (AST)currentAST.root; returnAST = andExpression_AST; } public final void equalityExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST equalityExpression_AST = null; relationalExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop258: do { if ((LA(1)==NOT_EQUAL||LA(1)==EQUAL)) { { switch ( LA(1)) { case NOT_EQUAL: { AST tmp204_AST = null; tmp204_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp204_AST); match(NOT_EQUAL); break; } case EQUAL: { AST tmp205_AST = null; tmp205_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp205_AST); match(EQUAL); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } relationalExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop258; } } while (true); } equalityExpression_AST = (AST)currentAST.root; returnAST = equalityExpression_AST; } public final void relationalExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST relationalExpression_AST = null; shiftExpression(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case SEMI: case RBRACK: case QUESTION: case LT: case COMMA: case GT: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: { { _loop263: do { if ((_tokenSet_39.member(LA(1)))) { { switch ( LA(1)) { case LT: { AST tmp206_AST = null; tmp206_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp206_AST); match(LT); break; } case GT: { AST tmp207_AST = null; tmp207_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp207_AST); match(GT); break; } case LE: { AST tmp208_AST = null; tmp208_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp208_AST); match(LE); break; } case GE: { AST tmp209_AST = null; tmp209_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp209_AST); match(GE); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } shiftExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop263; } } while (true); } break; } case LITERAL_instanceof: { AST tmp210_AST = null; tmp210_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp210_AST); match(LITERAL_instanceof); typeSpec(true); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } relationalExpression_AST = (AST)currentAST.root; returnAST = relationalExpression_AST; } public final void shiftExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST shiftExpression_AST = null; additiveExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop267: do { if ((_tokenSet_40.member(LA(1)))) { { switch ( LA(1)) { case SL: { AST tmp211_AST = null; tmp211_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp211_AST); match(SL); break; } case SR: { AST tmp212_AST = null; tmp212_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp212_AST); match(SR); break; } case BSR: { AST tmp213_AST = null; tmp213_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp213_AST); match(BSR); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } additiveExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop267; } } while (true); } shiftExpression_AST = (AST)currentAST.root; returnAST = shiftExpression_AST; } public final void additiveExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST additiveExpression_AST = null; multiplicativeExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop271: do { if ((LA(1)==PLUS||LA(1)==MINUS)) { { switch ( LA(1)) { case PLUS: { AST tmp214_AST = null; tmp214_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp214_AST); match(PLUS); break; } case MINUS: { AST tmp215_AST = null; tmp215_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp215_AST); match(MINUS); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } multiplicativeExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop271; } } while (true); } additiveExpression_AST = (AST)currentAST.root; returnAST = additiveExpression_AST; } public final void multiplicativeExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST multiplicativeExpression_AST = null; unaryExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop275: do { if ((_tokenSet_41.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp216_AST = null; tmp216_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp216_AST); match(STAR); break; } case DIV: { AST tmp217_AST = null; tmp217_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp217_AST); match(DIV); break; } case MOD: { AST tmp218_AST = null; tmp218_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp218_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } unaryExpression(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop275; } } while (true); } multiplicativeExpression_AST = (AST)currentAST.root; returnAST = multiplicativeExpression_AST; } public final void unaryExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST unaryExpression_AST = null; switch ( LA(1)) { case INC: { AST tmp219_AST = null; tmp219_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp219_AST); match(INC); unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case DEC: { AST tmp220_AST = null; tmp220_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp220_AST); match(DEC); unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case MINUS: { AST tmp221_AST = null; tmp221_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp221_AST); match(MINUS); if ( inputState.guessing==0 ) { tmp221_AST.setType(UNARY_MINUS); } unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case PLUS: { AST tmp222_AST = null; tmp222_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp222_AST); match(PLUS); if ( inputState.guessing==0 ) { tmp222_AST.setType(UNARY_PLUS); } unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { unaryExpressionNotPlusMinus(); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = unaryExpression_AST; } public final void unaryExpressionNotPlusMinus() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST unaryExpressionNotPlusMinus_AST = null; Token lpb = null; AST lpb_AST = null; Token lp = null; AST lp_AST = null; switch ( LA(1)) { case BNOT: { AST tmp223_AST = null; tmp223_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp223_AST); match(BNOT); unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } case LNOT: { AST tmp224_AST = null; tmp224_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp224_AST); match(LNOT); unaryExpression(); astFactory.addASTChild(currentAST, returnAST); unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { { boolean synPredMatched280 = false; if (((LA(1)==LPAREN) && ((LA(2) >= LITERAL_void && LA(2) <= LITERAL_double)))) { int _m280 = mark(); synPredMatched280 = true; inputState.guessing++; try { { match(LPAREN); builtInTypeSpec(true); match(RPAREN); unaryExpression(); } } catch (RecognitionException pe) { synPredMatched280 = false; } rewind(_m280); inputState.guessing--; } if ( synPredMatched280 ) { lpb = LT(1); lpb_AST = astFactory.create(lpb); astFactory.makeASTRoot(currentAST, lpb_AST); match(LPAREN); if ( inputState.guessing==0 ) { lpb_AST.setType(TYPECAST); } builtInTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); unaryExpression(); astFactory.addASTChild(currentAST, returnAST); } else { boolean synPredMatched282 = false; if (((LA(1)==LPAREN) && (LA(2)==IDENT))) { int _m282 = mark(); synPredMatched282 = true; inputState.guessing++; try { { match(LPAREN); classTypeSpec(true); match(RPAREN); unaryExpressionNotPlusMinus(); } } catch (RecognitionException pe) { synPredMatched282 = false; } rewind(_m282); inputState.guessing--; } if ( synPredMatched282 ) { lp = LT(1); lp_AST = astFactory.create(lp); astFactory.makeASTRoot(currentAST, lp_AST); match(LPAREN); if ( inputState.guessing==0 ) { lp_AST.setType(TYPECAST); } classTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); unaryExpressionNotPlusMinus(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_42.member(LA(1))) && (_tokenSet_43.member(LA(2)))) { postfixExpression(); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } } unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = unaryExpressionNotPlusMinus_AST; } public final void postfixExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST postfixExpression_AST = null; Token lp = null; AST lp_AST = null; Token lp3 = null; AST lp3_AST = null; Token lps = null; AST lps_AST = null; Token lb = null; AST lb_AST = null; Token in = null; AST in_AST = null; Token de = null; AST de_AST = null; primaryExpression(); astFactory.addASTChild(currentAST, returnAST); { _loop291: do { if ((LA(1)==DOT) && (_tokenSet_44.member(LA(2)))) { AST tmp227_AST = null; tmp227_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp227_AST); match(DOT); { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case IDENT: case LITERAL_super: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case IDENT: { AST tmp228_AST = null; tmp228_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp228_AST); match(IDENT); { switch ( LA(1)) { case LPAREN: { lp = LT(1); lp_AST = astFactory.create(lp); astFactory.makeASTRoot(currentAST, lp_AST); match(LPAREN); if ( inputState.guessing==0 ) { lp_AST.setType(METHOD_CALL); } argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); break; } case SEMI: case LBRACK: case RBRACK: case DOT: case QUESTION: case LT: case COMMA: case GT: case SR: case BSR: case STAR: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: case LITERAL_instanceof: case SL: case PLUS: case MINUS: case DIV: case MOD: case INC: case DEC: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LITERAL_super: { AST tmp230_AST = null; tmp230_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp230_AST); match(LITERAL_super); { switch ( LA(1)) { case LPAREN: { lp3 = LT(1); lp3_AST = astFactory.create(lp3); astFactory.makeASTRoot(currentAST, lp3_AST); match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); if ( inputState.guessing==0 ) { lp3_AST.setType(SUPER_CTOR_CALL); } break; } case DOT: { AST tmp232_AST = null; tmp232_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp232_AST); match(DOT); { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp233_AST = null; tmp233_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp233_AST); match(IDENT); { switch ( LA(1)) { case LPAREN: { lps = LT(1); lps_AST = astFactory.create(lps); astFactory.makeASTRoot(currentAST, lps_AST); match(LPAREN); if ( inputState.guessing==0 ) { lps_AST.setType(METHOD_CALL); } argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); break; } case SEMI: case LBRACK: case RBRACK: case DOT: case QUESTION: case LT: case COMMA: case GT: case SR: case BSR: case STAR: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: case LITERAL_instanceof: case SL: case PLUS: case MINUS: case DIV: case MOD: case INC: case DEC: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((LA(1)==DOT) && (LA(2)==LITERAL_this)) { AST tmp235_AST = null; tmp235_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp235_AST); match(DOT); AST tmp236_AST = null; tmp236_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp236_AST); match(LITERAL_this); } else if ((LA(1)==DOT) && (LA(2)==LITERAL_new)) { AST tmp237_AST = null; tmp237_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp237_AST); match(DOT); newExpression(); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==LBRACK)) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(INDEX_OP); } expression(); astFactory.addASTChild(currentAST, returnAST); match(RBRACK); } else { break _loop291; } } while (true); } { switch ( LA(1)) { case INC: { in = LT(1); in_AST = astFactory.create(in); astFactory.makeASTRoot(currentAST, in_AST); match(INC); if ( inputState.guessing==0 ) { in_AST.setType(POST_INC); } break; } case DEC: { de = LT(1); de_AST = astFactory.create(de); astFactory.makeASTRoot(currentAST, de_AST); match(DEC); if ( inputState.guessing==0 ) { de_AST.setType(POST_DEC); } break; } case SEMI: case RBRACK: case QUESTION: case LT: case COMMA: case GT: case SR: case BSR: case STAR: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: case LITERAL_instanceof: case SL: case PLUS: case MINUS: case DIV: case MOD: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } postfixExpression_AST = (AST)currentAST.root; returnAST = postfixExpression_AST; } public final void primaryExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST primaryExpression_AST = null; Token lbt = null; AST lbt_AST = null; switch ( LA(1)) { case IDENT: case LT: { identPrimary(); astFactory.addASTChild(currentAST, returnAST); { if ((LA(1)==DOT) && (LA(2)==LITERAL_class)) { AST tmp239_AST = null; tmp239_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp239_AST); match(DOT); AST tmp240_AST = null; tmp240_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp240_AST); match(LITERAL_class); } else if ((_tokenSet_45.member(LA(1))) && (_tokenSet_46.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } primaryExpression_AST = (AST)currentAST.root; break; } case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { constant(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_true: { AST tmp241_AST = null; tmp241_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp241_AST); match(LITERAL_true); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_false: { AST tmp242_AST = null; tmp242_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp242_AST); match(LITERAL_false); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_null: { AST tmp243_AST = null; tmp243_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp243_AST); match(LITERAL_null); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_new: { newExpression(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_this: { AST tmp244_AST = null; tmp244_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp244_AST); match(LITERAL_this); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_super: { AST tmp245_AST = null; tmp245_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp245_AST); match(LITERAL_super); primaryExpression_AST = (AST)currentAST.root; break; } case LPAREN: { match(LPAREN); assignmentExpression(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInType(); astFactory.addASTChild(currentAST, returnAST); { _loop296: do { if ((LA(1)==LBRACK)) { lbt = LT(1); lbt_AST = astFactory.create(lbt); astFactory.makeASTRoot(currentAST, lbt_AST); match(LBRACK); if ( inputState.guessing==0 ) { lbt_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { break _loop296; } } while (true); } AST tmp249_AST = null; tmp249_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp249_AST); match(DOT); AST tmp250_AST = null; tmp250_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp250_AST); match(LITERAL_class); primaryExpression_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = primaryExpression_AST; } /** object instantiation. * Trees are built as illustrated by the following input/tree pairs: * * new T() * * new * | * T -- ELIST * | * arg1 -- arg2 -- .. -- argn * * new int[] * * new * | * int -- ARRAY_DECLARATOR * * new int[] {1,2} * * new * | * int -- ARRAY_DECLARATOR -- ARRAY_INIT * | * EXPR -- EXPR * | | * 1 2 * * new int[3] * new * | * int -- ARRAY_DECLARATOR * | * EXPR * | * 3 * * new int[1][2] * * new * | * int -- ARRAY_DECLARATOR * | * ARRAY_DECLARATOR -- EXPR * | | * EXPR 1 * | * 2 * */ public final void newExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST newExpression_AST = null; AST tmp251_AST = null; tmp251_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp251_AST); match(LITERAL_new); { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } type(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case LPAREN: { match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); { switch ( LA(1)) { case LCURLY: { classBlock(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case LBRACK: case RBRACK: case DOT: case QUESTION: case LT: case COMMA: case GT: case SR: case BSR: case STAR: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: case LITERAL_instanceof: case SL: case PLUS: case MINUS: case DIV: case MOD: case INC: case DEC: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LBRACK: { newArrayDeclarator(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case LCURLY: { arrayInitializer(); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: case LBRACK: case RBRACK: case DOT: case QUESTION: case LT: case COMMA: case GT: case SR: case BSR: case STAR: case RPAREN: case ASSIGN: case RCURLY: case BAND: case COLON: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case LOR: case LAND: case BOR: case BXOR: case NOT_EQUAL: case EQUAL: case LE: case GE: case LITERAL_instanceof: case SL: case PLUS: case MINUS: case DIV: case MOD: case INC: case DEC: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } newExpression_AST = (AST)currentAST.root; returnAST = newExpression_AST; } /** Match a, a.b.c refs, a.b.c(...) refs, a.b.c[], a.b.c[].class, * and a.b.c.class refs. Also this(...) and super(...). Match * this or super. */ public final void identPrimary() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST identPrimary_AST = null; AST ta1_AST = null; AST ta2_AST = null; Token lp = null; AST lp_AST = null; Token lbc = null; AST lbc_AST = null; { switch ( LA(1)) { case LT: { typeArguments(); ta1_AST = (AST)returnAST; break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp254_AST = null; tmp254_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp254_AST); match(IDENT); { _loop304: do { boolean synPredMatched302 = false; if (((LA(1)==DOT) && (LA(2)==IDENT||LA(2)==LT))) { int _m302 = mark(); synPredMatched302 = true; inputState.guessing++; try { { match(DOT); { switch ( LA(1)) { case LT: { typeArguments(); break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(IDENT); } } catch (RecognitionException pe) { synPredMatched302 = false; } rewind(_m302); inputState.guessing--; } if ( synPredMatched302 ) { AST tmp255_AST = null; tmp255_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp255_AST); match(DOT); { switch ( LA(1)) { case LT: { typeArguments(); ta2_AST = (AST)returnAST; break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp256_AST = null; tmp256_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp256_AST); match(IDENT); } else if (((_tokenSet_47.member(LA(1))) && (_tokenSet_46.member(LA(2))))&&(false)) { } else { break _loop304; } } while (true); } { if ((LA(1)==LPAREN)) { { lp = LT(1); lp_AST = astFactory.create(lp); astFactory.makeASTRoot(currentAST, lp_AST); match(LPAREN); if ( inputState.guessing==0 ) { lp_AST.setType(METHOD_CALL); } if ( inputState.guessing==0 ) { if (ta2_AST != null) astFactory.addASTChild(currentAST, ta2_AST); } if ( inputState.guessing==0 ) { if (ta2_AST == null) astFactory.addASTChild(currentAST, ta1_AST); } argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); } } else if ((LA(1)==LBRACK) && (LA(2)==RBRACK)) { { int _cnt308=0; _loop308: do { if ((LA(1)==LBRACK) && (LA(2)==RBRACK)) { lbc = LT(1); lbc_AST = astFactory.create(lbc); astFactory.makeASTRoot(currentAST, lbc_AST); match(LBRACK); if ( inputState.guessing==0 ) { lbc_AST.setType(ARRAY_DECLARATOR); } match(RBRACK); } else { if ( _cnt308>=1 ) { break _loop308; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt308++; } while (true); } } else if ((_tokenSet_45.member(LA(1))) && (_tokenSet_46.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } identPrimary_AST = (AST)currentAST.root; returnAST = identPrimary_AST; } public final void constant() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constant_AST = null; switch ( LA(1)) { case NUM_INT: { AST tmp259_AST = null; tmp259_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp259_AST); match(NUM_INT); constant_AST = (AST)currentAST.root; break; } case CHAR_LITERAL: { AST tmp260_AST = null; tmp260_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp260_AST); match(CHAR_LITERAL); constant_AST = (AST)currentAST.root; break; } case STRING_LITERAL: { AST tmp261_AST = null; tmp261_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp261_AST); match(STRING_LITERAL); constant_AST = (AST)currentAST.root; break; } case NUM_FLOAT: { AST tmp262_AST = null; tmp262_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp262_AST); match(NUM_FLOAT); constant_AST = (AST)currentAST.root; break; } case NUM_LONG: { AST tmp263_AST = null; tmp263_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp263_AST); match(NUM_LONG); constant_AST = (AST)currentAST.root; break; } case NUM_DOUBLE: { AST tmp264_AST = null; tmp264_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp264_AST); match(NUM_DOUBLE); constant_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = constant_AST; } public final void newArrayDeclarator() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST newArrayDeclarator_AST = null; Token lb = null; AST lb_AST = null; { int _cnt319=0; _loop319: do { if ((LA(1)==LBRACK) && (_tokenSet_48.member(LA(2)))) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } { switch ( LA(1)) { case IDENT: case LITERAL_super: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LPAREN: case LITERAL_this: case PLUS: case MINUS: case INC: case DEC: case BNOT: case LNOT: case LITERAL_true: case LITERAL_false: case LITERAL_null: case LITERAL_new: case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: { expression(); astFactory.addASTChild(currentAST, returnAST); break; } case RBRACK: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RBRACK); } else { if ( _cnt319>=1 ) { break _loop319; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt319++; } while (true); } newArrayDeclarator_AST = (AST)currentAST.root; returnAST = newArrayDeclarator_AST; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "BLOCK", "MODIFIERS", "OBJBLOCK", "SLIST", "METHOD_DEF", "VARIABLE_DEF", "INSTANCE_INIT", "STATIC_INIT", "TYPE", "CLASS_DEF", "INTERFACE_DEF", "PACKAGE_DEF", "ARRAY_DECLARATOR", "EXTENDS_CLAUSE", "IMPLEMENTS_CLAUSE", "PARAMETERS", "PARAMETER_DEF", "LABELED_STAT", "TYPECAST", "INDEX_OP", "POST_INC", "POST_DEC", "METHOD_CALL", "EXPR", "ARRAY_INIT", "IMPORT", "UNARY_MINUS", "UNARY_PLUS", "CASE_GROUP", "ELIST", "FOR_INIT", "FOR_CONDITION", "FOR_ITERATOR", "EMPTY_STAT", "\"final\"", "\"abstract\"", "\"strictfp\"", "SUPER_CTOR_CALL", "CTOR_CALL", "VARIABLE_PARAMETER_DEF", "STATIC_IMPORT", "ENUM_DEF", "ENUM_CONSTANT_DEF", "FOR_EACH_CLAUSE", "ANNOTATION_DEF", "ANNOTATIONS", "ANNOTATION", "ANNOTATION_MEMBER_VALUE_PAIR", "ANNOTATION_FIELD_DEF", "ANNOTATION_ARRAY_INIT", "TYPE_ARGUMENTS", "TYPE_ARGUMENT", "TYPE_PARAMETERS", "TYPE_PARAMETER", "WILDCARD_TYPE", "TYPE_UPPER_BOUNDS", "TYPE_LOWER_BOUNDS", "\"package\"", "SEMI", "\"import\"", "\"static\"", "LBRACK", "RBRACK", "IDENT", "DOT", "QUESTION", "\"extends\"", "\"super\"", "LT", "COMMA", "GT", "SR", "BSR", "\"void\"", "\"boolean\"", "\"byte\"", "\"char\"", "\"short\"", "\"int\"", "\"float\"", "\"long\"", "\"double\"", "STAR", "\"private\"", "\"public\"", "\"protected\"", "\"transient\"", "\"native\"", "\"threadsafe\"", "\"synchronized\"", "\"volatile\"", "AT", "LPAREN", "RPAREN", "ASSIGN", "LCURLY", "RCURLY", "\"class\"", "\"interface\"", "\"enum\"", "BAND", "\"default\"", "\"implements\"", "\"this\"", "\"throws\"", "TRIPLE_DOT", "COLON", "\"if\"", "\"else\"", "\"while\"", "\"do\"", "\"break\"", "\"continue\"", "\"return\"", "\"switch\"", "\"throw\"", "\"assert\"", "\"for\"", "\"case\"", "\"try\"", "\"finally\"", "\"catch\"", "PLUS_ASSIGN", "MINUS_ASSIGN", "STAR_ASSIGN", "DIV_ASSIGN", "MOD_ASSIGN", "SR_ASSIGN", "BSR_ASSIGN", "SL_ASSIGN", "BAND_ASSIGN", "BXOR_ASSIGN", "BOR_ASSIGN", "LOR", "LAND", "BOR", "BXOR", "NOT_EQUAL", "EQUAL", "LE", "GE", "\"instanceof\"", "SL", "PLUS", "MINUS", "DIV", "MOD", "INC", "DEC", "BNOT", "LNOT", "\"true\"", "\"false\"", "\"null\"", "\"new\"", "NUM_INT", "CHAR_LITERAL", "STRING_LITERAL", "NUM_FLOAT", "NUM_LONG", "NUM_DOUBLE", "WS", "SL_COMMENT", "ML_COMMENT", "ESC", "HEX_DIGIT", "VOCAB", "EXPONENT", "FLOAT_SUFFIX" }; protected void buildTokenTypeASTClassMap() { tokenTypeToASTClassMap=null; }; private static final long[] mk_tokenSet_0() { long[] data = { -4611684094282039294L, 966359252993L, 0L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = { 4611687942572736514L, 966359253001L, 0L, 0L}; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = { 4611687942572736512L, 966359252993L, 0L, 0L}; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = { 4611687942572736514L, 966359252993L, 0L, 0L}; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = { 1924145348608L, 2139095041L, 0L, 0L}; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = { 0L, 4186152L, 0L, 0L}; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = { 4611686018427387904L, -4611566038511780098L, 32767L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = { 6917530951786430464L, -3458782106006585345L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = { 0L, 8836899398024L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = { 0L, 9979364900282L, 137438952960L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = { 0L, 8802539659656L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = { 0L, 4432410443336L, 0L, 0L}; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = { 4611687942572736512L, 5471784132955L, 0L, 0L}; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); private static final long[] mk_tokenSet_13() { long[] data = { 1924145348608L, 966363439369L, 0L, 0L}; return data; } public static final BitSet _tokenSet_13 = new BitSet(mk_tokenSet_13()); private static final long[] mk_tokenSet_14() { long[] data = { 1924145348608L, 970658406683L, 0L, 0L}; return data; } public static final BitSet _tokenSet_14 = new BitSet(mk_tokenSet_14()); private static final long[] mk_tokenSet_15() { long[] data = { 0L, 4186120L, 0L, 0L}; return data; } public static final BitSet _tokenSet_15 = new BitSet(mk_tokenSet_15()); private static final long[] mk_tokenSet_16() { long[] data = { 0L, 282L, 0L, 0L}; return data; } public static final BitSet _tokenSet_16 = new BitSet(mk_tokenSet_16()); private static final long[] mk_tokenSet_17() { long[] data = { 4611686018427387904L, 17179869698L, 0L, 0L}; return data; } public static final BitSet _tokenSet_17 = new BitSet(mk_tokenSet_17()); private static final long[] mk_tokenSet_18() { long[] data = { 274877906944L, 2151669768L, 0L, 0L}; return data; } public static final BitSet _tokenSet_18 = new BitSet(mk_tokenSet_18()); private static final long[] mk_tokenSet_19() { long[] data = { 0L, 2151670042L, 0L, 0L}; return data; } public static final BitSet _tokenSet_19 = new BitSet(mk_tokenSet_19()); private static final long[] mk_tokenSet_20() { long[] data = { 0L, 35186523758874L, 0L, 0L}; return data; } public static final BitSet _tokenSet_20 = new BitSet(mk_tokenSet_20()); private static final long[] mk_tokenSet_21() { long[] data = { 4611687942572736512L, 864277892467515785L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_21 = new BitSet(mk_tokenSet_21()); private static final long[] mk_tokenSet_22() { long[] data = { 0L, 8796093022592L, 0L, 0L}; return data; } public static final BitSet _tokenSet_22 = new BitSet(mk_tokenSet_22()); private static final long[] mk_tokenSet_23() { long[] data = { 0L, 4299153448L, 0L, 0L}; return data; } public static final BitSet _tokenSet_23 = new BitSet(mk_tokenSet_23()); private static final long[] mk_tokenSet_24() { long[] data = { 4611687942572736512L, 864277961186992521L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_24 = new BitSet(mk_tokenSet_24()); private static final long[] mk_tokenSet_25() { long[] data = { 4611687942572736512L, -3747335747166798405L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_25 = new BitSet(mk_tokenSet_25()); private static final long[] mk_tokenSet_26() { long[] data = { 4611687942572736512L, 1152792011338670473L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_26 = new BitSet(mk_tokenSet_26()); private static final long[] mk_tokenSet_27() { long[] data = { 4611687942572736512L, -57183194579525L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_27 = new BitSet(mk_tokenSet_27()); private static final long[] mk_tokenSet_28() { long[] data = { 1924145348608L, 4290764809L, 0L, 0L}; return data; } public static final BitSet _tokenSet_28 = new BitSet(mk_tokenSet_28()); private static final long[] mk_tokenSet_29() { long[] data = { 1924145348608L, 4290765083L, 0L, 0L}; return data; } public static final BitSet _tokenSet_29 = new BitSet(mk_tokenSet_29()); private static final long[] mk_tokenSet_30() { long[] data = { 0L, 8800392176008L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_30 = new BitSet(mk_tokenSet_30()); private static final long[] mk_tokenSet_31() { long[] data = { 4611686018427387904L, -4611676101339513414L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_31 = new BitSet(mk_tokenSet_31()); private static final long[] mk_tokenSet_32() { long[] data = { 1924145348608L, 141725532161L, 0L, 0L}; return data; } public static final BitSet _tokenSet_32 = new BitSet(mk_tokenSet_32()); private static final long[] mk_tokenSet_33() { long[] data = { 1924145348608L, 141725532169L, 0L, 0L}; return data; } public static final BitSet _tokenSet_33 = new BitSet(mk_tokenSet_33()); private static final long[] mk_tokenSet_34() { long[] data = { 0L, 8834751914376L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_34 = new BitSet(mk_tokenSet_34()); private static final long[] mk_tokenSet_35() { long[] data = { 4611687942572736512L, 8804678754697L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_35 = new BitSet(mk_tokenSet_35()); private static final long[] mk_tokenSet_36() { long[] data = { 4611687942572736512L, -4611676097052934213L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_36 = new BitSet(mk_tokenSet_36()); private static final long[] mk_tokenSet_37() { long[] data = { 0L, 79169136353672L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_37 = new BitSet(mk_tokenSet_37()); private static final long[] mk_tokenSet_38() { long[] data = { 4611686018427387904L, -4611676101339512902L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_38 = new BitSet(mk_tokenSet_38()); private static final long[] mk_tokenSet_39() { long[] data = { 0L, 1280L, 98304L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_39 = new BitSet(mk_tokenSet_39()); private static final long[] mk_tokenSet_40() { long[] data = { 0L, 6144L, 262144L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_40 = new BitSet(mk_tokenSet_40()); private static final long[] mk_tokenSet_41() { long[] data = { 0L, 4194304L, 6291456L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_41 = new BitSet(mk_tokenSet_41()); private static final long[] mk_tokenSet_42() { long[] data = { 0L, 8800392176008L, 137304735744L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_42 = new BitSet(mk_tokenSet_42()); private static final long[] mk_tokenSet_43() { long[] data = { 4611686018427387904L, -4611605655285923906L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_43 = new BitSet(mk_tokenSet_43()); private static final long[] mk_tokenSet_44() { long[] data = { 0L, 392L, 0L, 0L}; return data; } public static final BitSet _tokenSet_44 = new BitSet(mk_tokenSet_44()); private static final long[] mk_tokenSet_45() { long[] data = { 4611686018427387904L, -4611614455678099658L, 33554431L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_45 = new BitSet(mk_tokenSet_45()); private static final long[] mk_tokenSet_46() { long[] data = { 6917530951786430464L, -3458821688425185345L, 137438953471L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_46 = new BitSet(mk_tokenSet_46()); private static final long[] mk_tokenSet_47() { long[] data = { 4611686018427387904L, -4611614451383132362L, 33554431L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_47 = new BitSet(mk_tokenSet_47()); private static final long[] mk_tokenSet_48() { long[] data = { 0L, 8800392176012L, 137432137728L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_48 = new BitSet(mk_tokenSet_48()); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaLexer.java0000644001501200150120000016354411715044504024616 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "java.g" -> "JavaLexer.java"$ package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.*; import org.codehaus.groovy.antlr.parser.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; public class JavaLexer extends antlr.CharScanner implements JavaTokenTypes, TokenStream { protected static final int SCS_TYPE = 3, SCS_VAL = 4, SCS_LIT = 8, SCS_LIMIT = 16; protected static final int SCS_SQ_TYPE = 0, SCS_TQ_TYPE = 1, SCS_RE_TYPE = 2; protected int stringCtorState = 0; // hack string and regexp constructor boundaries protected int lastSigTokenType = EOF; // last returned non-whitespace token /** flag for enabling the "assert" keyword */ private boolean assertEnabled = true; /** flag for enabling the "enum" keyword */ private boolean enumEnabled = true; /** flag for including whitespace tokens (for IDE preparsing) */ private boolean whitespaceIncluded = false; /** Enable the "assert" keyword */ public void enableAssert(boolean shouldEnable) { assertEnabled = shouldEnable; } /** Query the "assert" keyword state */ public boolean isAssertEnabled() { return assertEnabled; } /** Enable the "enum" keyword */ public void enableEnum(boolean shouldEnable) { enumEnabled = shouldEnable; } /** Query the "enum" keyword state */ public boolean isEnumEnabled() { return enumEnabled; } /** This is a bit of plumbing which resumes collection of string constructor bodies, * after an embedded expression has been parsed. * Usage: new JavaRecognizer(new JavaLexer(in).plumb()). */ public TokenStream plumb() { return new TokenStream() { public Token nextToken() throws TokenStreamException { if (stringCtorState >= SCS_LIT) { // This goo is modeled upon the ANTLR code for nextToken: int quoteType = (stringCtorState & SCS_TYPE); stringCtorState = 0; // get out of this mode, now resetText(); /* try { switch (quoteType) { case SCS_SQ_TYPE: //todo: suitable replacement??? mSTRING_CTOR_END(true, false, false); break; case SCS_TQ_TYPE: // mSTRING_CTOR_END(true, false, true); break; case SCS_RE_TYPE: // mREGEXP_CTOR_END(true, false); break; default: throw new AssertionError(false); } lastSigTokenType = _returnToken.getType(); return _returnToken; }*//* catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); }*/ /*catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } }*/ } Token token = JavaLexer.this.nextToken(); int lasttype = token.getType(); if (whitespaceIncluded) { switch (lasttype) { // filter out insignificant types case WS: case SL_COMMENT: case ML_COMMENT: lasttype = lastSigTokenType; // back up! } } lastSigTokenType = lasttype; return token; } }; } protected JavaRecognizer parser; // little-used link; TODO: get rid of public JavaLexer(InputStream in) { this(new ByteBuffer(in)); } public JavaLexer(Reader in) { this(new CharBuffer(in)); } public JavaLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public JavaLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); literals.put(new ANTLRHashString("byte", this), new Integer(79)); literals.put(new ANTLRHashString("public", this), new Integer(88)); literals.put(new ANTLRHashString("case", this), new Integer(122)); literals.put(new ANTLRHashString("short", this), new Integer(81)); literals.put(new ANTLRHashString("break", this), new Integer(115)); literals.put(new ANTLRHashString("while", this), new Integer(113)); literals.put(new ANTLRHashString("new", this), new Integer(158)); literals.put(new ANTLRHashString("instanceof", this), new Integer(145)); literals.put(new ANTLRHashString("implements", this), new Integer(106)); literals.put(new ANTLRHashString("synchronized", this), new Integer(93)); literals.put(new ANTLRHashString("float", this), new Integer(83)); literals.put(new ANTLRHashString("package", this), new Integer(61)); literals.put(new ANTLRHashString("return", this), new Integer(117)); literals.put(new ANTLRHashString("throw", this), new Integer(119)); literals.put(new ANTLRHashString("null", this), new Integer(157)); literals.put(new ANTLRHashString("threadsafe", this), new Integer(92)); literals.put(new ANTLRHashString("protected", this), new Integer(89)); literals.put(new ANTLRHashString("class", this), new Integer(101)); literals.put(new ANTLRHashString("throws", this), new Integer(108)); literals.put(new ANTLRHashString("do", this), new Integer(114)); literals.put(new ANTLRHashString("strictfp", this), new Integer(40)); literals.put(new ANTLRHashString("super", this), new Integer(71)); literals.put(new ANTLRHashString("transient", this), new Integer(90)); literals.put(new ANTLRHashString("native", this), new Integer(91)); literals.put(new ANTLRHashString("interface", this), new Integer(102)); literals.put(new ANTLRHashString("final", this), new Integer(38)); literals.put(new ANTLRHashString("if", this), new Integer(111)); literals.put(new ANTLRHashString("double", this), new Integer(85)); literals.put(new ANTLRHashString("volatile", this), new Integer(94)); literals.put(new ANTLRHashString("assert", this), new Integer(120)); literals.put(new ANTLRHashString("catch", this), new Integer(125)); literals.put(new ANTLRHashString("try", this), new Integer(123)); literals.put(new ANTLRHashString("enum", this), new Integer(103)); literals.put(new ANTLRHashString("int", this), new Integer(82)); literals.put(new ANTLRHashString("for", this), new Integer(121)); literals.put(new ANTLRHashString("extends", this), new Integer(70)); literals.put(new ANTLRHashString("boolean", this), new Integer(78)); literals.put(new ANTLRHashString("char", this), new Integer(80)); literals.put(new ANTLRHashString("private", this), new Integer(87)); literals.put(new ANTLRHashString("default", this), new Integer(105)); literals.put(new ANTLRHashString("false", this), new Integer(156)); literals.put(new ANTLRHashString("this", this), new Integer(107)); literals.put(new ANTLRHashString("static", this), new Integer(64)); literals.put(new ANTLRHashString("abstract", this), new Integer(39)); literals.put(new ANTLRHashString("continue", this), new Integer(116)); literals.put(new ANTLRHashString("finally", this), new Integer(124)); literals.put(new ANTLRHashString("else", this), new Integer(112)); literals.put(new ANTLRHashString("import", this), new Integer(63)); literals.put(new ANTLRHashString("void", this), new Integer(77)); literals.put(new ANTLRHashString("switch", this), new Integer(118)); literals.put(new ANTLRHashString("true", this), new Integer(155)); literals.put(new ANTLRHashString("long", this), new Integer(84)); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case '?': { mQUESTION(true); theRetToken=_returnToken; break; } case '(': { mLPAREN(true); theRetToken=_returnToken; break; } case ')': { mRPAREN(true); theRetToken=_returnToken; break; } case '[': { mLBRACK(true); theRetToken=_returnToken; break; } case ']': { mRBRACK(true); theRetToken=_returnToken; break; } case '{': { mLCURLY(true); theRetToken=_returnToken; break; } case '}': { mRCURLY(true); theRetToken=_returnToken; break; } case ':': { mCOLON(true); theRetToken=_returnToken; break; } case ',': { mCOMMA(true); theRetToken=_returnToken; break; } case '~': { mBNOT(true); theRetToken=_returnToken; break; } case ';': { mSEMI(true); theRetToken=_returnToken; break; } case '\t': case '\n': case '\u000c': case '\r': case ' ': { mWS(true); theRetToken=_returnToken; break; } case '\'': { mCHAR_LITERAL(true); theRetToken=_returnToken; break; } case '"': { mSTRING_LITERAL(true); theRetToken=_returnToken; break; } case '$': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mIDENT(true); theRetToken=_returnToken; break; } case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mNUM_INT(true); theRetToken=_returnToken; break; } case '@': { mAT(true); theRetToken=_returnToken; break; } default: if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='>') && (LA(4)=='=')) { mBSR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='=')) { mSR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='>') && (true)) { mBSR(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='<') && (LA(3)=='=')) { mSL_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (LA(2)=='=')) { mEQUAL(true); theRetToken=_returnToken; } else if ((LA(1)=='!') && (LA(2)=='=')) { mNOT_EQUAL(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='=')) { mDIV_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (LA(2)=='=')) { mPLUS_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (LA(2)=='+')) { mINC(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (LA(2)=='=')) { mMINUS_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (LA(2)=='-')) { mDEC(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (LA(2)=='=')) { mSTAR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='%') && (LA(2)=='=')) { mMOD_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (true)) { mSR(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='=')) { mGE(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='<') && (true)) { mSL(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='=')) { mLE(true); theRetToken=_returnToken; } else if ((LA(1)=='^') && (LA(2)=='=')) { mBXOR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (LA(2)=='=')) { mBOR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (LA(2)=='|')) { mLOR(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (LA(2)=='=')) { mBAND_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (LA(2)=='&')) { mLAND(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='/')) { mSL_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='*')) { mML_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (true)) { mASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='!') && (true)) { mLNOT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (true)) { mDIV(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (true)) { mPLUS(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (true)) { mMINUS(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (true)) { mSTAR(true); theRetToken=_returnToken; } else if ((LA(1)=='%') && (true)) { mMOD(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (true)) { mGT(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (true)) { mLT(true); theRetToken=_returnToken; } else if ((LA(1)=='^') && (true)) { mBXOR(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (true)) { mBOR(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (true)) { mBAND(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mQUESTION(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = QUESTION; int _saveIndex; match('?'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LPAREN; int _saveIndex; match('('); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RPAREN; int _saveIndex; match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LBRACK; int _saveIndex; match('['); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RBRACK; int _saveIndex; match(']'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLCURLY(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LCURLY; int _saveIndex; match('{'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRCURLY(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RCURLY; int _saveIndex; match('}'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOLON(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COLON; int _saveIndex; match(':'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMMA(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMA; int _saveIndex; match(','); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ASSIGN; int _saveIndex; match('='); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mEQUAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EQUAL; int _saveIndex; match("=="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLNOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LNOT; int _saveIndex; match('!'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBNOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BNOT; int _saveIndex; match('~'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNOT_EQUAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NOT_EQUAL; int _saveIndex; match("!="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDIV(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DIV; int _saveIndex; match('/'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDIV_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DIV_ASSIGN; int _saveIndex; match("/="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS; int _saveIndex; match('+'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS_ASSIGN; int _saveIndex; match("+="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mINC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = INC; int _saveIndex; match("++"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMINUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MINUS; int _saveIndex; match('-'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMINUS_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MINUS_ASSIGN; int _saveIndex; match("-="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDEC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DEC; int _saveIndex; match("--"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR; int _saveIndex; match('*'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR_ASSIGN; int _saveIndex; match("*="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMOD(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MOD; int _saveIndex; match('%'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMOD_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MOD_ASSIGN; int _saveIndex; match("%="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SR; int _saveIndex; match(">>"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SR_ASSIGN; int _saveIndex; match(">>="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBSR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BSR; int _saveIndex; match(">>>"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBSR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BSR_ASSIGN; int _saveIndex; match(">>>="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mGE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = GE; int _saveIndex; match(">="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mGT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = GT; int _saveIndex; match(">"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL; int _saveIndex; match("<<"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_ASSIGN; int _saveIndex; match("<<="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LE; int _saveIndex; match("<="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LT; int _saveIndex; match('<'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBXOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BXOR; int _saveIndex; match('^'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBXOR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BXOR_ASSIGN; int _saveIndex; match("^="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BOR; int _saveIndex; match('|'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBOR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BOR_ASSIGN; int _saveIndex; match("|="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LOR; int _saveIndex; match("||"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBAND(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BAND; int _saveIndex; match('&'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBAND_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BAND_ASSIGN; int _saveIndex; match("&="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLAND(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LAND; int _saveIndex; match("&&"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSEMI(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SEMI; int _saveIndex; match(';'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mWS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS; int _saveIndex; { int _cnt369=0; _loop369: do { switch ( LA(1)) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\u000c': { match('\f'); break; } case '\n': case '\r': { { if ((LA(1)=='\r') && (LA(2)=='\n') && (true) && (true)) { match("\r\n"); } else if ((LA(1)=='\r') && (true) && (true) && (true)) { match('\r'); } else if ((LA(1)=='\n')) { match('\n'); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { newline(); } break; } default: { if ( _cnt369>=1 ) { break _loop369; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt369++; } while (true); } if ( inputState.guessing==0 ) { _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_COMMENT; int _saveIndex; match("//"); { _loop373: do { if ((_tokenSet_0.member(LA(1)))) { { match(_tokenSet_0); } } else { break _loop373; } } while (true); } { switch ( LA(1)) { case '\n': { match('\n'); break; } case '\r': { match('\r'); { if ((LA(1)=='\n')) { match('\n'); } else { } } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = Token.SKIP; newline(); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mML_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ML_COMMENT; int _saveIndex; match("/*"); { _loop379: do { if ((LA(1)=='\r') && (LA(2)=='\n') && ((LA(3) >= '\u0003' && LA(3) <= '\uffff')) && ((LA(4) >= '\u0003' && LA(4) <= '\uffff'))) { match('\r'); match('\n'); if ( inputState.guessing==0 ) { newline(); } } else if (((LA(1)=='*') && ((LA(2) >= '\u0003' && LA(2) <= '\uffff')) && ((LA(3) >= '\u0003' && LA(3) <= '\uffff')))&&( LA(2)!='/' )) { match('*'); } else if ((LA(1)=='\r') && ((LA(2) >= '\u0003' && LA(2) <= '\uffff')) && ((LA(3) >= '\u0003' && LA(3) <= '\uffff')) && (true)) { match('\r'); if ( inputState.guessing==0 ) { newline(); } } else if ((LA(1)=='\n')) { match('\n'); if ( inputState.guessing==0 ) { newline(); } } else if ((_tokenSet_1.member(LA(1)))) { { match(_tokenSet_1); } } else { break _loop379; } } while (true); } match("*/"); if ( inputState.guessing==0 ) { _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCHAR_LITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = CHAR_LITERAL; int _saveIndex; match('\''); { if ((LA(1)=='\\')) { mESC(false); } else if ((_tokenSet_2.member(LA(1)))) { { match(_tokenSet_2); } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } match('\''); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mESC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC; int _saveIndex; match('\\'); { switch ( LA(1)) { case 'n': { match('n'); break; } case 'r': { match('r'); break; } case 't': { match('t'); break; } case 'b': { match('b'); break; } case 'f': { match('f'); break; } case '"': { match('"'); break; } case '\'': { match('\''); break; } case '\\': { match('\\'); break; } case 'u': { { int _cnt390=0; _loop390: do { if ((LA(1)=='u')) { match('u'); } else { if ( _cnt390>=1 ) { break _loop390; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt390++; } while (true); } mHEX_DIGIT(false); mHEX_DIGIT(false); mHEX_DIGIT(false); mHEX_DIGIT(false); break; } case '0': case '1': case '2': case '3': { matchRange('0','3'); { if (((LA(1) >= '0' && LA(1) <= '7')) && (_tokenSet_0.member(LA(2))) && (true) && (true)) { matchRange('0','7'); { if (((LA(1) >= '0' && LA(1) <= '7')) && (_tokenSet_0.member(LA(2))) && (true) && (true)) { matchRange('0','7'); } else if ((_tokenSet_0.member(LA(1))) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } else if ((_tokenSet_0.member(LA(1))) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } break; } case '4': case '5': case '6': case '7': { matchRange('4','7'); { if (((LA(1) >= '0' && LA(1) <= '7')) && (_tokenSet_0.member(LA(2))) && (true) && (true)) { matchRange('0','7'); } else if ((_tokenSet_0.member(LA(1))) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTRING_LITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING_LITERAL; int _saveIndex; match('"'); { _loop386: do { if ((LA(1)=='\\')) { mESC(false); } else if ((_tokenSet_3.member(LA(1)))) { { match(_tokenSet_3); } } else { break _loop386; } } while (true); } match('"'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mHEX_DIGIT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = HEX_DIGIT; int _saveIndex; { switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': { matchRange('A','F'); break; } case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': { matchRange('a','f'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mVOCAB(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = VOCAB; int _saveIndex; matchRange('\3','\377'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mIDENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = IDENT; int _saveIndex; { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } case '$': { match('$'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { _loop400: do { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case '$': { match('$'); break; } default: { break _loop400; } } } while (true); } if ( inputState.guessing==0 ) { // check if "assert" keyword is enabled if (assertEnabled && "assert".equals(new String(text.getBuffer(),_begin,text.length()-_begin))) { _ttype = LITERAL_assert; // set token type for the rule in the parser } // check if "enum" keyword is enabled if (enumEnabled && "enum".equals(new String(text.getBuffer(),_begin,text.length()-_begin))) { _ttype = LITERAL_enum; // set token type for the rule in the parser } } _ttype = testLiteralsTable(_ttype); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNUM_INT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NUM_INT; int _saveIndex; Token f1=null; Token f2=null; Token f3=null; Token f4=null; boolean isDecimal=false; Token t=null; switch ( LA(1)) { case '.': { match('.'); if ( inputState.guessing==0 ) { _ttype = DOT; } { switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { { int _cnt405=0; _loop405: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt405>=1 ) { break _loop405; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt405++; } while (true); } { if ((LA(1)=='E'||LA(1)=='e')) { mEXPONENT(false); } else { } } { if ((LA(1)=='D'||LA(1)=='F'||LA(1)=='d'||LA(1)=='f')) { mFLOAT_SUFFIX(true); f1=_returnToken; if ( inputState.guessing==0 ) { t=f1; } } else { } } if ( inputState.guessing==0 ) { if (t != null && t.getText().toUpperCase().indexOf('F')>=0) { _ttype = NUM_FLOAT; } else { _ttype = NUM_DOUBLE; // assume double } } } break; } case '.': { { match(".."); if ( inputState.guessing==0 ) { _ttype = TRIPLE_DOT; } } break; } default: { } } } break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { switch ( LA(1)) { case '0': { match('0'); if ( inputState.guessing==0 ) { isDecimal = true; } { if ((LA(1)=='X'||LA(1)=='x')) { { switch ( LA(1)) { case 'x': { match('x'); break; } case 'X': { match('X'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { int _cnt413=0; _loop413: do { if ((_tokenSet_4.member(LA(1))) && (true) && (true) && (true)) { mHEX_DIGIT(false); } else { if ( _cnt413>=1 ) { break _loop413; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt413++; } while (true); } } else { boolean synPredMatched418 = false; if ((((LA(1) >= '0' && LA(1) <= '9')) && (true) && (true) && (true))) { int _m418 = mark(); synPredMatched418 = true; inputState.guessing++; try { { { int _cnt416=0; _loop416: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt416>=1 ) { break _loop416; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt416++; } while (true); } { switch ( LA(1)) { case '.': { match('.'); break; } case 'E': case 'e': { mEXPONENT(false); break; } case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(false); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } } catch (RecognitionException pe) { synPredMatched418 = false; } rewind(_m418); inputState.guessing--; } if ( synPredMatched418 ) { { int _cnt420=0; _loop420: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt420>=1 ) { break _loop420; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt420++; } while (true); } } else if (((LA(1) >= '0' && LA(1) <= '7')) && (true) && (true) && (true)) { { int _cnt422=0; _loop422: do { if (((LA(1) >= '0' && LA(1) <= '7'))) { matchRange('0','7'); } else { if ( _cnt422>=1 ) { break _loop422; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt422++; } while (true); } } else { } } } break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { matchRange('1','9'); } { _loop425: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { break _loop425; } } while (true); } if ( inputState.guessing==0 ) { isDecimal=true; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { if ((LA(1)=='L'||LA(1)=='l')) { { switch ( LA(1)) { case 'l': { match('l'); break; } case 'L': { match('L'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = NUM_LONG; } } else if (((LA(1)=='.'||LA(1)=='D'||LA(1)=='E'||LA(1)=='F'||LA(1)=='d'||LA(1)=='e'||LA(1)=='f'))&&(isDecimal)) { { switch ( LA(1)) { case '.': { match('.'); { _loop430: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { break _loop430; } } while (true); } { if ((LA(1)=='E'||LA(1)=='e')) { mEXPONENT(false); } else { } } { if ((LA(1)=='D'||LA(1)=='F'||LA(1)=='d'||LA(1)=='f')) { mFLOAT_SUFFIX(true); f2=_returnToken; if ( inputState.guessing==0 ) { t=f2; } } else { } } break; } case 'E': case 'e': { mEXPONENT(false); { if ((LA(1)=='D'||LA(1)=='F'||LA(1)=='d'||LA(1)=='f')) { mFLOAT_SUFFIX(true); f3=_returnToken; if ( inputState.guessing==0 ) { t=f3; } } else { } } break; } case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(true); f4=_returnToken; if ( inputState.guessing==0 ) { t=f4; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { if (t != null && t.getText().toUpperCase() .indexOf('F') >= 0) { _ttype = NUM_FLOAT; } else { _ttype = NUM_DOUBLE; // assume double } } } else { } } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mEXPONENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EXPONENT; int _saveIndex; { switch ( LA(1)) { case 'e': { match('e'); break; } case 'E': { match('E'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { switch ( LA(1)) { case '+': { match('+'); break; } case '-': { match('-'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { int _cnt439=0; _loop439: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt439>=1 ) { break _loop439; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt439++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mFLOAT_SUFFIX(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = FLOAT_SUFFIX; int _saveIndex; switch ( LA(1)) { case 'f': { match('f'); break; } case 'F': { match('F'); break; } case 'd': { match('d'); break; } case 'D': { match('D'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mAT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = AT; int _saveIndex; match('@'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-9224L; for (int i = 1; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[2048]; data[0]=-4398046520328L; for (int i = 1; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[2048]; data[0]=-549755823112L; data[1]=-268435457L; for (int i = 2; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[2048]; data[0]=-17179878408L; data[1]=-268435457L; for (int i = 2; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = new long[1025]; data[0]=287948901175001088L; data[1]=541165879422L; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaRecognizer.smap0000644001501200150120000014206311715044502025654 0ustar miguelmiguelSMAP JavaRecognizer.java G *S G *F + 0 java.g java.g *L 2:3 2:4 2:5 2:6 2:7 2:8 2:9 2:10 214:208 215:209 216:210 217:211 218:212 219:213 220:214 221:215 222:216 223:217 224:218 225:219 226:220 227:221 229:223 231:225 232:226 233:227 234:228 235:229 236:230 237:231 239:233 240:234 241:235 242:236 243:237 244:238 245:239 246:240 247:241 248:242 249:243 250:244 251:245 252:246 253:247 255:249 256:250 257:251 258:252 259:253 260:254 261:255 262:256 265:259 266:260 267:261 268:262 269:263 270:264 271:265 276:296 276:298 276:299 276:300 276:359 276:360 278:303 278:304 278:305 278:306 278:307 278:308 278:310 278:311 278:313 278:314 278:315 278:316 278:317 278:318 278:319 278:320 278:321 278:322 278:323 278:325 278:326 278:327 278:328 283:331 283:332 283:333 283:334 283:335 283:336 283:337 283:338 283:339 283:340 283:342 283:343 287:344 287:345 287:346 287:347 287:348 287:349 287:350 287:351 287:352 287:353 287:355 287:356 289:357 291:358 294:394 294:396 294:397 294:398 294:402 294:416 294:417 294:418 294:419 294:420 294:421 294:422 294:423 294:424 294:425 294:426 296:399 296:400 296:403 296:404 296:405 296:406 296:407 296:408 296:409 296:410 296:412 296:413 296:414 298:415 301:428 301:430 301:431 301:432 301:435 301:437 301:469 301:470 301:471 301:472 301:473 301:474 301:475 301:476 301:477 301:478 301:479 304:433 304:434 304:438 304:439 304:440 304:441 304:442 304:443 304:446 304:447 304:448 304:449 304:450 304:451 304:459 304:460 304:461 304:462 304:463 304:465 304:466 304:467 306:468 308:481 308:483 308:484 308:485 308:488 308:489 308:520 308:521 308:522 308:523 308:524 308:525 308:526 308:527 308:528 308:529 308:530 308:531 308:532 308:533 308:534 308:535 310:486 310:490 310:491 310:492 310:493 310:494 310:495 310:496 310:497 310:498 310:499 310:500 310:501 310:502 310:503 310:504 310:505 310:506 310:507 310:508 311:509 311:510 311:511 312:514 312:515 312:516 314:517 316:663 316:664 316:665 316:667 316:668 316:669 316:671 316:700 316:701 316:702 316:703 316:704 316:705 316:706 317:672 317:673 317:674 317:675 317:676 318:679 318:680 318:681 318:682 318:683 319:686 319:687 319:688 319:689 319:690 320:693 320:694 320:695 320:696 320:697 325:872 325:874 325:875 325:876 325:895 325:896 326:877 326:878 326:879 326:881 326:882 326:883 326:884 326:885 326:886 327:887 327:888 327:889 327:890 327:892 327:893 332:898 332:899 332:900 332:902 332:903 332:904 332:906 332:929 332:930 332:931 332:932 332:933 332:934 332:935 333:907 333:908 333:909 333:910 333:911 334:914 334:915 334:916 334:917 334:918 334:919 334:920 334:921 334:922 334:923 334:924 334:925 334:926 341:967 341:968 341:969 341:971 341:972 341:973 341:976 341:1012 341:1013 342:978 342:979 343:980 343:981 343:982 343:992 343:993 343:994 343:995 343:997 343:998 344:974 344:975 344:983 344:984 344:985 344:986 344:987 344:988 344:989 344:991 346:999 346:1000 346:1006 346:1008 346:1009 347:1002 347:1011 348:1003 349:1004 354:1063 354:1064 354:1065 354:1067 354:1068 354:1069 354:1070 354:1238 354:1239 355:1072 355:1073 355:1074 355:1075 355:1077 355:1078 355:1079 355:1080 355:1081 355:1135 355:1136 355:1137 355:1138 355:1139 356:1141 356:1142 356:1143 356:1218 356:1219 356:1220 356:1221 356:1223 356:1224 357:1144 357:1145 357:1146 357:1147 357:1148 358:1149 358:1150 358:1151 358:1152 358:1154 358:1155 358:1156 358:1157 358:1158 358:1212 358:1213 358:1214 358:1215 358:1216 360:1225 360:1226 360:1232 360:1234 360:1235 361:1228 361:1237 362:1229 363:1230 368:1297 368:1299 368:1300 368:1301 368:1303 368:1326 368:1327 368:1328 368:1329 368:1330 368:1331 368:1332 369:1304 369:1305 369:1306 369:1307 369:1308 370:1311 370:1312 370:1313 370:1314 370:1315 370:1316 370:1317 370:1318 370:1319 370:1320 370:1321 370:1322 370:1323 374:1384 374:1386 374:1387 374:1388 374:1389 374:1429 374:1430 375:1392 375:1393 375:1394 375:1395 375:1396 375:1397 375:1398 375:1399 375:1400 375:1401 375:1402 375:1403 375:1404 375:1405 375:1414 375:1415 375:1416 375:1417 375:1418 376:1408 376:1409 376:1410 376:1411 378:1420 378:1421 378:1422 378:1423 378:1425 378:1426 379:1428 382:1432 382:1434 382:1435 382:1436 382:1491 382:1492 383:1437 383:1438 383:1440 383:1441 383:1442 383:1443 383:1444 383:1445 384:1448 384:1449 384:1450 384:1451 384:1452 384:1453 384:1455 384:1456 384:1457 384:1458 384:1461 384:1462 384:1463 384:1466 384:1467 384:1468 384:1469 384:1470 384:1472 384:1473 384:1474 384:1475 384:1476 384:1477 384:1478 384:1479 384:1480 384:1481 384:1482 384:1484 384:1485 384:1486 384:1487 385:1490 388:1241 388:1243 388:1244 388:1245 388:1246 388:1294 388:1295 391:1248 391:1249 392:1251 392:1252 392:1253 393:1255 393:1256 394:1257 394:1258 394:1259 394:1264 394:1265 394:1266 394:1267 394:1269 394:1270 396:1260 396:1261 396:1262 396:1263 399:1275 399:1277 399:1278 399:1279 399:1280 402:1272 402:1273 402:1274 407:1283 407:1284 409:1285 409:1286 409:1287 409:1288 409:1290 409:1291 410:1293 414:1545 414:1547 414:1548 414:1549 414:1551 414:1579 414:1580 414:1581 414:1582 414:1583 414:1584 414:1585 415:1552 415:1553 415:1554 415:1555 415:1556 416:1561 416:1562 416:1563 416:1564 416:1565 417:1570 417:1571 417:1572 417:1573 417:1574 418:1558 419:1567 420:1576 421:1494 421:1496 421:1497 421:1498 421:1499 421:1542 421:1543 424:1502 424:1503 424:1504 424:1505 424:1506 424:1507 424:1511 424:1512 424:1513 424:1516 424:1517 424:1518 424:1519 424:1520 424:1522 424:1523 425:1524 425:1525 425:1536 425:1538 425:1539 426:1527 426:1541 427:1528 428:1529 429:1530 430:1531 431:1532 432:1533 433:1534 438:1334 438:1335 438:1336 438:1338 438:1339 438:1340 438:1343 438:1381 438:1382 439:1345 439:1346 440:1348 440:1349 440:1350 440:1360 440:1361 440:1362 440:1363 440:1365 440:1366 440:1367 441:1341 441:1342 441:1351 441:1352 441:1353 441:1354 441:1355 441:1356 441:1357 441:1359 444:1368 444:1369 444:1375 444:1377 444:1378 445:1371 445:1380 446:1372 447:1373 453:1015 453:1016 453:1017 453:1019 453:1020 453:1021 453:1024 453:1060 453:1061 454:1026 454:1027 455:1028 455:1029 455:1030 455:1040 455:1041 455:1042 455:1043 455:1045 455:1046 456:1022 456:1023 456:1031 456:1032 456:1033 456:1034 456:1035 456:1036 456:1037 456:1039 458:1047 458:1048 458:1054 458:1056 458:1057 459:1050 459:1059 460:1051 461:1052 467:1683 467:1685 467:1686 467:1687 467:1689 467:1712 467:1713 467:1714 467:1715 467:1716 467:1717 467:1718 468:1690 468:1691 468:1692 468:1693 468:1694 469:1697 469:1698 469:1699 469:1700 469:1701 469:1702 469:1703 469:1704 469:1705 469:1706 469:1707 469:1708 469:1709 473:1587 473:1589 473:1590 473:1591 473:1593 473:1675 473:1676 473:1677 473:1678 473:1679 473:1680 473:1681 474:1594 474:1595 474:1596 474:1597 474:1598 474:1599 474:1600 475:1603 475:1604 475:1605 475:1606 475:1607 475:1608 475:1609 476:1612 476:1613 476:1614 476:1615 476:1616 476:1617 476:1618 477:1621 477:1622 477:1623 477:1624 477:1625 477:1626 477:1627 478:1630 478:1631 478:1632 478:1633 478:1634 478:1635 478:1636 479:1639 479:1640 479:1641 479:1642 479:1643 479:1644 479:1645 480:1648 480:1649 480:1650 480:1651 480:1652 480:1653 480:1654 481:1657 481:1658 481:1659 481:1660 481:1661 481:1662 481:1663 482:1666 482:1667 482:1668 482:1669 482:1670 482:1671 482:1672 487:537 487:539 487:540 487:541 487:567 487:568 488:543 488:544 488:545 488:546 488:547 488:548 488:549 488:550 488:551 488:552 488:553 488:554 488:555 488:556 488:557 488:558 488:559 488:560 488:561 488:562 488:564 488:565 488:566 491:570 491:572 491:573 491:574 491:624 491:625 492:576 492:577 492:578 492:579 493:580 493:581 493:582 493:583 493:584 493:585 493:586 493:587 493:588 493:589 493:590 493:591 493:592 493:593 493:594 493:595 493:597 493:598 494:600 494:601 494:602 494:603 494:604 494:605 494:606 494:607 494:608 494:609 494:610 494:617 494:618 494:619 494:620 494:621 495:623 501:627 501:629 501:630 501:631 501:632 501:660 501:661 503:634 503:635 503:636 503:640 503:644 503:645 503:646 503:647 503:649 503:650 507:637 507:638 507:639 511:641 511:642 511:643 514:651 514:652 514:653 514:654 514:656 514:657 515:659 518:1720 518:1722 518:1723 518:1724 518:1726 518:1835 518:1836 518:1837 518:1838 518:1839 518:1840 518:1841 519:1727 519:1728 519:1729 519:1730 519:1731 519:1732 519:1733 520:1736 520:1737 520:1738 520:1739 520:1740 520:1741 520:1742 521:1745 521:1746 521:1747 521:1748 521:1749 521:1750 521:1751 522:1754 522:1755 522:1756 522:1757 522:1758 522:1759 522:1760 523:1763 523:1764 523:1765 523:1766 523:1767 523:1768 523:1769 524:1772 524:1773 524:1774 524:1775 524:1776 524:1777 524:1778 525:1781 525:1782 525:1783 525:1784 525:1785 525:1786 525:1787 526:1790 526:1791 526:1792 526:1793 526:1794 526:1795 526:1796 527:1799 527:1800 527:1801 527:1802 527:1803 527:1804 527:1805 528:1808 528:1809 528:1810 528:1811 528:1812 528:1813 528:1814 529:1817 529:1818 529:1819 529:1820 529:1821 529:1822 529:1823 530:1826 530:1827 530:1828 530:1829 530:1830 530:1831 530:1832 533:1843 533:1845 533:1846 533:1847 533:1850 533:1961 533:1962 534:1848 534:1849 534:1852 534:1853 534:1854 534:1856 534:1857 534:1858 534:1859 534:1861 534:1862 534:1863 534:1864 534:1865 534:1866 534:1867 534:1868 534:1869 534:1870 534:1871 534:1872 534:1873 534:1874 534:1875 534:1876 534:1877 534:1878 534:1879 534:1880 534:1881 534:1882 534:1883 534:1884 534:1885 534:1886 534:1887 534:1888 534:1889 534:1890 534:1891 534:1892 534:1893 534:1894 534:1895 534:1896 534:1903 534:1904 534:1905 534:1906 534:1907 534:1909 534:1947 534:1948 534:1949 534:1950 534:1951 535:1953 535:1954 535:1955 535:1956 535:1958 535:1959 538:362 538:364 538:365 538:366 538:367 538:391 538:392 539:369 539:370 539:371 539:372 539:373 539:374 539:375 539:376 539:377 539:378 539:380 539:381 540:382 540:383 540:384 540:385 540:387 540:388 541:390 543:1964 543:1966 543:1967 543:1968 543:1974 543:1979 543:1980 543:1981 543:1982 543:1984 543:1985 544:1970 544:1971 544:1972 544:1973 544:1975 544:1976 544:1977 544:1978 547:2052 547:2054 547:2055 547:2056 547:2075 547:2076 548:2058 548:2059 548:2060 548:2061 548:2062 548:2063 548:2064 548:2065 548:2066 548:2067 548:2068 548:2069 548:2070 548:2072 548:2073 548:2074 551:2078 551:2080 551:2081 551:2082 551:2086 551:2102 551:2103 552:2083 552:2084 552:2085 552:2088 552:2089 552:2090 552:2091 552:2092 552:2093 553:2094 553:2095 553:2096 553:2097 553:2099 553:2100 556:1987 556:1989 556:1990 556:1991 556:1993 556:2044 556:2045 556:2046 556:2047 556:2048 556:2049 556:2050 558:1994 558:1995 558:1996 558:1997 558:1998 558:1999 558:2000 558:2001 558:2002 558:2003 558:2004 558:2005 558:2006 558:2007 558:2008 558:2009 558:2010 558:2011 558:2012 558:2013 558:2014 558:2015 558:2016 558:2017 558:2018 558:2019 558:2020 558:2021 558:2022 558:2023 558:2024 558:2025 558:2026 558:2027 558:2030 558:2031 558:2032 558:2033 558:2034 558:2037 558:2038 558:2039 558:2040 558:2041 562:2159 562:2161 562:2162 562:2163 562:2255 562:2256 563:2164 563:2165 563:2167 563:2168 563:2169 563:2170 563:2171 563:2172 564:2175 564:2176 564:2177 564:2178 564:2179 564:2180 564:2181 564:2182 564:2183 564:2184 564:2185 564:2186 564:2187 564:2188 564:2189 564:2190 564:2191 564:2192 564:2193 564:2194 564:2195 564:2196 564:2197 564:2198 564:2199 564:2200 564:2201 564:2202 564:2203 564:2204 564:2205 564:2206 564:2207 564:2208 564:2209 564:2247 564:2248 564:2249 564:2250 564:2251 565:2210 565:2211 565:2212 565:2217 565:2218 565:2219 565:2220 565:2222 565:2223 574:2213 574:2214 574:2215 574:2216 576:2225 576:2226 576:2227 576:2228 576:2235 576:2236 576:2237 576:2238 576:2239 578:2253 580:2254 583:2258 583:2260 583:2261 583:2262 583:2264 583:2308 583:2309 583:2310 583:2311 583:2312 583:2313 583:2314 584:2265 584:2266 584:2267 584:2268 584:2269 584:2270 584:2271 584:2272 584:2273 584:2274 584:2275 584:2276 584:2277 584:2278 584:2279 584:2280 584:2281 584:2282 584:2283 584:2284 584:2285 584:2286 584:2287 584:2288 584:2289 584:2290 584:2291 584:2292 584:2293 584:2294 584:2295 584:2296 584:2297 584:2298 585:2301 585:2302 585:2303 585:2304 585:2305 588:2316 588:2318 588:2319 588:2320 588:2322 588:2352 588:2353 589:2321 589:2325 589:2326 589:2327 589:2328 589:2329 589:2330 589:2338 589:2339 589:2340 589:2341 589:2342 590:2344 590:2345 590:2346 590:2347 590:2349 590:2350 594:708 594:709 594:710 594:712 594:713 594:714 594:719 594:759 594:760 595:721 595:722 595:723 595:724 597:715 597:726 597:727 597:728 597:729 597:730 597:739 597:740 597:741 597:742 597:743 599:716 599:745 599:746 601:717 601:747 601:748 603:718 603:749 603:750 604:751 604:752 604:753 604:754 604:756 604:757 609:762 609:763 609:764 609:766 609:767 609:768 609:772 609:809 609:810 610:774 610:775 610:776 610:777 612:769 612:779 612:780 612:781 612:782 612:783 612:791 612:792 612:793 612:794 612:795 614:770 614:797 614:798 616:771 616:799 616:800 617:801 617:802 617:803 617:804 617:806 617:807 621:812 621:813 621:814 621:816 621:817 621:818 621:821 621:839 621:840 622:823 622:824 622:825 622:826 624:819 624:827 624:828 626:820 626:829 626:830 627:831 627:832 627:833 627:834 627:836 627:837 631:842 631:843 631:844 631:846 631:847 631:848 631:850 631:869 631:870 632:852 632:853 632:854 632:855 632:856 632:857 632:858 634:849 634:859 634:860 635:861 635:862 635:863 635:864 635:866 635:867 639:2355 639:2357 639:2358 639:2359 639:2360 639:2428 639:2429 642:2362 642:2363 643:2365 643:2366 643:2367 644:2369 644:2370 644:2371 644:2372 644:2373 644:2374 644:2375 644:2376 644:2377 644:2378 644:2379 644:2380 644:2381 644:2383 644:2384 645:2386 645:2387 645:2388 645:2389 645:2390 645:2391 645:2392 645:2411 645:2412 645:2413 645:2414 645:2415 649:2417 649:2418 651:2419 651:2420 651:2421 651:2422 651:2424 651:2425 652:2427 654:2885 654:2887 654:2888 654:2889 654:2892 654:2921 654:2922 657:2890 657:2891 657:2895 657:2896 657:2897 657:2898 657:2901 657:2902 657:2903 657:2904 657:2906 657:2907 657:2908 657:2909 658:2912 658:2913 658:2914 658:2915 658:2917 658:2918 659:2920 661:2924 661:2926 661:2927 661:2928 661:2929 661:2957 661:2958 663:2931 663:2932 663:2933 664:2934 664:2935 664:2936 664:2937 664:2938 664:2939 664:2940 664:2941 664:2942 664:2943 664:2944 664:2946 664:2947 665:2948 665:2949 665:2950 665:2951 665:2953 665:2954 666:2956 669:2487 669:2489 669:2490 669:2491 669:2553 669:2554 670:2493 671:2494 671:2495 671:2496 671:2497 671:2498 671:2499 671:2500 671:2501 671:2502 671:2503 671:2504 671:2505 671:2506 671:2507 671:2508 671:2509 671:2510 671:2511 671:2512 671:2513 671:2514 671:2515 671:2516 671:2517 671:2518 671:2519 671:2520 671:2521 671:2522 671:2523 671:2524 671:2525 671:2526 671:2527 671:2528 671:2531 671:2532 671:2533 671:2536 671:2537 671:2538 671:2539 671:2540 671:2541 671:2542 672:2543 673:2544 673:2545 673:2546 673:2547 673:2549 673:2550 674:2552 677:2612 677:2614 677:2615 677:2616 677:2677 677:2678 678:2618 679:2619 679:2620 679:2621 679:2622 679:2623 679:2624 679:2625 679:2626 679:2627 679:2628 679:2629 679:2630 679:2631 679:2632 679:2633 679:2634 679:2635 679:2636 679:2637 679:2638 679:2639 679:2640 679:2641 679:2642 679:2643 679:2644 679:2645 679:2646 679:2647 679:2648 679:2649 679:2650 679:2651 679:2652 679:2655 679:2656 679:2657 679:2660 679:2661 679:2662 679:2663 679:2664 679:2665 679:2666 680:2667 681:2668 681:2669 681:2670 681:2671 681:2673 681:2674 682:2676 686:2818 686:2820 686:2821 686:2822 686:2882 686:2883 687:2824 688:2825 688:2826 688:2827 688:2828 688:2829 688:2830 688:2831 688:2832 688:2833 688:2834 688:2835 688:2836 688:2837 688:2838 688:2839 688:2840 688:2841 688:2842 688:2843 688:2844 688:2845 688:2846 688:2847 688:2848 688:2849 688:2850 688:2851 688:2852 688:2853 688:2854 688:2855 688:2856 688:2857 688:2860 688:2861 688:2862 688:2865 688:2866 688:2867 688:2868 688:2869 688:2870 688:2871 689:2872 690:2873 690:2874 690:2875 690:2876 690:2878 690:2879 691:2881 695:2680 695:2682 695:2683 695:2684 695:2815 695:2816 696:2686 697:2688 697:2689 697:2690 697:2691 697:2692 697:2693 697:2694 697:2695 697:2696 697:2697 697:2698 697:2699 697:2700 697:2701 697:2702 697:2703 697:2704 697:2706 697:2707 697:2709 697:2710 697:2711 697:2712 697:2720 697:2721 697:2722 697:2723 697:2724 697:2733 697:2734 697:2735 697:2736 697:2737 698:2740 698:2741 698:2742 698:2743 698:2744 698:2745 698:2746 698:2747 698:2748 698:2749 698:2750 698:2751 698:2752 698:2753 698:2754 698:2755 698:2756 698:2757 698:2758 698:2759 698:2760 698:2761 698:2762 698:2763 698:2764 698:2765 698:2766 698:2767 698:2768 698:2769 698:2770 698:2771 698:2772 698:2773 698:2774 698:2775 698:2776 698:2777 698:2778 698:2781 698:2782 698:2783 698:2786 698:2787 698:2788 698:2789 698:2790 698:2791 698:2792 698:2799 698:2800 698:2801 698:2802 698:2803 699:2805 700:2806 700:2807 700:2808 700:2809 700:2811 700:2812 701:2814 704:3335 704:3337 704:3338 704:3339 704:3348 704:3453 704:3454 705:3340 705:3350 705:3351 706:3341 706:3353 706:3354 706:3355 706:3356 706:3357 706:3358 706:3359 706:3360 706:3447 706:3448 706:3449 706:3450 706:3451 707:3361 707:3362 707:3363 707:3364 707:3366 707:3367 708:3342 708:3371 708:3372 708:3373 708:3374 708:3375 708:3376 708:3377 708:3378 708:3379 708:3380 708:3381 708:3382 708:3383 709:3343 709:3344 709:3385 709:3386 709:3387 709:3388 709:3424 709:3439 709:3440 709:3441 709:3442 711:3389 711:3390 713:3345 713:3391 713:3392 715:3346 715:3394 715:3395 715:3396 715:3397 715:3398 715:3399 715:3406 715:3407 715:3408 715:3409 715:3410 717:3412 717:3413 717:3414 719:3415 719:3416 719:3417 719:3419 719:3421 719:3422 720:3418 725:3347 725:3425 725:3426 725:3427 725:3428 725:3429 725:3430 726:3431 726:3432 726:3433 726:3434 726:3436 726:3437 733:3456 733:3458 733:3459 733:3460 733:3523 733:3524 734:3461 734:3467 734:3468 735:3462 735:3463 735:3469 735:3470 735:3471 736:3473 736:3474 736:3475 736:3476 736:3489 736:3490 736:3491 736:3492 736:3493 737:3464 737:3477 737:3478 738:3479 740:3465 740:3496 740:3497 740:3498 740:3499 740:3500 740:3509 740:3510 740:3511 740:3512 740:3513 741:3515 741:3516 741:3517 741:3518 741:3520 741:3521 745:3633 745:3635 745:3636 745:3637 745:3699 745:3700 746:3639 747:3640 747:3641 747:3642 747:3643 747:3644 747:3645 747:3646 747:3647 747:3648 747:3649 747:3650 747:3651 747:3652 747:3653 747:3654 747:3655 747:3656 747:3657 747:3658 747:3659 747:3660 747:3661 747:3662 747:3663 747:3664 747:3665 747:3666 747:3667 747:3668 747:3669 747:3670 747:3671 747:3672 747:3673 747:3674 747:3677 747:3678 747:3679 747:3682 747:3683 747:3684 747:3685 747:3686 747:3687 747:3688 748:3689 749:3690 749:3691 749:3692 749:3693 749:3695 749:3696 750:3698 754:3702 754:3704 754:3705 754:3706 754:3717 754:3719 754:3914 754:3915 754:3916 754:3917 754:3918 754:3919 754:3920 755:3707 755:3720 755:3721 755:3722 755:3723 755:3724 755:3725 755:3726 755:3727 755:3728 755:3729 755:3730 755:3731 755:3732 755:3733 755:3734 755:3735 755:3736 755:3737 755:3738 755:3739 755:3740 755:3741 755:3742 755:3743 755:3744 755:3745 755:3746 755:3747 755:3748 755:3749 756:3708 756:3751 756:3752 756:3753 756:3754 756:3755 756:3756 756:3757 756:3758 756:3892 756:3893 756:3894 756:3895 756:3896 757:3759 757:3760 757:3761 757:3762 757:3764 757:3765 762:3709 762:3710 762:3769 762:3770 762:3771 762:3772 762:3773 762:3774 762:3775 762:3776 762:3777 762:3778 762:3779 762:3780 762:3782 762:3783 762:3784 762:3785 762:3786 762:3802 762:3803 762:3804 762:3805 762:3806 762:3808 762:3809 763:3811 763:3812 763:3813 763:3814 763:3869 763:3884 763:3885 763:3886 763:3887 766:3711 766:3815 766:3816 766:3817 766:3818 768:3712 768:3819 768:3820 772:3713 772:3822 772:3823 772:3824 772:3825 772:3826 772:3834 772:3835 772:3836 772:3837 772:3838 774:3714 774:3841 774:3842 774:3843 774:3844 774:3845 774:3848 774:3849 774:3850 774:3851 774:3852 774:3855 774:3856 774:3857 774:3858 774:3859 775:3861 775:3862 775:3863 775:3864 775:3866 775:3867 783:3715 783:3870 783:3871 783:3872 783:3873 783:3874 783:3875 784:3876 784:3877 784:3878 784:3879 784:3881 784:3882 789:3716 789:3900 789:3901 789:3902 789:3903 790:3904 790:3905 790:3906 790:3907 790:3909 790:3910 794:2556 794:2558 794:2559 794:2560 794:2563 794:2609 794:2610 795:2566 795:2594 795:2595 795:2596 795:2597 795:2598 796:2561 796:2562 796:2567 796:2568 796:2569 796:2570 796:2571 797:2572 797:2573 797:2574 797:2575 797:2576 797:2577 797:2578 797:2579 797:2580 797:2581 797:2582 797:2583 797:2584 797:2586 797:2587 799:2600 799:2601 799:2602 799:2603 799:2605 799:2606 800:2608 804:2431 804:2433 804:2434 804:2435 804:2438 804:2484 804:2485 805:2441 805:2469 805:2470 805:2471 805:2472 805:2473 806:2436 806:2437 806:2442 806:2443 806:2444 806:2445 806:2446 806:2447 806:2448 806:2449 806:2450 806:2451 806:2452 806:2453 806:2454 806:2455 806:2456 806:2457 806:2458 806:2459 806:2461 806:2462 808:2475 808:2476 808:2477 808:2478 808:2480 808:2481 809:2483 813:2960 813:2962 813:2963 813:2964 813:2978 813:3153 813:3166 813:3178 813:3179 813:3180 813:3181 813:3183 813:3184 815:2965 815:2980 815:2981 815:2982 816:2966 816:2984 816:2985 816:2986 816:2987 816:2988 816:2989 816:2990 816:2991 816:3147 816:3148 816:3149 816:3150 816:3151 817:2992 817:2993 817:2994 817:2995 817:2997 817:2998 819:2967 819:3002 819:3003 819:3004 819:3005 819:3006 819:3007 819:3008 819:3009 819:3010 819:3011 819:3012 819:3013 819:3015 819:3016 819:3017 819:3018 819:3019 819:3035 819:3036 819:3037 819:3038 819:3039 820:3055 820:3139 820:3140 820:3141 820:3142 821:2968 821:2969 821:3042 821:3043 821:3044 821:3045 821:3046 823:3047 823:3048 823:3049 823:3050 823:3052 823:3053 828:2970 828:3056 828:3057 828:3058 829:3060 829:3061 829:3062 829:3063 829:3118 829:3133 829:3134 829:3135 829:3136 832:2971 832:3064 832:3065 832:3066 832:3067 834:2972 834:3068 834:3069 838:2973 838:3071 838:3072 838:3073 838:3074 838:3075 838:3083 838:3084 838:3085 838:3086 838:3087 840:2974 840:3090 840:3091 840:3092 840:3093 840:3094 840:3097 840:3098 840:3099 840:3100 840:3101 840:3104 840:3105 840:3106 840:3107 840:3108 841:3110 841:3111 841:3112 841:3113 841:3115 841:3116 849:2975 849:3119 849:3120 849:3121 849:3122 849:3123 849:3124 850:3125 850:3126 850:3127 850:3128 850:3130 850:3131 856:2976 856:3154 856:3155 856:3156 856:3157 857:3158 857:3159 857:3160 857:3161 857:3163 857:3164 860:2977 860:3167 860:3168 860:3169 861:3170 861:3171 861:3172 861:3173 861:3175 861:3176 865:3186 865:3188 865:3189 865:3190 865:3199 865:3332 865:3333 867:3191 867:3201 867:3202 868:3192 868:3204 868:3205 868:3206 868:3207 868:3208 868:3209 868:3210 868:3211 868:3326 868:3327 868:3328 868:3329 868:3330 869:3212 869:3213 869:3214 869:3215 869:3217 869:3218 871:3193 871:3222 871:3223 871:3224 871:3225 871:3226 871:3227 871:3228 871:3229 871:3230 871:3231 871:3232 871:3233 871:3235 871:3236 871:3237 871:3238 871:3239 871:3255 871:3256 871:3257 871:3258 871:3259 876:3194 876:3261 876:3262 877:3264 877:3265 877:3266 877:3267 877:3303 877:3318 877:3319 877:3320 877:3321 880:3195 880:3268 880:3269 880:3270 880:3271 882:3196 882:3272 882:3273 886:3197 886:3275 886:3276 886:3277 886:3278 886:3279 886:3286 886:3287 886:3288 886:3289 886:3290 888:3292 888:3293 888:3294 890:3295 890:3296 890:3297 890:3298 890:3300 890:3301 897:3198 897:3304 897:3305 897:3306 897:3307 897:3308 897:3309 898:3310 898:3311 898:3312 898:3313 898:3315 898:3316 903:4122 903:4124 903:4125 903:4126 903:4164 903:4165 904:4127 904:4128 904:4130 904:4131 904:4132 904:4133 904:4134 904:4135 905:4138 905:4139 905:4140 905:4141 905:4143 905:4144 905:4145 905:4146 906:4149 906:4150 906:4151 906:4152 906:4153 906:4154 906:4155 906:4156 906:4157 906:4158 906:4160 906:4161 907:4162 909:4163 911:4167 911:4168 911:4170 911:4171 911:4172 911:4238 911:4239 912:4179 912:4180 912:4181 912:4182 912:4183 912:4191 912:4192 912:4193 912:4194 912:4195 913:4173 913:4174 913:4198 913:4199 913:4200 913:4201 913:4202 913:4203 913:4204 913:4205 913:4206 913:4207 913:4208 913:4209 913:4231 913:4232 913:4233 913:4234 913:4235 914:4210 914:4211 914:4237 915:4175 915:4176 915:4215 915:4216 915:4217 915:4218 915:4219 915:4220 915:4221 915:4222 915:4223 915:4224 915:4225 916:4226 916:4227 920:937 920:938 920:939 920:941 920:942 920:943 920:964 920:965 921:945 921:946 921:947 922:946 923:948 923:949 923:950 923:951 923:952 923:956 923:957 923:958 923:959 923:961 923:962 923:963 924:953 924:954 924:955 925:954 933:4606 933:4610 933:4611 933:4612 933:4614 933:4615 933:4616 933:4621 933:4638 933:4639 934:4607 934:4617 934:4618 934:4619 934:4620 934:4623 934:4624 934:4625 934:4626 934:4627 934:4628 934:4629 935:4608 935:4630 935:4631 935:4632 935:4633 935:4635 935:4636 936:4609 938:3526 938:3527 938:3528 938:3530 938:3531 938:3532 938:3564 938:3565 939:3536 939:3537 939:3538 939:3539 939:3541 939:3542 940:3533 940:3534 940:3544 940:3545 940:3546 940:3547 940:3548 940:3549 940:3550 940:3551 940:3552 940:3553 940:3555 940:3556 940:3557 940:3558 940:3559 940:3561 940:3562 940:3563 943:4641 943:4643 943:4644 943:4645 943:4671 943:4672 944:4648 944:4649 944:4650 944:4651 944:4652 944:4653 944:4654 944:4655 944:4656 944:4664 944:4665 944:4666 944:4667 944:4668 945:4670 948:4732 948:4734 948:4735 948:4736 948:4828 948:4829 949:4737 949:4738 949:4740 949:4741 949:4742 949:4743 949:4744 949:4745 950:4748 950:4749 950:4750 950:4751 950:4752 950:4753 950:4754 950:4755 950:4756 950:4757 950:4758 950:4759 950:4760 950:4761 950:4762 950:4763 950:4764 950:4765 950:4766 950:4767 950:4768 950:4769 950:4770 950:4771 950:4772 950:4773 950:4774 950:4775 950:4776 950:4777 950:4778 950:4779 950:4780 950:4781 950:4782 950:4820 950:4821 950:4822 950:4823 950:4824 951:4783 951:4784 951:4785 951:4790 951:4791 951:4792 951:4793 951:4795 951:4796 960:4786 960:4787 960:4788 960:4789 962:4798 962:4799 962:4800 962:4801 962:4808 962:4809 962:4810 962:4811 962:4812 964:4826 966:4827 969:4674 969:4676 969:4677 969:4678 969:4680 969:4724 969:4725 969:4726 969:4727 969:4728 969:4729 969:4730 970:4681 970:4682 970:4683 970:4684 970:4685 970:4686 970:4687 970:4688 970:4689 970:4690 970:4691 970:4692 970:4693 970:4694 970:4695 970:4696 970:4697 970:4698 970:4699 970:4700 970:4701 970:4702 970:4703 970:4704 970:4705 970:4706 970:4707 970:4708 970:4709 970:4710 970:4711 970:4712 970:4713 970:4714 971:4717 971:4718 971:4719 971:4720 971:4721 977:4086 977:4088 977:4089 977:4090 977:4119 977:4120 978:4092 978:4093 978:4094 978:4095 981:4096 981:4097 981:4098 981:4099 984:4101 984:4102 984:4103 984:4104 984:4105 984:4112 984:4113 984:4114 984:4115 984:4116 985:4118 988:4023 988:4025 988:4026 988:4027 988:4050 988:4051 989:4029 989:4030 989:4031 989:4032 989:4033 989:4034 989:4035 989:4036 989:4037 989:4038 989:4039 989:4040 989:4041 989:4042 989:4043 989:4044 989:4045 989:4047 989:4048 989:4049 995:3922 995:3924 995:3925 995:3926 995:3927 995:4020 995:4021 998:3930 998:3931 998:3932 998:3933 998:3934 998:3935 998:3937 998:3939 998:3940 998:3941 998:3942 998:3943 998:3944 998:3945 998:3946 998:3947 998:3948 998:3999 998:4003 998:4005 998:4006 998:4007 998:4008 999:3949 999:3950 999:3951 999:3952 999:3953 999:3954 999:3955 999:3956 999:3957 999:3959 999:3960 999:3962 999:3963 999:3964 999:3965 999:3966 999:3967 999:3968 999:3969 999:3970 999:3971 999:3972 999:3973 999:3974 999:3975 999:3976 999:3978 999:3979 1000:3981 1000:3982 1000:3983 1000:3984 1000:3985 1000:3986 1000:3993 1000:3994 1000:3995 1000:3996 1000:3997 1002:4000 1002:4001 1002:4002 1004:4011 1004:4012 1004:4013 1004:4014 1004:4016 1004:4017 1005:4019 1009:4852 1009:4854 1009:4855 1009:4856 1009:4862 1009:4881 1009:4882 1010:4857 1010:4858 1010:4859 1010:4860 1010:4864 1010:4865 1010:4866 1010:4867 1010:4868 1010:4869 1010:4870 1011:4861 1011:4871 1011:4872 1012:4873 1012:4874 1012:4875 1012:4876 1012:4878 1012:4879 1016:4884 1016:4886 1016:4887 1016:4888 1016:4894 1016:4914 1016:4915 1017:4889 1017:4890 1017:4891 1017:4892 1017:4896 1017:4897 1017:4898 1017:4899 1017:4900 1017:4901 1017:4902 1017:4903 1018:4893 1018:4904 1018:4905 1019:4906 1019:4907 1019:4908 1019:4909 1019:4911 1019:4912 1023:4917 1023:4919 1023:4920 1023:4921 1023:4924 1023:4991 1023:4992 1026:4922 1026:4923 1026:4926 1026:4927 1026:4928 1026:4929 1026:4930 1026:4931 1026:4932 1026:4933 1026:4934 1026:4935 1026:4937 1026:4938 1026:4940 1026:4941 1026:4942 1026:4943 1026:4944 1026:4945 1026:4946 1026:4963 1026:4964 1026:4965 1026:4966 1026:4967 1026:4969 1026:4970 1026:4971 1026:4972 1026:4973 1026:4974 1026:4975 1026:4976 1026:4977 1026:4978 1026:4980 1026:4981 1027:4982 1027:4983 1027:4984 1027:4985 1027:4987 1027:4988 1028:4990 1039:4053 1039:4055 1039:4056 1039:4057 1039:4083 1039:4084 1040:4058 1040:4059 1040:4061 1040:4062 1040:4063 1040:4064 1040:4065 1040:4066 1042:4068 1042:4069 1042:4070 1042:4071 1042:4072 1042:4073 1042:4074 1042:4075 1042:4076 1042:4077 1042:4079 1042:4080 1043:4081 1045:4082 1047:4241 1047:4243 1047:4244 1047:4245 1047:4252 1047:4534 1047:4556 1047:4562 1047:4569 1047:4585 1047:4598 1047:4599 1047:4600 1047:4601 1047:4602 1047:4603 1047:4604 1049:4253 1049:4254 1049:4255 1049:4256 1049:4257 1055:4535 1055:4536 1055:4537 1055:4538 1055:4539 1055:4540 1055:4542 1055:4544 1055:4545 1055:4546 1055:4547 1055:4548 1055:4549 1055:4550 1055:4551 1055:4552 1055:4553 1055:4554 1057:4555 1060:4557 1060:4558 1060:4559 1060:4560 1062:4561 1064:4246 1064:4563 1064:4564 1064:4565 1064:4566 1064:4567 1064:4568 1067:4247 1067:4248 1067:4570 1067:4571 1067:4572 1067:4573 1067:4574 1067:4575 1067:4576 1067:4577 1067:4578 1067:4579 1067:4580 1067:4582 1067:4583 1067:4584 1070:4260 1070:4261 1070:4262 1070:4263 1070:4264 1070:4265 1070:4266 1070:4267 1070:4268 1070:4269 1070:4270 1070:4271 1071:4277 1071:4279 1071:4280 1071:4281 1071:4282 1072:4285 1079:4273 1079:4274 1079:4275 1079:4276 1083:4288 1083:4289 1083:4290 1083:4291 1083:4292 1086:4295 1086:4296 1086:4297 1086:4298 1086:4299 1086:4300 1086:4301 1086:4302 1086:4303 1086:4304 1086:4305 1086:4306 1086:4307 1089:4310 1089:4311 1089:4312 1089:4313 1089:4314 1089:4315 1089:4316 1089:4317 1089:4318 1089:4319 1089:4320 1089:4321 1089:4322 1089:4323 1091:4324 1092:4327 1092:4328 1092:4329 1092:4330 1092:4331 1092:4332 1092:4334 1092:4335 1092:4336 1092:4337 1092:4338 1092:4339 1092:4340 1092:4347 1092:4348 1092:4349 1092:4350 1092:4351 1092:4353 1094:4354 1095:4357 1095:4358 1095:4359 1095:4360 1095:4361 1095:4362 1095:4364 1095:4365 1095:4366 1095:4367 1095:4368 1095:4369 1095:4370 1095:4377 1095:4378 1095:4379 1095:4380 1095:4381 1095:4383 1097:4384 1098:4387 1098:4388 1098:4389 1098:4390 1098:4391 1098:4392 1098:4394 1098:4395 1098:4396 1098:4397 1098:4398 1098:4399 1098:4400 1098:4401 1098:4402 1098:4403 1098:4404 1098:4405 1098:4406 1098:4407 1098:4408 1098:4409 1098:4410 1098:4411 1098:4412 1098:4413 1098:4414 1098:4415 1098:4416 1098:4417 1098:4418 1098:4419 1098:4420 1098:4421 1098:4422 1098:4423 1098:4424 1098:4425 1098:4426 1098:4427 1098:4434 1098:4435 1098:4436 1098:4437 1098:4438 1098:4440 1100:4441 1101:4444 1101:4445 1101:4446 1101:4447 1101:4448 1101:4449 1101:4450 1101:4451 1101:4452 1101:4453 1101:4454 1102:4455 1102:4456 1102:4457 1102:4458 1102:4459 1102:4460 1102:4461 1102:4462 1102:4463 1102:4464 1102:4466 1102:4467 1103:4468 1105:4469 1106:4472 1106:4473 1106:4474 1106:4475 1106:4476 1109:4479 1109:4480 1109:4481 1109:4482 1109:4483 1109:4484 1109:4485 1109:4486 1109:4487 1111:4488 1112:4586 1112:4587 1112:4588 1112:4589 1112:4590 1112:4591 1112:4592 1112:4593 1112:4594 1112:4595 1112:4596 1112:4597 1115:4491 1115:4492 1115:4493 1115:4494 1115:4495 1115:4496 1115:4497 1115:4498 1115:4500 1115:4501 1115:4502 1115:4503 1115:4504 1115:4505 1115:4512 1115:4513 1115:4514 1115:4515 1115:4516 1115:4518 1117:4519 1118:4249 1118:4250 1118:4522 1118:4523 1118:4524 1118:4525 1118:4526 1118:4527 1118:4528 1118:4529 1121:4531 1121:4994 1121:4996 1121:4997 1121:4998 1121:5042 1121:5043 1122:4999 1122:5000 1122:5002 1122:5003 1122:5004 1122:5005 1123:5006 1124:5008 1124:5009 1124:5010 1124:5011 1124:5012 1124:5013 1124:5015 1124:5016 1124:5018 1124:5019 1124:5020 1124:5021 1124:5022 1124:5023 1124:5024 1124:5025 1124:5026 1124:5027 1124:5028 1124:5032 1124:5033 1124:5034 1124:5035 1125:5029 1125:5030 1125:5031 1127:5038 1128:5039 1128:5040 1128:5041 1131:5238 1131:5240 1131:5241 1131:5242 1131:5253 1131:5254 1133:5244 1133:5245 1133:5246 1134:5247 1134:5248 1134:5249 1135:5250 1135:5251 1135:5252 1138:5256 1138:5258 1138:5259 1138:5260 1138:5262 1138:5279 1138:5280 1140:5261 1140:5264 1140:5265 1140:5266 1140:5267 1140:5268 1140:5269 1141:5270 1141:5271 1141:5272 1141:5273 1141:5275 1141:5276 1142:5278 1144:5045 1144:5047 1144:5048 1144:5049 1144:5077 1144:5078 1145:5052 1145:5053 1145:5054 1145:5058 1145:5059 1145:5060 1145:5061 1145:5063 1145:5064 1145:5065 1153:5055 1153:5056 1153:5057 1155:5066 1155:5067 1156:5068 1156:5069 1156:5070 1156:5071 1156:5073 1156:5074 1157:5076 1159:5414 1159:5416 1159:5417 1159:5418 1159:5448 1159:5449 1160:5421 1160:5422 1160:5423 1160:5424 1160:5425 1160:5426 1160:5427 1160:5428 1160:5429 1160:5432 1160:5433 1160:5434 1160:5435 1160:5436 1160:5437 1160:5440 1160:5441 1160:5442 1160:5443 1160:5444 1160:5446 1162:5447 1163:5451 1163:5453 1163:5454 1163:5455 1163:5456 1163:5480 1163:5481 1164:5458 1164:5459 1164:5460 1164:5461 1164:5462 1164:5463 1164:5464 1164:5465 1164:5466 1164:5467 1164:5469 1164:5470 1165:5471 1165:5472 1165:5473 1165:5474 1165:5476 1165:5477 1166:5479 1169:5187 1169:5189 1169:5190 1169:5191 1169:5192 1169:5235 1169:5236 1171:5195 1171:5196 1171:5197 1171:5198 1171:5199 1171:5200 1171:5202 1171:5204 1171:5205 1171:5206 1171:5207 1171:5208 1171:5209 1171:5210 1171:5211 1171:5212 1171:5213 1171:5214 1171:5218 1171:5220 1171:5221 1171:5222 1171:5223 1173:5215 1173:5216 1173:5217 1175:5226 1175:5227 1175:5228 1175:5229 1175:5231 1175:5232 1176:5234 1178:5282 1178:5284 1178:5285 1178:5286 1178:5287 1178:5345 1178:5346 1179:5290 1179:5291 1179:5292 1179:5293 1179:5294 1179:5295 1179:5296 1179:5297 1179:5298 1179:5299 1179:5300 1179:5301 1179:5302 1179:5303 1179:5304 1179:5305 1179:5306 1179:5307 1179:5308 1179:5309 1179:5310 1179:5311 1179:5312 1179:5313 1179:5314 1179:5315 1179:5316 1179:5317 1179:5318 1179:5319 1179:5320 1179:5321 1179:5322 1179:5323 1179:5330 1179:5331 1179:5332 1179:5333 1179:5334 1180:5336 1180:5337 1180:5338 1180:5339 1180:5341 1180:5342 1181:5344 1183:5348 1183:5350 1183:5351 1183:5352 1183:5353 1183:5411 1183:5412 1184:5356 1184:5357 1184:5358 1184:5359 1184:5360 1184:5361 1184:5362 1184:5363 1184:5364 1184:5365 1184:5366 1184:5367 1184:5368 1184:5369 1184:5370 1184:5371 1184:5372 1184:5373 1184:5374 1184:5375 1184:5376 1184:5377 1184:5378 1184:5379 1184:5380 1184:5381 1184:5382 1184:5383 1184:5384 1184:5385 1184:5386 1184:5387 1184:5388 1184:5389 1184:5396 1184:5397 1184:5398 1184:5399 1184:5400 1185:5402 1185:5403 1185:5404 1185:5405 1185:5407 1185:5408 1186:5410 1189:5080 1189:5082 1189:5083 1189:5084 1189:5184 1189:5185 1190:5086 1190:5087 1190:5088 1190:5089 1190:5090 1190:5091 1191:5092 1191:5093 1191:5094 1191:5095 1191:5096 1191:5097 1191:5098 1191:5099 1191:5100 1191:5101 1191:5103 1191:5104 1192:5106 1192:5107 1192:5108 1192:5109 1192:5110 1192:5177 1192:5178 1192:5179 1192:5180 1192:5181 1193:5183 1195:5538 1195:5540 1195:5541 1195:5542 1195:5551 1195:5552 1196:5544 1196:5545 1196:5546 1196:5547 1196:5548 1196:5549 1196:5550 1200:5518 1200:5520 1200:5521 1200:5522 1200:5535 1200:5536 1201:5524 1201:5525 1201:5526 1201:5527 1201:5528 1201:5529 1201:5530 1201:5531 1201:5532 1201:5533 1201:5534 1240:4831 1240:4833 1240:4834 1240:4835 1240:4836 1240:4849 1240:4850 1241:4838 1241:4839 1242:4840 1242:4841 1242:4842 1242:4843 1242:4845 1242:4846 1243:4848 1247:5483 1247:5485 1247:5486 1247:5487 1247:5488 1247:5515 1247:5516 1248:5490 1248:5491 1248:5492 1248:5493 1248:5494 1248:5495 1248:5496 1248:5497 1248:5498 1248:5499 1248:5500 1248:5501 1248:5502 1248:5504 1248:5505 1249:5506 1249:5507 1249:5508 1249:5509 1249:5511 1249:5512 1250:5514 1254:5554 1254:5556 1254:5557 1254:5558 1254:5701 1254:5702 1255:5560 1255:5561 1256:5563 1256:5564 1256:5565 1256:5566 1256:5567 1256:5568 1256:5569 1256:5570 1256:5571 1256:5572 1256:5573 1256:5574 1256:5575 1256:5576 1256:5578 1256:5579 1256:5580 1256:5581 1256:5582 1256:5583 1256:5584 1256:5675 1256:5676 1256:5677 1256:5678 1256:5679 1256:5694 1256:5695 1256:5696 1256:5697 1256:5698 1257:5587 1257:5588 1257:5589 1257:5590 1257:5591 1257:5592 1257:5700 1258:5595 1258:5596 1258:5597 1258:5598 1258:5599 1258:5600 1259:5603 1259:5604 1259:5605 1259:5606 1259:5607 1259:5608 1260:5611 1260:5612 1260:5613 1260:5614 1260:5615 1260:5616 1261:5619 1261:5620 1261:5621 1261:5622 1261:5623 1261:5624 1262:5627 1262:5628 1262:5629 1262:5630 1262:5631 1262:5632 1263:5635 1263:5636 1263:5637 1263:5638 1263:5639 1263:5640 1264:5643 1264:5644 1264:5645 1264:5646 1264:5647 1264:5648 1265:5651 1265:5652 1265:5653 1265:5654 1265:5655 1265:5656 1266:5659 1266:5660 1266:5661 1266:5662 1266:5663 1266:5664 1267:5667 1267:5668 1267:5669 1267:5670 1267:5671 1267:5672 1269:5681 1269:5682 1275:2105 1275:2107 1275:2108 1275:2109 1275:2156 1275:2157 1276:2111 1276:2112 1277:2114 1277:2115 1277:2116 1277:2117 1277:2118 1277:2119 1277:2120 1277:2121 1277:2122 1277:2123 1277:2124 1277:2125 1277:2149 1277:2150 1277:2151 1277:2152 1277:2153 1278:2155 1282:5704 1282:5706 1282:5707 1282:5708 1282:5730 1282:5731 1283:5710 1283:5711 1283:5712 1283:5713 1283:5714 1283:5715 1283:5716 1283:5717 1283:5718 1283:5719 1283:5720 1283:5721 1283:5722 1283:5723 1283:5724 1283:5725 1283:5727 1283:5728 1283:5729 1288:5733 1288:5735 1288:5736 1288:5737 1288:5759 1288:5760 1289:5739 1289:5740 1289:5741 1289:5742 1289:5743 1289:5744 1289:5745 1289:5746 1289:5747 1289:5748 1289:5749 1289:5750 1289:5751 1289:5752 1289:5753 1289:5754 1289:5756 1289:5757 1289:5758 1294:5762 1294:5764 1294:5765 1294:5766 1294:5788 1294:5789 1295:5768 1295:5769 1295:5770 1295:5771 1295:5772 1295:5773 1295:5774 1295:5775 1295:5776 1295:5777 1295:5778 1295:5779 1295:5780 1295:5781 1295:5782 1295:5783 1295:5785 1295:5786 1295:5787 1300:5791 1300:5793 1300:5794 1300:5795 1300:5817 1300:5818 1301:5797 1301:5798 1301:5799 1301:5800 1301:5801 1301:5802 1301:5803 1301:5804 1301:5805 1301:5806 1301:5807 1301:5808 1301:5809 1301:5810 1301:5811 1301:5812 1301:5814 1301:5815 1301:5816 1306:5820 1306:5822 1306:5823 1306:5824 1306:5846 1306:5847 1307:5826 1307:5827 1307:5828 1307:5829 1307:5830 1307:5831 1307:5832 1307:5833 1307:5834 1307:5835 1307:5836 1307:5837 1307:5838 1307:5839 1307:5840 1307:5841 1307:5843 1307:5844 1307:5845 1312:5849 1312:5851 1312:5852 1312:5853 1312:5895 1312:5896 1313:5855 1313:5856 1313:5857 1313:5858 1313:5859 1313:5860 1313:5862 1313:5863 1313:5864 1313:5865 1313:5866 1313:5867 1313:5868 1313:5871 1313:5872 1313:5873 1313:5874 1313:5875 1313:5876 1313:5879 1313:5880 1313:5881 1313:5882 1313:5883 1313:5885 1313:5886 1313:5887 1313:5888 1313:5889 1313:5890 1313:5892 1313:5893 1313:5894 1318:5898 1318:5900 1318:5901 1318:5902 1318:6011 1318:6012 1319:5904 1319:5905 1320:5907 1320:5908 1320:5909 1320:5910 1320:5911 1320:5912 1320:5913 1320:5914 1320:5915 1320:5916 1320:5917 1320:5918 1320:5919 1320:5920 1320:5921 1320:5922 1320:5923 1320:5924 1320:5925 1320:5926 1320:5927 1320:5928 1320:5929 1320:5930 1320:5931 1320:5932 1320:5933 1320:5934 1320:5935 1320:5936 1320:5937 1320:5938 1320:5939 1320:5940 1320:5941 1320:5942 1320:5944 1320:5945 1320:5946 1320:5947 1320:5948 1320:5949 1320:5950 1320:5977 1320:5978 1320:5979 1320:5980 1320:5981 1320:5985 1320:5986 1320:5987 1320:5988 1320:5990 1320:5991 1320:6004 1320:6005 1320:6006 1320:6007 1320:6008 1321:5953 1321:5954 1321:5955 1321:5956 1321:5957 1321:5958 1321:6010 1322:5961 1322:5962 1322:5963 1322:5964 1322:5965 1322:5966 1323:5969 1323:5970 1323:5971 1323:5972 1323:5973 1323:5974 1325:5983 1325:5984 1327:5994 1327:5995 1327:5996 1327:5997 1327:5998 1327:5999 1327:6000 1327:6001 1333:6014 1333:6016 1333:6017 1333:6018 1333:6068 1333:6069 1334:6020 1334:6021 1334:6022 1334:6023 1334:6024 1334:6025 1334:6027 1334:6028 1334:6029 1334:6030 1334:6031 1334:6032 1334:6033 1334:6036 1334:6037 1334:6038 1334:6039 1334:6040 1334:6041 1334:6044 1334:6045 1334:6046 1334:6047 1334:6048 1334:6049 1334:6052 1334:6053 1334:6054 1334:6055 1334:6056 1334:6058 1334:6059 1334:6060 1334:6061 1334:6062 1334:6063 1334:6065 1334:6066 1334:6067 1339:6071 1339:6073 1339:6074 1339:6075 1339:6117 1339:6118 1340:6077 1340:6078 1340:6079 1340:6080 1340:6081 1340:6082 1340:6084 1340:6085 1340:6086 1340:6087 1340:6088 1340:6089 1340:6090 1340:6093 1340:6094 1340:6095 1340:6096 1340:6097 1340:6098 1340:6101 1340:6102 1340:6103 1340:6104 1340:6105 1340:6107 1340:6108 1340:6109 1340:6110 1340:6111 1340:6112 1340:6114 1340:6115 1340:6116 1345:6120 1345:6122 1345:6123 1345:6124 1345:6174 1345:6175 1346:6126 1346:6127 1346:6128 1346:6129 1346:6130 1346:6131 1346:6133 1346:6134 1346:6135 1346:6136 1346:6137 1346:6138 1346:6139 1346:6142 1346:6143 1346:6144 1346:6145 1346:6146 1346:6147 1346:6150 1346:6151 1346:6152 1346:6153 1346:6154 1346:6155 1346:6158 1346:6159 1346:6160 1346:6161 1346:6162 1346:6164 1346:6165 1346:6166 1346:6167 1346:6168 1346:6169 1346:6171 1346:6172 1346:6173 1349:6177 1349:6179 1349:6180 1349:6181 1349:6183 1349:6266 1349:6267 1349:6268 1349:6269 1349:6270 1349:6271 1349:6272 1350:6184 1350:6185 1350:6186 1350:6187 1350:6188 1350:6189 1350:6190 1350:6191 1350:6192 1351:6195 1351:6196 1351:6197 1351:6198 1351:6199 1351:6200 1351:6201 1351:6202 1351:6203 1352:6206 1352:6207 1352:6208 1352:6209 1352:6210 1352:6211 1352:6212 1352:6213 1352:6215 1352:6216 1352:6217 1353:6220 1353:6221 1353:6222 1353:6223 1353:6224 1353:6225 1353:6226 1353:6227 1353:6229 1353:6230 1353:6231 1354:6234 1354:6235 1354:6236 1354:6237 1354:6238 1354:6239 1354:6240 1354:6241 1354:6242 1354:6243 1354:6244 1354:6245 1354:6246 1354:6247 1354:6248 1354:6249 1354:6250 1354:6251 1354:6252 1354:6253 1354:6254 1354:6255 1354:6256 1354:6257 1354:6258 1354:6259 1354:6260 1354:6261 1354:6262 1354:6263 1357:6274 1357:6276 1357:6277 1357:6278 1357:6284 1357:6412 1357:6413 1357:6414 1357:6415 1357:6416 1357:6417 1357:6418 1358:6285 1358:6286 1358:6287 1358:6288 1358:6289 1358:6290 1358:6291 1358:6292 1358:6293 1359:6296 1359:6297 1359:6298 1359:6299 1359:6300 1359:6301 1359:6302 1359:6303 1359:6304 1360:6307 1360:6308 1360:6309 1360:6310 1360:6311 1360:6312 1360:6313 1360:6314 1360:6315 1360:6316 1360:6317 1360:6318 1360:6319 1360:6320 1360:6321 1360:6322 1360:6323 1360:6324 1360:6325 1360:6326 1360:6327 1360:6328 1360:6329 1360:6330 1360:6331 1360:6365 1360:6399 1360:6403 1360:6404 1360:6405 1360:6406 1360:6407 1361:6409 1368:6333 1368:6334 1368:6335 1368:6336 1368:6337 1368:6338 1368:6340 1368:6341 1368:6342 1368:6343 1368:6345 1368:6346 1368:6347 1368:6348 1368:6349 1368:6350 1368:6351 1368:6352 1369:6279 1369:6280 1369:6353 1369:6354 1369:6355 1369:6356 1369:6357 1369:6358 1369:6360 1369:6361 1369:6362 1370:6363 1370:6364 1375:6366 1375:6367 1375:6368 1375:6369 1375:6370 1375:6371 1375:6372 1375:6374 1375:6375 1375:6376 1375:6377 1375:6379 1375:6380 1375:6381 1375:6382 1375:6383 1375:6384 1375:6385 1375:6386 1376:6281 1376:6282 1376:6387 1376:6388 1376:6389 1376:6390 1376:6391 1376:6392 1376:6394 1376:6395 1376:6396 1377:6397 1377:6398 1379:6400 1379:6401 1379:6402 1384:6420 1384:6422 1384:6423 1384:6424 1384:6789 1384:6790 1386:6438 1386:6439 1388:6440 1388:6441 1388:6442 1388:6679 1388:6689 1388:6697 1388:6709 1388:6710 1388:6711 1388:6712 1388:6714 1388:6715 1400:6443 1400:6444 1400:6445 1400:6446 1400:6447 1400:6449 1400:6450 1400:6451 1400:6452 1400:6453 1400:6461 1400:6462 1400:6463 1400:6464 1400:6465 1401:6468 1401:6469 1401:6470 1401:6471 1401:6472 1401:6473 1401:6474 1401:6673 1401:6674 1401:6675 1401:6676 1401:6677 1402:6425 1402:6426 1402:6476 1402:6477 1402:6478 1402:6479 1402:6480 1402:6481 1402:6482 1402:6483 1402:6484 1402:6537 1402:6538 1402:6539 1402:6540 1402:6541 1403:6486 1403:6487 1404:6488 1406:6545 1406:6546 1406:6547 1406:6548 1406:6549 1406:6550 1407:6552 1407:6665 1407:6666 1407:6667 1407:6668 1407:6669 1408:6427 1408:6428 1408:6553 1408:6554 1408:6555 1408:6556 1408:6557 1408:6558 1408:6559 1408:6560 1408:6561 1409:6562 1409:6563 1410:6567 1410:6568 1410:6569 1410:6570 1410:6571 1410:6572 1410:6574 1410:6575 1410:6576 1410:6577 1410:6578 1410:6585 1410:6586 1410:6587 1410:6588 1410:6589 1410:6591 1410:6592 1410:6593 1410:6594 1411:6429 1411:6430 1411:6596 1411:6597 1411:6598 1411:6599 1411:6600 1411:6601 1411:6602 1411:6603 1411:6604 1411:6657 1411:6658 1411:6659 1411:6660 1411:6661 1412:6606 1412:6607 1413:6608 1417:6680 1417:6681 1417:6682 1417:6683 1417:6684 1417:6685 1417:6686 1417:6687 1417:6688 1418:6690 1418:6691 1418:6692 1418:6693 1418:6694 1418:6695 1418:6696 1419:6431 1419:6432 1419:6698 1419:6699 1419:6700 1419:6701 1419:6702 1419:6703 1419:6704 1419:6706 1419:6707 1419:6708 1422:6717 1422:6782 1422:6783 1422:6784 1422:6785 1422:6786 1423:6788 1424:6433 1424:6434 1424:6718 1424:6719 1424:6720 1424:6721 1424:6722 1424:6723 1424:6724 1424:6725 1425:6435 1425:6436 1425:6729 1425:6730 1425:6731 1425:6732 1425:6733 1425:6734 1425:6735 1425:6736 1430:6792 1430:6794 1430:6795 1430:6796 1430:6800 1430:6942 1430:6943 1430:6944 1430:6945 1430:6946 1430:6947 1430:6948 1431:6801 1431:6802 1431:6803 1431:6804 1431:6805 1431:6807 1431:6808 1431:6809 1431:6810 1431:6811 1431:6812 1431:6813 1431:6814 1431:6815 1431:6816 1431:6818 1431:6819 1431:6820 1431:6821 1432:6824 1432:6827 1432:6828 1432:6829 1432:6830 1432:6831 1432:6832 1432:6833 1432:6834 1432:6835 1432:6836 1433:6839 1433:6840 1433:6841 1433:6842 1433:6843 1433:6844 1433:6845 1434:6848 1434:6849 1434:6850 1434:6851 1434:6852 1434:6853 1434:6854 1435:6857 1435:6858 1435:6859 1435:6860 1435:6861 1435:6862 1435:6863 1436:6866 1436:6867 1436:6868 1436:6869 1436:6870 1437:6873 1437:6874 1437:6875 1437:6876 1437:6877 1437:6878 1437:6879 1438:6882 1438:6883 1438:6884 1438:6885 1438:6886 1438:6887 1438:6888 1439:6891 1439:6892 1439:6893 1439:6894 1439:6895 1439:6896 1441:6897 1441:6900 1441:6901 1441:6902 1441:6903 1441:6904 1441:6905 1441:6906 1441:6907 1441:6908 1441:6909 1441:6910 1441:6911 1442:6797 1442:6798 1442:6912 1442:6913 1442:6914 1442:6915 1442:6916 1442:6917 1442:6918 1442:6919 1442:6920 1442:6921 1442:6923 1442:6924 1442:6925 1442:6926 1442:6927 1442:6929 1442:6930 1443:6931 1443:6932 1443:6933 1443:6934 1443:6935 1443:6936 1443:6937 1443:6938 1443:6939 1450:7184 1450:7188 1450:7190 1450:7191 1450:7192 1450:7347 1450:7348 1451:7185 1451:7193 1451:7201 1451:7202 1451:7203 1451:7204 1451:7205 1451:7212 1451:7213 1451:7214 1451:7215 1451:7216 1452:7186 1452:7218 1452:7219 1452:7220 1452:7221 1453:7187 1455:7222 1455:7223 1455:7224 1455:7286 1455:7288 1455:7289 1455:7290 1455:7291 1455:7293 1455:7294 1469:7225 1469:7226 1469:7227 1469:7228 1469:7229 1469:7230 1469:7232 1469:7234 1469:7235 1469:7236 1469:7237 1469:7244 1469:7245 1469:7246 1469:7247 1469:7248 1469:7250 1469:7252 1469:7253 1469:7254 1469:7255 1469:7256 1469:7257 1469:7258 1469:7259 1470:7194 1470:7260 1470:7261 1470:7262 1470:7263 1470:7265 1470:7266 1470:7267 1470:7268 1470:7269 1470:7276 1470:7277 1470:7278 1470:7279 1470:7280 1470:7282 1470:7283 1470:7284 1470:7285 1479:7315 1479:7338 1479:7340 1479:7341 1479:7342 1479:7343 1480:7346 1487:7195 1487:7196 1487:7296 1487:7298 1487:7299 1487:7300 1487:7301 1487:7302 1487:7303 1490:7305 1490:7306 1491:7308 1491:7309 1492:7311 1492:7312 1492:7313 1494:7316 1494:7318 1494:7319 1494:7320 1494:7330 1494:7331 1494:7332 1494:7333 1494:7335 1494:7336 1494:7337 1495:7197 1495:7198 1495:7321 1495:7322 1495:7323 1495:7324 1495:7325 1495:7326 1495:7327 1495:7329 1549:6950 1549:6999 1549:7001 1549:7002 1549:7003 1549:7181 1549:7182 1550:6951 1550:7005 1550:7006 1550:7007 1550:7008 1550:7010 1550:7011 1550:7012 1550:7013 1550:7014 1550:7030 1550:7031 1550:7032 1550:7033 1550:7034 1550:7036 1550:7037 1551:6952 1551:7039 1551:7040 1551:7041 1551:7042 1551:7043 1551:7044 1551:7045 1551:7047 1551:7048 1551:7049 1551:7050 1551:7051 1551:7100 1551:7101 1551:7102 1551:7103 1551:7104 1551:7174 1551:7175 1551:7176 1551:7177 1551:7178 1552:6953 1552:7180 1553:6954 1554:6955 1555:6956 1556:6957 1557:6958 1558:6959 1559:6960 1560:6961 1561:6962 1561:7108 1561:7109 1561:7110 1561:7111 1561:7113 1561:7114 1561:7115 1561:7116 1561:7117 1561:7166 1561:7167 1561:7168 1561:7169 1561:7170 1562:6963 1563:6964 1564:6965 1565:3567 1565:3569 1565:3570 1565:3571 1565:3572 1565:3630 1565:3631 1565:6966 1566:3575 1566:3576 1566:3577 1566:3578 1566:3579 1566:3580 1566:3581 1566:3582 1566:3583 1566:3584 1566:3585 1566:3586 1566:3587 1566:3588 1566:3589 1566:3590 1566:3591 1566:3592 1566:3593 1566:3594 1566:3595 1566:3596 1566:3597 1566:3598 1566:3599 1566:3600 1566:3601 1566:3602 1566:3603 1566:3604 1566:3605 1566:3606 1566:3607 1566:3608 1566:3623 1566:3624 1566:3625 1566:3626 1566:3627 1566:6967 1567:3629 1567:6968 1568:3611 1568:3612 1568:3613 1568:3614 1568:3615 1568:3616 1568:3618 1568:3619 1568:6969 1569:6970 1570:6971 1571:6972 1572:6973 1572:7419 1572:7421 1572:7422 1572:7423 1572:7496 1572:7497 1573:6974 1573:7428 1573:7429 1573:7430 1573:7487 1573:7488 1573:7489 1573:7490 1573:7492 1573:7493 1573:7494 1573:7495 1574:6975 1575:6976 1576:6977 1577:6978 1578:6979 1579:6980 1580:6981 1581:6982 1582:6983 1583:6984 1583:7424 1583:7425 1583:7431 1583:7432 1583:7433 1583:7434 1583:7435 1583:7436 1583:7437 1584:6985 1584:7440 1584:7441 1584:7442 1584:7443 1584:7444 1584:7445 1584:7446 1584:7447 1584:7448 1584:7449 1584:7450 1584:7451 1584:7452 1584:7453 1584:7454 1584:7455 1584:7456 1584:7457 1584:7458 1584:7459 1584:7460 1584:7461 1584:7462 1584:7463 1584:7464 1584:7465 1584:7466 1584:7467 1584:7468 1584:7469 1584:7470 1584:7471 1584:7472 1584:7473 1584:7480 1584:7481 1584:7482 1584:7483 1584:7484 1585:6986 1585:7486 1586:6987 1587:6988 1588:6989 1589:6990 1589:7350 1589:7352 1589:7353 1589:7354 1589:7356 1589:7411 1589:7412 1589:7413 1589:7414 1589:7415 1589:7416 1589:7417 1590:6991 1590:7357 1590:7358 1590:7359 1590:7360 1590:7361 1590:7362 1591:6992 1591:7366 1591:7367 1591:7368 1591:7369 1591:7370 1591:7371 1592:6993 1592:7363 1592:7375 1592:7376 1592:7377 1592:7378 1592:7379 1592:7380 1593:6994 1593:7372 1593:7384 1593:7385 1593:7386 1593:7387 1593:7388 1593:7389 1594:6995 1594:7381 1594:7393 1594:7394 1594:7395 1594:7396 1594:7397 1594:7398 1595:6996 1595:7390 1595:7402 1595:7403 1595:7404 1595:7405 1595:7406 1595:7407 1596:6997 1596:7399 1597:6998 1597:7408 *E groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/PreJava2GroovyConverter.java0000644001501200150120000001027311713765676027455 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.java; import java.util.Stack; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.treewalker.VisitorAdapter; /** This class mutates the Java AST, whilst it is still a Java AST, in readiness for conversion to Groovy, yippee-ky-a ! */ public class PreJava2GroovyConverter extends VisitorAdapter{ private String[] tokenNames; private Stack stack; public PreJava2GroovyConverter(String[] tokenNames) { this.tokenNames = tokenNames; this.stack = new Stack(); } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { if (t.getType() == JavaTokenTypes.LITERAL_do) { visitJavaLiteralDo(t); } else if (t.getType() == JavaTokenTypes.ARRAY_INIT) { visitJavaArrayInit(t); } } } private void visitJavaLiteralDo(GroovySourceAST t) { // todo - incomplete, as body of do...while... should be executed at least once, which this doesn't provide. swapTwoChildren(t); } /** * Handle Arrays. Examples: * *

           * String[] myArray = new String[] {"a","b","c"};
           * 
           * becomes
           * 
           * String[] myArray = ["a", "b", "c"]
           * 
           * ---
           * 
           * To convert node (t) and surrounding nodes into the right structure for List Constructor
           * 
           * (a) java/EXPR
           *  |
           *  +- (b) java/new
           *      |
           *      + (t) java/ARRAY_INIT
           *    
           *  becomes
           *  
           * (a) groovy/LIST_CONSTRUCTOR (via ARRAY_INIT as temporary marker type)
           *  |
           *  +- (t) groovy/ELIST
           *  
           *  * note: node (b) is thrown away...
           * 
      */ private void visitJavaArrayInit(GroovySourceAST t) { // given that we might have a grandParent... if (stack.size() > 2) { GroovySourceAST grandParent = getGrandParentNode(); if (grandParent.getType() == JavaTokenTypes.EXPR) { grandParent.setType(JavaTokenTypes.ARRAY_INIT); //set type as indicator for Java2GroovyConvertor to turn into LIST_CONSTRUCTOR grandParent.setFirstChild(t); t.setType(JavaTokenTypes.ELIST); } } } /** To swap two children of node t... * *
      	 *   (t)
      	 *    |
      	 *    |
      	 *   (a) -- (b)
      	 * 
      	 * t.down = firstNode
      	 * a.right = b
      	 * b.right = null
      	 *
      * becomes *
      	 *   (t)
      	 *    |
      	 *    |
      	 *   (b) -- (a)
      	 *   
      	 * t.down = b
      	 * a.right = null
      	 * b.right = a
      	 *
      * * todo - build API of basic tree mutations like this method. */ public void swapTwoChildren(GroovySourceAST t) { // this swaps the two child nodes, see javadoc above for explanation of implementation GroovySourceAST a = (GroovySourceAST) t.getFirstChild(); GroovySourceAST b = (GroovySourceAST) a.getNextSibling(); t.setFirstChild(b); a.setNextSibling(null); b.setNextSibling(a); } public void push(GroovySourceAST t) { stack.push(t); } public GroovySourceAST pop() { if (!stack.empty()) { return (GroovySourceAST) stack.pop(); } return null; } private GroovySourceAST getParentNode() { Object currentNode = stack.pop(); Object parentNode = stack.peek(); stack.push(currentNode); return (GroovySourceAST) parentNode; } private GroovySourceAST getGrandParentNode() { Object currentNode = stack.pop(); Object parentNode = stack.pop(); Object grandParentNode = stack.peek(); stack.push(parentNode); stack.push(currentNode); return (GroovySourceAST) grandParentNode; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/java.g0000644001501200150120000016203011627206700023150 0ustar miguelmiguel// Note: Please don't use physical tabs. Logical tabs for indent are width 4. header { package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.*; import org.codehaus.groovy.antlr.parser.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; } /** Java 1.5 Recognizer * * Run 'java Main [-showtree] directory-full-of-java-files' * * [The -showtree option pops up a Swing frame that shows * the AST constructed from the parser.] * * Run 'java Main ' * * Contributing authors: * Jeremy Rayner groovy@ross-rayner.com * John Mitchell johnm@non.net * Terence Parr parrt@magelang.com * John Lilley jlilley@empathy.com * Scott Stanchfield thetick@magelang.com * Markus Mohnen mohnen@informatik.rwth-aachen.de * Peter Williams pete.williams@sun.com * Allan Jacobs Allan.Jacobs@eng.sun.com * Steve Messick messick@redhills.com * John Pybus john@pybus.org * * Version 1.00 December 9, 1997 -- initial release * Version 1.01 December 10, 1997 * fixed bug in octal def (0..7 not 0..8) * Version 1.10 August 1998 (parrt) * added tree construction * fixed definition of WS,comments for mac,pc,unix newlines * added unary plus * Version 1.11 (Nov 20, 1998) * Added "shutup" option to turn off last ambig warning. * Fixed inner class def to allow named class defs as statements * synchronized requires compound not simple statement * add [] after builtInType DOT class in primaryExpression * "const" is reserved but not valid..removed from modifiers * Version 1.12 (Feb 2, 1999) * Changed LITERAL_xxx to xxx in tree grammar. * Updated java.g to use tokens {...} now for 2.6.0 (new feature). * * Version 1.13 (Apr 23, 1999) * Didn't have (stat)? for else clause in tree parser. * Didn't gen ASTs for interface extends. Updated tree parser too. * Updated to 2.6.0. * Version 1.14 (Jun 20, 1999) * Allowed final/abstract on local classes. * Removed local interfaces from methods * Put instanceof precedence where it belongs...in relationalExpr * It also had expr not type as arg; fixed it. * Missing ! on SEMI in classBlock * fixed: (expr) + "string" was parsed incorrectly (+ as unary plus). * fixed: didn't like Object[].class in parser or tree parser * Version 1.15 (Jun 26, 1999) * Screwed up rule with instanceof in it. :( Fixed. * Tree parser didn't like (expr).something; fixed. * Allowed multiple inheritance in tree grammar. oops. * Version 1.16 (August 22, 1999) * Extending an interface built a wacky tree: had extra EXTENDS. * Tree grammar didn't allow multiple superinterfaces. * Tree grammar didn't allow empty var initializer: {} * Version 1.17 (October 12, 1999) * ESC lexer rule allowed 399 max not 377 max. * java.tree.g didn't handle the expression of synchronized * statements. * Version 1.18 (August 12, 2001) * Terence updated to Java 2 Version 1.3 by * observing/combining work of Allan Jacobs and Steve * Messick. Handles 1.3 src. Summary: * o primary didn't include boolean.class kind of thing * o constructor calls parsed explicitly now: * see explicitConstructorInvocation * o add strictfp modifier * o missing objBlock after new expression in tree grammar * o merged local class definition alternatives, moved after declaration * o fixed problem with ClassName.super.field * o reordered some alternatives to make things more efficient * o long and double constants were not differentiated from int/float * o whitespace rule was inefficient: matched only one char * o add an examples directory with some nasty 1.3 cases * o made Main.java use buffered IO and a Reader for Unicode support * o supports UNICODE? * Using Unicode charVocabulay makes code file big, but only * in the bitsets at the end. I need to make ANTLR generate * unicode bitsets more efficiently. * Version 1.19 (April 25, 2002) * Terence added in nice fixes by John Pybus concerning floating * constants and problems with super() calls. John did a nice * reorg of the primary/postfix expression stuff to read better * and makes f.g.super() parse properly (it was METHOD_CALL not * a SUPER_CTOR_CALL). Also: * * o "finally" clause was a root...made it a child of "try" * o Added stuff for asserts too for Java 1.4, but *commented out* * as it is not backward compatible. * * Version 1.20 (October 27, 2002) * * Terence ended up reorging John Pybus' stuff to * remove some nondeterminisms and some syntactic predicates. * Note that the grammar is stricter now; e.g., this(...) must * be the first statement. * * Trinary ?: operator wasn't working as array name: * (isBig ? bigDigits : digits)[i]; * * Checked parser/tree parser on source for * Resin-2.0.5, jive-2.1.1, jdk 1.3.1, Lucene, antlr 2.7.2a4, * and the 110k-line jGuru server source. * * Version 1.21 (October 17, 2003) * Fixed lots of problems including: * Ray Waldin: add typeDefinition to interfaceBlock in java.tree.g * He found a problem/fix with floating point that start with 0 * Ray also fixed problem that (int.class) was not recognized. * Thorsten van Ellen noticed that \n are allowed incorrectly in strings. * TJP fixed CHAR_LITERAL analogously. * * Version 1.21.2 (March, 2003) * Changes by Matt Quail to support generics (as per JDK1.5/JSR14) * Notes: * o We only allow the "extends" keyword and not the "implements" * keyword, since thats what JSR14 seems to imply. * o Thanks to Monty Zukowski for his help on the antlr-interest * mail list. * o Thanks to Alan Eliasen for testing the grammar over his * Fink source base * * Version 1.22 (July, 2004) * Changes by Michael Studman to support Java 1.5 language extensions * Notes: * o Added support for annotations types * o Finished off Matt Quail's generics enhancements to support bound type arguments * o Added support for new for statement syntax * o Added support for static import syntax * o Added support for enum types * o Tested against JDK 1.5 source base and source base of jdigraph project * o Thanks to Matt Quail for doing the hard part by doing most of the generics work * * Version 1.22.1 (July 28, 2004) * Bug/omission fixes for Java 1.5 language support * o Fixed tree structure bug with classOrInterface - thanks to Pieter Vangorpto for * spotting this * o Fixed bug where incorrect handling of SR and BSR tokens would cause type * parameters to be recognised as type arguments. * o Enabled type parameters on constructors, annotations on enum constants * and package definitions * o Fixed problems when parsing if ((char.class.equals(c))) {} - solution by Matt Quail at Cenqua * * Version 1.22.2 (July 28, 2004) * Slight refactoring of Java 1.5 language support * o Refactored for/"foreach" productions so that original literal "for" literal * is still used but the for sub-clauses vary by token type * o Fixed bug where type parameter was not included in generic constructor's branch of AST * * Version 1.22.3 (August 26, 2004) * Bug fixes as identified by Michael Stahl; clean up of tabs/spaces * and other refactorings * o Fixed typeParameters omission in identPrimary and newStatement * o Replaced GT reconcilliation code with simple semantic predicate * o Adapted enum/assert keyword checking support from Michael Stahl's java15 grammar * o Refactored typeDefinition production and field productions to reduce duplication * * Version 1.22.4 (October 21, 2004) * Small bux fixes * o Added typeArguments to explicitConstructorInvocation, e.g. new MyParameterised() * o Added typeArguments to postfixExpression productions for anonymous inner class super * constructor invocation, e.g. new Outer().super() * o Fixed bug in array declarations identified by Geoff Roy * * Version 1.22.4.j.1 * Changes by Jeremy Rayner to support java2groovy tool * o I have taken java.g for Java1.5 from Michael Studman (1.22.4) * and have made some changes to enable use by java2groovy tool (Jan 2007) * * This grammar is in the PUBLIC DOMAIN */ class JavaRecognizer extends Parser; options { k = 2; // two token lookahead exportVocab=Java; // Call its vocabulary "Java" codeGenMakeSwitchThreshold = 2; // Some optimizations codeGenBitsetTestThreshold = 3; defaultErrorHandler = false; // Don't generate parser error handlers buildAST = true; } tokens { BLOCK; MODIFIERS; OBJBLOCK; SLIST; METHOD_DEF; VARIABLE_DEF; INSTANCE_INIT; STATIC_INIT; TYPE; CLASS_DEF; INTERFACE_DEF; PACKAGE_DEF; ARRAY_DECLARATOR; EXTENDS_CLAUSE; IMPLEMENTS_CLAUSE; PARAMETERS; PARAMETER_DEF; LABELED_STAT; TYPECAST; INDEX_OP; POST_INC; POST_DEC; METHOD_CALL; EXPR; ARRAY_INIT; IMPORT; UNARY_MINUS; UNARY_PLUS; CASE_GROUP; ELIST; FOR_INIT; FOR_CONDITION; FOR_ITERATOR; EMPTY_STAT; FINAL="final"; ABSTRACT="abstract"; STRICTFP="strictfp"; SUPER_CTOR_CALL; CTOR_CALL; VARIABLE_PARAMETER_DEF; STATIC_IMPORT; ENUM_DEF; ENUM_CONSTANT_DEF; FOR_EACH_CLAUSE; ANNOTATION_DEF; ANNOTATIONS; ANNOTATION; ANNOTATION_MEMBER_VALUE_PAIR; ANNOTATION_FIELD_DEF; ANNOTATION_ARRAY_INIT; TYPE_ARGUMENTS; TYPE_ARGUMENT; TYPE_PARAMETERS; TYPE_PARAMETER; WILDCARD_TYPE; TYPE_UPPER_BOUNDS; TYPE_LOWER_BOUNDS; } { /** This factory is the correct way to wire together a Groovy parser and lexer. */ public static JavaRecognizer make(JavaLexer lexer) { JavaRecognizer parser = new JavaRecognizer(lexer.plumb()); // TODO: set up a common error-handling control block, to avoid excessive tangle between these guys parser.lexer = lexer; lexer.parser = parser; parser.setASTNodeClass("org.codehaus.groovy.antlr.GroovySourceAST"); return parser; } // Create a scanner that reads from the input stream passed to us... public static JavaRecognizer make(InputStream in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(Reader in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(InputBuffer in) { return make(new JavaLexer(in)); } public static JavaRecognizer make(LexerSharedInputState in) { return make(new JavaLexer(in)); } private static GroovySourceAST dummyVariableToforceClassLoaderToFindASTClass = new GroovySourceAST(); JavaLexer lexer; public JavaLexer getLexer() { return lexer; } public void setFilename(String f) { super.setFilename(f); lexer.setFilename(f); } private SourceBuffer sourceBuffer; public void setSourceBuffer(SourceBuffer sourceBuffer) { this.sourceBuffer = sourceBuffer; } /** Create an AST node with the token type and text passed in, but * with the same background information as another supplied Token (e.g. line numbers) * to be used in place of antlr tree construction syntax, * i.e. #[TOKEN,"text"] becomes create(TOKEN,"text",anotherToken) * * todo - change antlr.ASTFactory to do this instead... */ public AST create(int type, String txt, Token first, Token last) { AST t = astFactory.create(type,txt); if ( t != null && first != null) { // first copy details from first token t.initialize(first); // then ensure that type and txt are specific to this new node t.initialize(type,txt); } if ((t instanceof GroovySourceAST) && last != null) { GroovySourceAST node = (GroovySourceAST)t; node.setLast(last); // This is a good point to call node.setSnippet(), // but it bulks up the AST too much for production code. } return t; } /** * Counts the number of LT seen in the typeArguments production. * It is used in semantic predicates to ensure we have seen * enough closing '>' characters; which actually may have been * either GT, SR or BSR tokens. */ private int ltCounter = 0; } // Compilation Unit: In Java, this is a single file. This is the start // rule for this parser compilationUnit : // A compilation unit starts with an optional package definition ( (annotations "package")=> packageDefinition | /* nothing */ ) // Next we have a series of zero or more import statements ( importDefinition )* // Wrapping things up with any number of class or interface // definitions ( typeDefinition )* EOF! ; // Package statement: optional annotations followed by "package" then the package identifier. packageDefinition options {defaultErrorHandler = true;} // let ANTLR handle errors : annotations p:"package"^ {#p.setType(PACKAGE_DEF);} identifier SEMI! ; // Import statement: import followed by a package or class name importDefinition options {defaultErrorHandler = true;} { boolean isStatic = false; } : i:"import"^ {#i.setType(IMPORT);} ( "static"! {#i.setType(STATIC_IMPORT);} )? identifierStar SEMI! ; // A type definition is either a class, interface, enum or annotation with possible additional semis. typeDefinition options {defaultErrorHandler = true;} : m:modifiers! typeDefinitionInternal[#m] | SEMI! ; // Protected type definitions production for reuse in other productions protected typeDefinitionInternal[AST mods] : classDefinition[#mods] // inner class | interfaceDefinition[#mods] // inner interface | enumDefinition[#mods] // inner enum | annotationDefinition[#mods] // inner annotation ; // A declaration is the creation of a reference or primitive-type variable // Create a separate Type/Var tree for each var in the var list. declaration! : m:modifiers t:typeSpec[false] v:variableDefinitions[#m,#t] {#declaration = #v;} ; // A type specification is a type name with possible brackets afterwards // (which would make it an array type). typeSpec[boolean addImagNode] : classTypeSpec[addImagNode] | builtInTypeSpec[addImagNode] ; // A class type specification is a class type with either: // - possible brackets afterwards // (which would make it an array type). // - generic type arguments after classTypeSpec[boolean addImagNode] {Token first = LT(1);} : classOrInterfaceType[false] (options{greedy=true;}: // match as many as possible lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK! )* { if ( addImagNode ) { #classTypeSpec = #(create(TYPE,"TYPE",first,LT(1)), #classTypeSpec); } } ; // A non-built in type name, with possible type parameters classOrInterfaceType[boolean addImagNode] {Token first = LT(1);} : IDENT^ (typeArguments)? (options{greedy=true;}: // match as many as possible DOT^ IDENT (typeArguments)? )* { if ( addImagNode ) { #classOrInterfaceType = #(create(TYPE,"TYPE",first,LT(1)), #classOrInterfaceType); } } ; // A specialised form of typeSpec where built in types must be arrays typeArgumentSpec : classTypeSpec[true] | builtInTypeArraySpec[true] ; // A generic type argument is a class type, a possibly bounded wildcard type or a built-in type array typeArgument {Token first = LT(1);} : ( typeArgumentSpec | wildcardType ) {#typeArgument = #(create(TYPE_ARGUMENT,"TYPE_ARGUMENT",first,LT(1)), #typeArgument);} ; // Wildcard type indicating all types (with possible constraint) wildcardType : q:QUESTION^ {#q.setType(WILDCARD_TYPE);} (("extends" | "super")=> typeArgumentBounds)? ; // Type arguments to a class or interface type typeArguments {int currentLtLevel = 0; Token first = LT(1);} : {currentLtLevel = ltCounter;} LT! {ltCounter++;} typeArgument (options{greedy=true;}: // match as many as possible {inputState.guessing !=0 || ltCounter == currentLtLevel + 1}? COMMA! typeArgument )* ( // turn warning off since Antlr generates the right code, // plus we have our semantic predicate below options{generateAmbigWarnings=false;}: typeArgumentsOrParametersEnd )? // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {(currentLtLevel != 0) || ltCounter == currentLtLevel}? {#typeArguments = #(create(TYPE_ARGUMENTS,"TYPE_ARGUMENTS",first,LT(1)), #typeArguments);} ; // this gobbles up *some* amount of '>' characters, and counts how many // it gobbled. protected typeArgumentsOrParametersEnd : GT! {ltCounter-=1;} | SR! {ltCounter-=2;} | BSR! {ltCounter-=3;} ; // Restriction on wildcard types based on super class or derrived class typeArgumentBounds {boolean isUpperBounds = false; Token first = LT(1);} : ( "extends"! {isUpperBounds=true;} | "super"! ) classOrInterfaceType[false] { if (isUpperBounds) { #typeArgumentBounds = #(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1)), #typeArgumentBounds); } else { #typeArgumentBounds = #(create(TYPE_LOWER_BOUNDS,"TYPE_LOWER_BOUNDS",first,LT(1)), #typeArgumentBounds); } } ; // A builtin type array specification is a builtin type with brackets afterwards builtInTypeArraySpec[boolean addImagNode] {Token first = LT(1);} : builtInType (options{greedy=true;}: // match as many as possible lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK! )+ { if ( addImagNode ) { #builtInTypeArraySpec = #(create(TYPE,"TYPE",first,LT(1)), #builtInTypeArraySpec); } } ; // A builtin type specification is a builtin type with possible brackets // afterwards (which would make it an array type). builtInTypeSpec[boolean addImagNode] {Token first = LT(1);} : builtInType (options{greedy=true;}: // match as many as possible lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK! )* { if ( addImagNode ) { #builtInTypeSpec = #(create(TYPE,"TYPE",first,LT(1)), #builtInTypeSpec); } } ; // A type name. which is either a (possibly qualified and parameterized) // class name or a primitive (builtin) type type : classOrInterfaceType[false] | builtInType ; // The primitive types. builtInType : "void" | "boolean" | "byte" | "char" | "short" | "int" | "float" | "long" | "double" ; // A (possibly-qualified) java identifier. We start with the first IDENT // and expand its name by adding dots and following IDENTS identifier : IDENT ( DOT^ IDENT )* ; identifierStar : IDENT ( DOT^ IDENT )* ( DOT^ STAR )? ; // A list of zero or more modifiers. We could have used (modifier)* in // place of a call to modifiers, but I thought it was a good idea to keep // this rule separate so they can easily be collected in a Vector if // someone so desires modifiers {Token first = LT(1);} : ( //hush warnings since the semantic check for "@interface" solves the non-determinism options{generateAmbigWarnings=false;}: modifier | //Semantic check that we aren't matching @interface as this is not an annotation //A nicer way to do this would be nice {LA(1)==AT && !LT(2).getText().equals("interface")}? annotation )* {#modifiers = #(create(MODIFIERS, "MODIFIERS",first,LT(1)), #modifiers);} ; // modifiers for Java classes, interfaces, class/instance vars and methods modifier : "private" | "public" | "protected" | "static" | "transient" | "final" | "abstract" | "native" | "threadsafe" | "synchronized" | "volatile" | "strictfp" ; annotation! {Token first = LT(1);} : AT! i:identifier ( LPAREN! ( args:annotationArguments )? RPAREN! )? {#annotation = #(create(ANNOTATION,"ANNOTATION",first,LT(1)), i, args);} ; annotations {Token first = LT(1);} : (annotation)* {#annotations = #([ANNOTATIONS, "ANNOTATIONS"], #annotations);} ; annotationArguments : annotationMemberValueInitializer | anntotationMemberValuePairs ; anntotationMemberValuePairs : annotationMemberValuePair ( COMMA! annotationMemberValuePair )* ; annotationMemberValuePair! {Token first = LT(1);} : i:IDENT ASSIGN! v:annotationMemberValueInitializer {#annotationMemberValuePair = #(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",first,LT(1)), i, v);} ; annotationMemberValueInitializer : conditionalExpression | annotation | annotationMemberArrayInitializer ; // This is an initializer used to set up an annotation member array. annotationMemberArrayInitializer : lc:LCURLY^ {#lc.setType(ANNOTATION_ARRAY_INIT);} ( annotationMemberArrayValueInitializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA! annotationMemberArrayValueInitializer )* (COMMA!)? )? RCURLY! ; // The two things that can initialize an annotation array element are a conditional expression // and an annotation (nested annotation array initialisers are not valid) annotationMemberArrayValueInitializer : conditionalExpression | annotation ; superClassClause! {Token first = LT(1);} : ( "extends" c:classOrInterfaceType[false] )? {#superClassClause = #(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1)),c);} ; // Definition of a Java class classDefinition![AST modifiers] {Token first = LT(1);} : "class" IDENT // it _might_ have type paramaters (tp:typeParameters)? // it _might_ have a superclass... sc:superClassClause // it might implement some interfaces... ic:implementsClause // now parse the body of the class cb:classBlock {#classDefinition = #(create(CLASS_DEF,"CLASS_DEF",first,LT(1)), modifiers,IDENT,tp,sc,ic,cb);} ; // Definition of a Java Interface interfaceDefinition![AST modifiers] {Token first = LT(1);} : "interface" IDENT // it _might_ have type paramaters (tp:typeParameters)? // it might extend some other interfaces ie:interfaceExtends // now parse the body of the interface (looks like a class...) ib:interfaceBlock {#interfaceDefinition = #(create(INTERFACE_DEF,"INTERFACE_DEF",first,LT(1)), modifiers,IDENT,tp,ie,ib);} ; enumDefinition![AST modifiers] {Token first = LT(1);} : "enum" IDENT // it might implement some interfaces... ic:implementsClause // now parse the body of the enum eb:enumBlock {#enumDefinition = #(create(ENUM_DEF,"ENUM_DEF",first,LT(1)), modifiers,IDENT,ic,eb);} ; annotationDefinition![AST modifiers] {Token first = LT(1);} : AT "interface" IDENT // now parse the body of the annotation ab:annotationBlock {#annotationDefinition = #(create(ANNOTATION_DEF,"ANNOTATION_DEF",first,LT(1)), modifiers,IDENT,ab);} ; typeParameters {int currentLtLevel = 0; Token first = LT(1);} : {currentLtLevel = ltCounter;} LT! {ltCounter++;} typeParameter (COMMA! typeParameter)* (typeArgumentsOrParametersEnd)? // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {(currentLtLevel != 0) || ltCounter == currentLtLevel}? {#typeParameters = #(create(TYPE_PARAMETERS,"TYPE_PARAMETERS",first,LT(1)), #typeParameters);} ; typeParameter {Token first = LT(1);} : // I'm pretty sure Antlr generates the right thing here: (id:IDENT) ( options{generateAmbigWarnings=false;}: typeParameterBounds )? {#typeParameter = #(create(TYPE_PARAMETER,"TYPE_PARAMETER",first,LT(1)), #typeParameter);} ; typeParameterBounds {Token first = LT(1);} : "extends"! classOrInterfaceType[false] (BAND! classOrInterfaceType[false])* {#typeParameterBounds = #(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1)), #typeParameterBounds);} ; // This is the body of a class. You can have classFields and extra semicolons. classBlock : LCURLY! ( classField | SEMI! )* RCURLY! {#classBlock = #([OBJBLOCK, "OBJBLOCK"], #classBlock);} ; // This is the body of an interface. You can have interfaceField and extra semicolons. interfaceBlock : LCURLY! ( interfaceField | SEMI! )* RCURLY! {#interfaceBlock = #([OBJBLOCK, "OBJBLOCK"], #interfaceBlock);} ; // This is the body of an annotation. You can have annotation fields and extra semicolons, // That's about it (until you see what an annoation field is...) annotationBlock : LCURLY! ( annotationField | SEMI! )* RCURLY! {#annotationBlock = #([OBJBLOCK, "OBJBLOCK"], #annotationBlock);} ; // This is the body of an enum. You can have zero or more enum constants // followed by any number of fields like a regular class enumBlock : LCURLY! ( enumConstant ( options{greedy=true;}: COMMA! enumConstant )* ( COMMA! )? )? ( SEMI! ( classField | SEMI! )* )? RCURLY! {#enumBlock = #([OBJBLOCK, "OBJBLOCK"], #enumBlock);} ; // An annotation field annotationField! {Token first = LT(1);} : mods:modifiers ( td:typeDefinitionInternal[#mods] {#annotationField = #td;} | t:typeSpec[false] // annotation field ( i:IDENT // the name of the field LPAREN! RPAREN! rt:declaratorBrackets[#t] ( "default" amvi:annotationMemberValueInitializer )? SEMI {#annotationField = #(create(ANNOTATION_FIELD_DEF,"ANNOTATION_FIELD_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),rt), i,amvi );} | v:variableDefinitions[#mods,#t] SEMI // variable {#annotationField = #v;} ) ) ; //An enum constant may have optional parameters and may have a //a class body enumConstant! : an:annotations i:IDENT ( LPAREN! a:argList RPAREN! )? ( b:enumConstantBlock )? {#enumConstant = #([ENUM_CONSTANT_DEF, "ENUM_CONSTANT_DEF"], an, i, a, b);} ; //The class-like body of an enum constant enumConstantBlock : LCURLY! ( enumConstantField | SEMI! )* RCURLY! {#enumConstantBlock = #([OBJBLOCK, "OBJBLOCK"], #enumConstantBlock);} ; //An enum constant field is just like a class field but without //the posibility of a constructor definition or a static initializer enumConstantField! {Token first = LT(1);} : mods:modifiers ( td:typeDefinitionInternal[#mods] {#enumConstantField = #td;} | // A generic method has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you wanted. (tp:typeParameters)? t:typeSpec[false] // method or variable declaration(s) ( IDENT // the name of the method // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList RPAREN! rt:declaratorBrackets[#t] // get the list of exceptions that this method is // declared to throw (tc:throwsClause)? ( s2:compoundStatement | SEMI ) {#enumConstantField = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, tp, #(create(TYPE,"TYPE",first,LT(1)),rt), IDENT, param, tc, s2);} | v:variableDefinitions[#mods,#t] SEMI {#enumConstantField = #v;} ) ) // "{ ... }" instance initializer | s4:compoundStatement {#enumConstantField = #(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1)), s4);} ; // An interface can extend several other interfaces... interfaceExtends {Token first = LT(1);} : ( e:"extends"! classOrInterfaceType[false] ( COMMA! classOrInterfaceType[false] )* )? {#interfaceExtends = #(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1)), #interfaceExtends);} ; // A class can implement several interfaces... implementsClause {Token first = LT(1);} : ( i:"implements"! classOrInterfaceType[false] ( COMMA! classOrInterfaceType[false] )* )? {#implementsClause = #(create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE",first,LT(1)), #implementsClause);} ; // Now the various things that can be defined inside a class classField! {Token first = LT(1);} : // method, constructor, or variable declaration mods:modifiers ( td:typeDefinitionInternal[#mods] {#classField = #td;} | (tp:typeParameters)? ( h:ctorHead s:constructorBody // constructor // just treat CTOR_DEF like METHOD_DEF for java2groovy {#classField = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, tp, h, s);} | // A generic method/ctor has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you wanted. t:typeSpec[false] // method or variable declaration(s) ( IDENT // the name of the method // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList RPAREN! rt:declaratorBrackets[#t] // get the list of exceptions that this method is // declared to throw (tc:throwsClause)? ( s2:compoundStatement | SEMI ) {#classField = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, tp, #(create(TYPE,"TYPE",first,LT(1)),rt), IDENT, param, tc, s2);} | v:variableDefinitions[#mods,#t] SEMI {#classField = #v;} ) ) ) // "static { ... }" class initializer | "static" s3:compoundStatement {#classField = #(create(STATIC_INIT,"STATIC_INIT",first,LT(1)), s3);} // "{ ... }" instance initializer | s4:compoundStatement {#classField = #(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1)), s4);} ; // Now the various things that can be defined inside a interface interfaceField! {Token first = LT(1);} : // method, constructor, or variable declaration mods:modifiers ( td:typeDefinitionInternal[#mods] {#interfaceField = #td;} | (tp:typeParameters)? // A generic method has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you want a more strict // grammar. t:typeSpec[false] // method or variable declaration(s) ( IDENT // the name of the method // parse the formal parameter declarations. LPAREN! param:parameterDeclarationList RPAREN! rt:declaratorBrackets[#t] // get the list of exceptions that this method is // declared to throw (tc:throwsClause)? SEMI {#interfaceField = #(create(METHOD_DEF,"METHOD_DEF",first,LT(1)), mods, tp, #(create(TYPE,"TYPE",first,LT(1)),rt), IDENT, param, tc);} | v:variableDefinitions[#mods,#t] SEMI {#interfaceField = #v;} ) ) ; constructorBody : lc:LCURLY^ {#lc.setType(SLIST);} ( options { greedy=true; } : explicitConstructorInvocation)? (statement)* RCURLY! ; /** Catch obvious constructor calls, but not the expr.super(...) calls */ explicitConstructorInvocation : (typeArguments)? ( "this"! lp1:LPAREN^ argList RPAREN! SEMI! {#lp1.setType(CTOR_CALL);} | "super"! lp2:LPAREN^ argList RPAREN! SEMI! {#lp2.setType(SUPER_CTOR_CALL);} ) ; variableDefinitions[AST mods, AST t] : variableDeclarator[getASTFactory().dupTree(mods), getASTFactory().dupTree(t)] ( COMMA! variableDeclarator[getASTFactory().dupTree(mods), getASTFactory().dupTree(t)] )* ; /** Declaration of a variable. This can be a class/instance variable, * or a local variable in a method * It can also include possible initialization. */ variableDeclarator![AST mods, AST t] { Token first = LT(1);} : id:IDENT d:declaratorBrackets[t] v:varInitializer {#variableDeclarator = #(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1)), mods, #(create(TYPE,"TYPE",first,LT(1)),d), id, v);} ; declaratorBrackets[AST typ] : {#declaratorBrackets=typ;} (lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK!)* ; varInitializer : ( ASSIGN^ initializer )? ; // This is an initializer used to set up an array. arrayInitializer : lc:LCURLY^ {#lc.setType(ARRAY_INIT);} ( initializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA! initializer )* (COMMA!)? )? RCURLY! ; // The two "things" that can initialize an array element are an expression // and another (nested) array initializer. initializer : expression | arrayInitializer ; // This is the header of a method. It includes the name and parameters // for the method. // This also watches for a list of exception classes in a "throws" clause. ctorHead : IDENT // the name of the method // parse the formal parameter declarations. LPAREN! parameterDeclarationList RPAREN! // get the list of exceptions that this method is declared to throw (throwsClause)? ; // This is a list of exception classes that the method is declared to throw throwsClause : "throws"^ identifier ( COMMA! identifier )* ; // A list of formal parameters // Zero or more parameters // If a parameter is variable length (e.g. String... myArg) it is the right-most parameter parameterDeclarationList {Token first = LT(1);} // The semantic check in ( .... )* block is flagged as superfluous, and seems superfluous but // is the only way I could make this work. If my understanding is correct this is a known bug : ( ( parameterDeclaration )=> parameterDeclaration ( options {warnWhenFollowAmbig=false;} : ( COMMA! parameterDeclaration ) => COMMA! parameterDeclaration )* ( COMMA! variableLengthParameterDeclaration )? | variableLengthParameterDeclaration )? {#parameterDeclarationList = #(create(PARAMETERS,"PARAMETERS",first,LT(1)), #parameterDeclarationList);} ; // A formal parameter. parameterDeclaration! {Token first = LT(1);} : pm:parameterModifier t:typeSpec[false] id:IDENT pd:declaratorBrackets[#t] {#parameterDeclaration = #(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1)), pm, #(create(TYPE,"TYPE",first,LT(1)),pd), id);} ; variableLengthParameterDeclaration! {Token first = LT(1);} : pm:parameterModifier t:typeSpec[false] TRIPLE_DOT! id:IDENT pd:declaratorBrackets[#t] {#variableLengthParameterDeclaration = #(create(VARIABLE_PARAMETER_DEF,"VARIABLE_PARAMETER_DEF",first,LT(1)), pm, #(create(TYPE,"TYPE",first,LT(1)),pd), id);} ; parameterModifier {Token first = LT(1);} //final can appear amongst annotations in any order - greedily consume any preceding //annotations to shut nond-eterminism warnings off : (options{greedy=true;} : annotation)* (f:"final")? (annotation)* {#parameterModifier = #(create(MODIFIERS,"MODIFIERS",first,LT(1)), #parameterModifier);} ; // Compound statement. This is used in many contexts: // Inside a class definition prefixed with "static": // it is a class initializer // Inside a class definition without "static": // it is an instance initializer // As the body of a method // As a completely indepdent braced block of code inside a method // it starts a new scope for variable definitions compoundStatement : lc:LCURLY^ {#lc.setType(SLIST);} // include the (possibly-empty) list of statements (statement)* RCURLY! ; statement // A list of statements in curly braces -- start a new scope! : compoundStatement // declarations are ambiguous with "ID DOT" relative to expression // statements. Must backtrack to be sure. Could use a semantic // predicate to test symbol table to see what the type was coming // up, but that's pretty hard without a symbol table ;) | (declaration)=> declaration SEMI! // An expression statement. This could be a method call, // assignment statement, or any other expression evaluated for // side-effects. | expression SEMI! //TODO: what abour interfaces, enums and annotations // class definition | m:modifiers! classDefinition[#m] // Attach a label to the front of a statement | IDENT c:COLON^ {#c.setType(LABELED_STAT);} statement // If-else statement | "if"^ LPAREN! expression RPAREN! statement ( // CONFLICT: the old "dangling-else" problem... // ANTLR generates proper code matching // as soon as possible. Hush warning. options { warnWhenFollowAmbig = false; } : "else"! statement )? // For statement | forStatement // While statement | "while"^ LPAREN! expression RPAREN! statement // do-while statement | "do"^ statement "while"! LPAREN! expression RPAREN! SEMI! // get out of a loop (or switch) | "break"^ (IDENT)? SEMI! // do next iteration of a loop | "continue"^ (IDENT)? SEMI! // Return an expression | "return"^ (expression)? SEMI! // switch/case statement | "switch"^ LPAREN! expression RPAREN! LCURLY! ( casesGroup )* RCURLY! // exception try-catch block | tryBlock // throw an exception | "throw"^ expression SEMI! // synchronize a statement | "synchronized"^ LPAREN! expression RPAREN! compoundStatement // asserts (uncomment if you want 1.4 compatibility) | "assert"^ expression ( COLON! expression )? SEMI! // empty statement | s:SEMI {#s.setType(EMPTY_STAT);} ; forStatement : f:"for"^ LPAREN! ( (forInit SEMI)=>traditionalForClause | forEachClause ) RPAREN! statement // statement to loop over ; traditionalForClause : forInit SEMI! // initializer forCond SEMI! // condition test forIter // updater ; forEachClause {Token first = LT(1);} : p:parameterDeclaration COLON! expression {#forEachClause = #(create(FOR_EACH_CLAUSE,"FOR_EACH_CLAUSE",first,LT(1)), #forEachClause);} ; casesGroup : ( // CONFLICT: to which case group do the statements bind? // ANTLR generates proper code: it groups the // many "case"/"default" labels together then // follows them with the statements options { greedy = true; } : aCase )+ caseSList {#casesGroup = #([CASE_GROUP, "CASE_GROUP"], #casesGroup);} ; aCase : ("case"^ expression | "default") COLON! ; caseSList {Token first = LT(1);} : (statement)* {#caseSList = #(create(SLIST,"SLIST",first,LT(1)),#caseSList);} ; // The initializer for a for loop forInit {Token first = LT(1);} // if it looks like a declaration, it is : ((declaration)=> declaration // otherwise it could be an expression list... | expressionList )? {#forInit = #(create(FOR_INIT,"FOR_INIT",first,LT(1)),#forInit);} ; forCond {Token first = LT(1);} : (expression)? {#forCond = #(create(FOR_CONDITION,"FOR_CONDITION",first,LT(1)),#forCond);} ; forIter {Token first = LT(1);} : (expressionList)? {#forIter = #(create(FOR_ITERATOR,"FOR_ITERATOR",first,LT(1)),#forIter);} ; // an exception handler try/catch block tryBlock : "try"^ compoundStatement (handler)* ( finallyClause )? ; finallyClause : "finally"^ compoundStatement ; // an exception handler handler : "catch"^ LPAREN! parameterDeclaration RPAREN! compoundStatement ; // expressions // Note that most of these expressions follow the pattern // thisLevelExpression : // nextHigherPrecedenceExpression // (OPERATOR nextHigherPrecedenceExpression)* // which is a standard recursive definition for a parsing an expression. // The operators in java have the following precedences: // lowest (13) = *= /= %= += -= <<= >>= >>>= &= ^= |= // (12) ?: // (11) || // (10) && // ( 9) | // ( 8) ^ // ( 7) & // ( 6) == != // ( 5) < <= > >= // ( 4) << >> // ( 3) +(binary) -(binary) // ( 2) * / % // ( 1) ++ -- +(unary) -(unary) ~ ! (type) // [] () (method call) . (dot -- identifier qualification) // new () (explicit parenthesis) // // the last two are not usually on a precedence chart; I put them in // to point out that new has a higher precedence than '.', so you // can validy use // new Frame().show() // // Note that the above precedence levels map to the rules below... // Once you have a precedence chart, writing the appropriate rules as below // is usually very straightfoward // the mother of all expressions expression {Token first = LT(1);} : assignmentExpression {#expression = #(create(EXPR,"EXPR",first,LT(1)),#expression);} ; // This is a list of expressions. expressionList {Token first = LT(1);} : expression (COMMA! expression)* {#expressionList = #(create(ELIST,"ELIST",first,LT(1)), #expressionList);} ; // assignment expression (level 13) assignmentExpression : conditionalExpression ( ( ASSIGN^ | PLUS_ASSIGN^ | MINUS_ASSIGN^ | STAR_ASSIGN^ | DIV_ASSIGN^ | MOD_ASSIGN^ | SR_ASSIGN^ | BSR_ASSIGN^ | SL_ASSIGN^ | BAND_ASSIGN^ | BXOR_ASSIGN^ | BOR_ASSIGN^ ) assignmentExpression )? ; // conditional test (level 12) conditionalExpression : logicalOrExpression ( QUESTION^ assignmentExpression COLON! conditionalExpression )? ; // logical or (||) (level 11) logicalOrExpression : logicalAndExpression (LOR^ logicalAndExpression)* ; // logical and (&&) (level 10) logicalAndExpression : inclusiveOrExpression (LAND^ inclusiveOrExpression)* ; // bitwise or non-short-circuiting or (|) (level 9) inclusiveOrExpression : exclusiveOrExpression (BOR^ exclusiveOrExpression)* ; // exclusive or (^) (level 8) exclusiveOrExpression : andExpression (BXOR^ andExpression)* ; // bitwise or non-short-circuiting and (&) (level 7) andExpression : equalityExpression (BAND^ equalityExpression)* ; // equality/inequality (==/!=) (level 6) equalityExpression : relationalExpression ((NOT_EQUAL^ | EQUAL^) relationalExpression)* ; // boolean relational expressions (level 5) relationalExpression : shiftExpression ( ( ( LT^ | GT^ | LE^ | GE^ ) shiftExpression )* | "instanceof"^ typeSpec[true] ) ; // bit shift expressions (level 4) shiftExpression : additiveExpression ((SL^ | SR^ | BSR^) additiveExpression)* ; // binary addition/subtraction (level 3) additiveExpression : multiplicativeExpression ((PLUS^ | MINUS^) multiplicativeExpression)* ; // multiplication/division/modulo (level 2) multiplicativeExpression : unaryExpression ((STAR^ | DIV^ | MOD^ ) unaryExpression)* ; unaryExpression : INC^ unaryExpression | DEC^ unaryExpression | MINUS^ {#MINUS.setType(UNARY_MINUS);} unaryExpression | PLUS^ {#PLUS.setType(UNARY_PLUS);} unaryExpression | unaryExpressionNotPlusMinus ; unaryExpressionNotPlusMinus : BNOT^ unaryExpression | LNOT^ unaryExpression | ( // subrule allows option to shut off warnings options { // "(int" ambig with postfixExpr due to lack of sequence // info in linear approximate LL(k). It's ok. Shut up. generateAmbigWarnings=false; } : // If typecast is built in type, must be numeric operand // Have to backtrack to see if operator follows (LPAREN builtInTypeSpec[true] RPAREN unaryExpression)=> lpb:LPAREN^ {#lpb.setType(TYPECAST);} builtInTypeSpec[true] RPAREN! unaryExpression // Have to backtrack to see if operator follows. If no operator // follows, it's a typecast. No semantic checking needed to parse. // if it _looks_ like a cast, it _is_ a cast; else it's a "(expr)" | (LPAREN classTypeSpec[true] RPAREN unaryExpressionNotPlusMinus)=> lp:LPAREN^ {#lp.setType(TYPECAST);} classTypeSpec[true] RPAREN! unaryExpressionNotPlusMinus | postfixExpression ) ; // qualified names, array expressions, method invocation, post inc/dec postfixExpression : primaryExpression ( /* options { // the use of postfixExpression in SUPER_CTOR_CALL adds DOT // to the lookahead set, and gives loads of false non-det // warnings. // shut them off. generateAmbigWarnings=false; } : */ //type arguments are only appropriate for a parameterized method/ctor invocations //semantic check may be needed here to ensure that this is the case DOT^ (typeArguments)? ( IDENT ( lp:LPAREN^ {#lp.setType(METHOD_CALL);} argList RPAREN! )? | "super" ( // (new Outer()).super() (create enclosing instance) lp3:LPAREN^ argList RPAREN! {#lp3.setType(SUPER_CTOR_CALL);} | DOT^ (typeArguments)? IDENT ( lps:LPAREN^ {#lps.setType(METHOD_CALL);} argList RPAREN! )? ) ) | DOT^ "this" | DOT^ newExpression | lb:LBRACK^ {#lb.setType(INDEX_OP);} expression RBRACK! )* ( // possibly add on a post-increment or post-decrement. // allows INC/DEC on too much, but semantics can check in:INC^ {#in.setType(POST_INC);} | de:DEC^ {#de.setType(POST_DEC);} )? ; // the basic element of an expression primaryExpression : identPrimary ( options {greedy=true;} : DOT^ "class" )? | constant | "true" | "false" | "null" | newExpression | "this" | "super" | LPAREN! assignmentExpression RPAREN! // look for int.class and int[].class | builtInType ( lbt:LBRACK^ {#lbt.setType(ARRAY_DECLARATOR);} RBRACK! )* DOT^ "class" ; /** Match a, a.b.c refs, a.b.c(...) refs, a.b.c[], a.b.c[].class, * and a.b.c.class refs. Also this(...) and super(...). Match * this or super. */ identPrimary : (ta1:typeArguments!)? IDENT // Syntax for method invocation with type arguments is // foo("blah") ( options { // .ident could match here or in postfixExpression. // We do want to match here. Turn off warning. greedy=true; // This turns the ambiguity warning of the second alternative // off. See below. (The "false" predicate makes it non-issue) warnWhenFollowAmbig=false; } // we have a new nondeterminism because of // typeArguments... only a syntactic predicate will help... // The problem is that this loop here conflicts with // DOT typeArguments "super" in postfixExpression (k=2) // A proper solution would require a lot of refactoring... : (DOT (typeArguments)? IDENT) => DOT^ (ta2:typeArguments!)? IDENT | {false}? // FIXME: this is very ugly but it seems to work... // this will also produce an ANTLR warning! // Unfortunately a syntactic predicate can only select one of // multiple alternatives on the same level, not break out of // an enclosing loop, which is why this ugly hack (a fake // empty alternative with always-false semantic predicate) // is necessary. )* ( options { // ARRAY_DECLARATOR here conflicts with INDEX_OP in // postfixExpression on LBRACK RBRACK. // We want to match [] here, so greedy. This overcomes // limitation of linear approximate lookahead. greedy=true; } : ( lp:LPAREN^ {#lp.setType(METHOD_CALL);} // if the input is valid, only the last IDENT may // have preceding typeArguments... rather hacky, this is... {if (#ta2 != null) astFactory.addASTChild(currentAST, #ta2);} {if (#ta2 == null) astFactory.addASTChild(currentAST, #ta1);} argList RPAREN! ) | ( options {greedy=true;} : lbc:LBRACK^ {#lbc.setType(ARRAY_DECLARATOR);} RBRACK! )+ )? ; /** object instantiation. * Trees are built as illustrated by the following input/tree pairs: * * new T() * * new * | * T -- ELIST * | * arg1 -- arg2 -- .. -- argn * * new int[] * * new * | * int -- ARRAY_DECLARATOR * * new int[] {1,2} * * new * | * int -- ARRAY_DECLARATOR -- ARRAY_INIT * | * EXPR -- EXPR * | | * 1 2 * * new int[3] * new * | * int -- ARRAY_DECLARATOR * | * EXPR * | * 3 * * new int[1][2] * * new * | * int -- ARRAY_DECLARATOR * | * ARRAY_DECLARATOR -- EXPR * | | * EXPR 1 * | * 2 * */ newExpression : "new"^ (typeArguments)? type ( LPAREN! argList RPAREN! (classBlock)? //java 1.1 // Note: This will allow bad constructs like // new int[4][][3] {exp,exp}. // There needs to be a semantic check here... // to make sure: // a) [ expr ] and [ ] are not mixed // b) [ expr ] and an init are not used together | newArrayDeclarator (arrayInitializer)? ) ; argList {Token first = LT(1);} : ( expressionList | /*nothing*/ {#argList = create(ELIST,"ELIST",first,LT(1));} ) ; newArrayDeclarator : ( // CONFLICT: // newExpression is a primaryExpression which can be // followed by an array index reference. This is ok, // as the generated code will stay in this loop as // long as it sees an LBRACK (proper behavior) options { warnWhenFollowAmbig = false; } : lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} (expression)? RBRACK! )+ ; constant : NUM_INT | CHAR_LITERAL | STRING_LITERAL | NUM_FLOAT | NUM_LONG | NUM_DOUBLE ; //---------------------------------------------------------------------------- // The Java scanner //---------------------------------------------------------------------------- class JavaLexer extends Lexer; options { exportVocab=Java; // call the vocabulary "Java" testLiterals=false; // don't automatically test for literals k=4; // four characters of lookahead charVocabulary='\u0003'..'\uFFFF'; // without inlining some bitset tests, couldn't do unicode; // I need to make ANTLR generate smaller bitsets; see // bottom of JavaLexer.java codeGenBitsetTestThreshold=20; } { protected static final int SCS_TYPE = 3, SCS_VAL = 4, SCS_LIT = 8, SCS_LIMIT = 16; protected static final int SCS_SQ_TYPE = 0, SCS_TQ_TYPE = 1, SCS_RE_TYPE = 2; protected int stringCtorState = 0; // hack string and regexp constructor boundaries protected int lastSigTokenType = EOF; // last returned non-whitespace token /** flag for enabling the "assert" keyword */ private boolean assertEnabled = true; /** flag for enabling the "enum" keyword */ private boolean enumEnabled = true; /** flag for including whitespace tokens (for IDE preparsing) */ private boolean whitespaceIncluded = false; /** Enable the "assert" keyword */ public void enableAssert(boolean shouldEnable) { assertEnabled = shouldEnable; } /** Query the "assert" keyword state */ public boolean isAssertEnabled() { return assertEnabled; } /** Enable the "enum" keyword */ public void enableEnum(boolean shouldEnable) { enumEnabled = shouldEnable; } /** Query the "enum" keyword state */ public boolean isEnumEnabled() { return enumEnabled; } /** This is a bit of plumbing which resumes collection of string constructor bodies, * after an embedded expression has been parsed. * Usage: new JavaRecognizer(new JavaLexer(in).plumb()). */ public TokenStream plumb() { return new TokenStream() { public Token nextToken() throws TokenStreamException { if (stringCtorState >= SCS_LIT) { // This goo is modeled upon the ANTLR code for nextToken: int quoteType = (stringCtorState & SCS_TYPE); stringCtorState = 0; // get out of this mode, now resetText(); /* try { switch (quoteType) { case SCS_SQ_TYPE: //todo: suitable replacement??? mSTRING_CTOR_END(true, false, false); break; case SCS_TQ_TYPE: // mSTRING_CTOR_END(true, false, true); break; case SCS_RE_TYPE: // mREGEXP_CTOR_END(true, false); break; default: throw new AssertionError(false); } lastSigTokenType = _returnToken.getType(); return _returnToken; }*//* catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); }*/ /*catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } }*/ } Token token = JavaLexer.this.nextToken(); int lasttype = token.getType(); if (whitespaceIncluded) { switch (lasttype) { // filter out insignificant types case WS: case SL_COMMENT: case ML_COMMENT: lasttype = lastSigTokenType; // back up! } } lastSigTokenType = lasttype; return token; } }; } protected JavaRecognizer parser; // little-used link; TODO: get rid of } // OPERATORS QUESTION : '?' ; LPAREN : '(' ; RPAREN : ')' ; LBRACK : '[' ; RBRACK : ']' ; LCURLY : '{' ; RCURLY : '}' ; COLON : ':' ; COMMA : ',' ; //DOT : '.' ; ASSIGN : '=' ; EQUAL : "==" ; LNOT : '!' ; BNOT : '~' ; NOT_EQUAL : "!=" ; DIV : '/' ; DIV_ASSIGN : "/=" ; PLUS : '+' ; PLUS_ASSIGN : "+=" ; INC : "++" ; MINUS : '-' ; MINUS_ASSIGN : "-=" ; DEC : "--" ; STAR : '*' ; STAR_ASSIGN : "*=" ; MOD : '%' ; MOD_ASSIGN : "%=" ; SR : ">>" ; SR_ASSIGN : ">>=" ; BSR : ">>>" ; BSR_ASSIGN : ">>>=" ; GE : ">=" ; GT : ">" ; SL : "<<" ; SL_ASSIGN : "<<=" ; LE : "<=" ; LT : '<' ; BXOR : '^' ; BXOR_ASSIGN : "^=" ; BOR : '|' ; BOR_ASSIGN : "|=" ; LOR : "||" ; BAND : '&' ; BAND_ASSIGN : "&=" ; LAND : "&&" ; SEMI : ';' ; // Whitespace -- ignored WS : ( ' ' | '\t' | '\f' // handle newlines | ( options {generateAmbigWarnings=false;} : "\r\n" // Evil DOS | '\r' // Macintosh | '\n' // Unix (the right way) ) { newline(); } )+ { _ttype = Token.SKIP; } ; // Single-line comments SL_COMMENT : "//" (~('\n'|'\r'))* ('\n'|'\r'('\n')?) {$setType(Token.SKIP); newline();} ; // multiple-line comments ML_COMMENT : "/*" ( /* '\r' '\n' can be matched in one alternative or by matching '\r' in one iteration and '\n' in another. I am trying to handle any flavor of newline that comes in, but the language that allows both "\r\n" and "\r" and "\n" to all be valid newline is ambiguous. Consequently, the resulting grammar must be ambiguous. I'm shutting this warning off. */ options { generateAmbigWarnings=false; } : { LA(2)!='/' }? '*' | '\r' '\n' {newline();} | '\r' {newline();} | '\n' {newline();} | ~('*'|'\n'|'\r') )* "*/" {$setType(Token.SKIP);} ; // character literals CHAR_LITERAL : '\'' ( ESC | ~('\''|'\n'|'\r'|'\\') ) '\'' ; // string literals STRING_LITERAL : '"' (ESC|~('"'|'\\'|'\n'|'\r'))* '"' ; // escape sequence -- note that this is protected; it can only be called // from another lexer rule -- it will not ever directly return a token to // the parser // There are various ambiguities hushed in this rule. The optional // '0'...'9' digit matches should be matched here rather than letting // them go back to STRING_LITERAL to be matched. ANTLR does the // right thing by matching immediately; hence, it's ok to shut off // the FOLLOW ambig warnings. protected ESC : '\\' ( 'n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | ('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT | '0'..'3' ( options { warnWhenFollowAmbig = false; } : '0'..'7' ( options { warnWhenFollowAmbig = false; } : '0'..'7' )? )? | '4'..'7' ( options { warnWhenFollowAmbig = false; } : '0'..'7' )? ) ; // hexadecimal digit (again, note it's protected!) protected HEX_DIGIT : ('0'..'9'|'A'..'F'|'a'..'f') ; // a dummy rule to force vocabulary to be all characters (except special // ones that ANTLR uses internally (0 to 2) protected VOCAB : '\3'..'\377' ; // an identifier. Note that testLiterals is set to true! This means // that after we match the rule, we look in the literals table to see // if it's a literal or really an identifer IDENT options {testLiterals=true;} : ('a'..'z'|'A'..'Z'|'_'|'$') ('a'..'z'|'A'..'Z'|'_'|'0'..'9'|'$')* { // check if "assert" keyword is enabled if (assertEnabled && "assert".equals($getText)) { $setType(LITERAL_assert); // set token type for the rule in the parser } // check if "enum" keyword is enabled if (enumEnabled && "enum".equals($getText)) { $setType(LITERAL_enum); // set token type for the rule in the parser } } ; // a numeric literal NUM_INT {boolean isDecimal=false; Token t=null;} : '.' {_ttype = DOT;} ( (('0'..'9')+ (EXPONENT)? (f1:FLOAT_SUFFIX {t=f1;})? { if (t != null && t.getText().toUpperCase().indexOf('F')>=0) { _ttype = NUM_FLOAT; } else { _ttype = NUM_DOUBLE; // assume double } }) | // JDK 1.5 token for variable length arguments (".." {_ttype = TRIPLE_DOT;}) )? | ( '0' {isDecimal = true;} // special case for just '0' ( ('x'|'X') ( // hex // the 'e'|'E' and float suffix stuff look // like hex digits, hence the (...)+ doesn't // know when to stop: ambig. ANTLR resolves // it correctly by matching immediately. It // is therefor ok to hush warning. options { warnWhenFollowAmbig=false; } : HEX_DIGIT )+ | //float or double with leading zero (('0'..'9')+ ('.'|EXPONENT|FLOAT_SUFFIX)) => ('0'..'9')+ | ('0'..'7')+ // octal )? | ('1'..'9') ('0'..'9')* {isDecimal=true;} // non-zero decimal ) ( ('l'|'L') { _ttype = NUM_LONG; } // only check to see if it's a float if looks like decimal so far | {isDecimal}? ( '.' ('0'..'9')* (EXPONENT)? (f2:FLOAT_SUFFIX {t=f2;})? | EXPONENT (f3:FLOAT_SUFFIX {t=f3;})? | f4:FLOAT_SUFFIX {t=f4;} ) { if (t != null && t.getText().toUpperCase() .indexOf('F') >= 0) { _ttype = NUM_FLOAT; } else { _ttype = NUM_DOUBLE; // assume double } } )? ; // JDK 1.5 token for annotations and their declarations AT : '@' ; // a couple protected methods to assist in matching floating point numbers protected EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; protected FLOAT_SUFFIX : 'f'|'F'|'d'|'D' ; // Note: Please don't use physical tabs. Logical tabs for indent are width 4. // Here's a little hint for you, Emacs: // Local Variables: // tab-width: 4 // mode: antlr-mode // indent-tabs-mode: nil // End: groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/Java2GroovyMain.java0000644001501200150120000002002111713765676025713 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.java; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.StringReader; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.codehaus.groovy.antlr.AntlrASTProcessor; import org.codehaus.groovy.antlr.SourceBuffer; import org.codehaus.groovy.antlr.UnicodeEscapingReader; import org.codehaus.groovy.antlr.parser.GroovyLexer; import org.codehaus.groovy.antlr.parser.GroovyRecognizer; import org.codehaus.groovy.antlr.treewalker.*; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import antlr.collections.AST; public class Java2GroovyMain { public static void main(String[] args) { try{ Options options = new Options(); PosixParser cliParser = new PosixParser(); CommandLine cli = cliParser.parse(options, args); String[] filenames = cli.getArgs(); if( filenames.length == 0 ) { System.err.println("Needs at least one filename"); } List filenameList = Arrays.asList(filenames); Iterator i = filenameList.iterator(); while (i.hasNext()) { String filename = (String) i.next(); File f = new File(filename); String text = DefaultGroovyMethods.getText(f); System.out.println(convert(filename, text, true, true)); } } catch (Throwable t) { t.printStackTrace(); } } public static String convert(String filename, String input) throws Exception{ return convert(filename, input, false, false); } public static String convert(String filename, String input,boolean withHeader, boolean withNewLines) throws Exception{ JavaRecognizer parser = getJavaParser(input); String[] tokenNames = parser.getTokenNames(); parser.compilationUnit(); AST ast = parser.getAST(); // output AST in format suitable for opening in http://freemind.sourceforge.net // which is a really nice way of seeing the AST, folding nodes etc if ("mindmap".equals(System.getProperty("antlr.ast"))) { try { PrintStream out = new PrintStream(new FileOutputStream(filename + ".mm")); Visitor visitor = new MindMapPrinter(out,tokenNames); AntlrASTProcessor treewalker = new PreOrderTraversal(visitor); treewalker.process(ast); } catch (FileNotFoundException e) { System.out.println("Cannot create " + filename + ".mm"); } } // modify the Java AST into a Groovy AST modifyJavaASTintoGroovyAST(tokenNames, ast); String[] groovyTokenNames = getGroovyTokenNames(input); // groovify the fat Java-Like Groovy AST groovifyFatJavaLikeGroovyAST(ast, groovyTokenNames); // now output ByteArrayOutputStream baos = new ByteArrayOutputStream(); Visitor visitor = new SourcePrinter(new PrintStream(baos),groovyTokenNames, withNewLines); AntlrASTProcessor traverser = new SourceCodeTraversal(visitor); traverser.process(ast); String header = ""; if (withHeader) { header = "/*\n" + " Automatically Converted from Java Source \n" + " \n" + " by java2groovy v0.0.1 Copyright Jeremy Rayner 2007\n" + " \n" + " !! NOT FIT FOR ANY PURPOSE !! \n" + " 'java2groovy' cannot be used to convert one working program into another" + " */\n\n"; } return header + new String(baos.toByteArray()); } /** * @param ast * @param groovyTokenNames */ private static void groovifyFatJavaLikeGroovyAST(AST ast, String[] groovyTokenNames) { Visitor groovifier = new Groovifier(groovyTokenNames); AntlrASTProcessor groovifierTraverser = new PreOrderTraversal(groovifier); groovifierTraverser.process(ast); } /** * @param tokenNames * @param ast */ private static void modifyJavaASTintoGroovyAST(String[] tokenNames, AST ast) { // mutate the tree when in Javaland Visitor preJava2groovyConverter = new PreJava2GroovyConverter(tokenNames); AntlrASTProcessor preJava2groovyTraverser = new PreOrderTraversal(preJava2groovyConverter); preJava2groovyTraverser.process(ast); // map the nodes to Groovy types Visitor java2groovyConverter = new Java2GroovyConverter(tokenNames); AntlrASTProcessor java2groovyTraverser = new PreOrderTraversal(java2groovyConverter); java2groovyTraverser.process(ast); } /** * @param input * @return */ private static JavaRecognizer getJavaParser(String input) { JavaRecognizer parser = null; SourceBuffer sourceBuffer = new SourceBuffer(); UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new StringReader(input),sourceBuffer); JavaLexer lexer = new JavaLexer(unicodeReader); unicodeReader.setLexer(lexer); parser = JavaRecognizer.make(lexer); parser.setSourceBuffer(sourceBuffer); return parser; } public static String mindmap(String input) throws Exception{ JavaRecognizer parser = getJavaParser(input); String[] tokenNames = parser.getTokenNames(); parser.compilationUnit(); AST ast = parser.getAST(); // modify the Java AST into a Groovy AST modifyJavaASTintoGroovyAST(tokenNames, ast); String[] groovyTokenNames = getGroovyTokenNames(input); // groovify the fat Java-Like Groovy AST groovifyFatJavaLikeGroovyAST(ast, groovyTokenNames); // now output ByteArrayOutputStream baos = new ByteArrayOutputStream(); Visitor visitor = new MindMapPrinter(new PrintStream(baos),groovyTokenNames); AntlrASTProcessor traverser = new SourceCodeTraversal(visitor); traverser.process(ast); return new String(baos.toByteArray()); } public static String nodePrinter(String input) throws Exception{ JavaRecognizer parser = getJavaParser(input); String[] tokenNames = parser.getTokenNames(); parser.compilationUnit(); AST ast = parser.getAST(); // modify the Java AST into a Groovy AST modifyJavaASTintoGroovyAST(tokenNames, ast); String[] groovyTokenNames = getGroovyTokenNames(input); // groovify the fat Java-Like Groovy AST groovifyFatJavaLikeGroovyAST(ast, groovyTokenNames); // now output ByteArrayOutputStream baos = new ByteArrayOutputStream(); Visitor visitor = new NodePrinter(new PrintStream(baos),groovyTokenNames); AntlrASTProcessor traverser = new SourceCodeTraversal(visitor); traverser.process(ast); return new String(baos.toByteArray()); } private static String[] getGroovyTokenNames(String input) { GroovyRecognizer groovyParser = null; SourceBuffer groovySourceBuffer = new SourceBuffer(); UnicodeEscapingReader groovyUnicodeReader = new UnicodeEscapingReader(new StringReader(input),groovySourceBuffer); GroovyLexer groovyLexer = new GroovyLexer(groovyUnicodeReader); groovyUnicodeReader.setLexer(groovyLexer); groovyParser = GroovyRecognizer.make(groovyLexer); return groovyParser.getTokenNames(); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/Groovifier.java0000644001501200150120000000507511713765676025064 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import org.codehaus.groovy.antlr.treewalker.VisitorAdapter; public class Groovifier extends VisitorAdapter implements GroovyTokenTypes { private String[] tokenNames; private String currentClassName = ""; private boolean cleanRedundantPublic; public Groovifier(String[] tokenNames) { this(tokenNames, true); } public Groovifier(String[] tokenNames, boolean cleanRedundantPublic) { this.tokenNames = tokenNames; this.cleanRedundantPublic = cleanRedundantPublic; } public void visitClassDef(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { currentClassName = t.childOfType(GroovyTokenTypes.IDENT).getText(); } } public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { // only want to do this once per node... // remove 'public' when implied already if requested if (t.getType() == LITERAL_public && cleanRedundantPublic) { t.setType(EXPR); } // constructors are not distinguished from methods in java ast if (t.getType() == METHOD_DEF) { String methodName = t.childOfType(IDENT).getText(); if (methodName != null && methodName.length() > 0) { if (methodName.equals(currentClassName)) { t.setType(CTOR_IDENT); } } } /* if (t.getType() == MODIFIERS) { GroovySourceAST publicNode = t.childOfType(LITERAL_public); if (t.getNumberOfChildren() > 1 && publicNode != null) { // has more than one modifier, and one of them is public // delete 'public' node publicNode.setType(EXPR); // near enough the same as delete for now... } }*/ // ---- } } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaTokenTypes.java0000644001501200150120000001017311715044504025631 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "java.g" -> "JavaLexer.java"$ package org.codehaus.groovy.antlr.java; import org.codehaus.groovy.antlr.*; import org.codehaus.groovy.antlr.parser.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; public interface JavaTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int BLOCK = 4; int MODIFIERS = 5; int OBJBLOCK = 6; int SLIST = 7; int METHOD_DEF = 8; int VARIABLE_DEF = 9; int INSTANCE_INIT = 10; int STATIC_INIT = 11; int TYPE = 12; int CLASS_DEF = 13; int INTERFACE_DEF = 14; int PACKAGE_DEF = 15; int ARRAY_DECLARATOR = 16; int EXTENDS_CLAUSE = 17; int IMPLEMENTS_CLAUSE = 18; int PARAMETERS = 19; int PARAMETER_DEF = 20; int LABELED_STAT = 21; int TYPECAST = 22; int INDEX_OP = 23; int POST_INC = 24; int POST_DEC = 25; int METHOD_CALL = 26; int EXPR = 27; int ARRAY_INIT = 28; int IMPORT = 29; int UNARY_MINUS = 30; int UNARY_PLUS = 31; int CASE_GROUP = 32; int ELIST = 33; int FOR_INIT = 34; int FOR_CONDITION = 35; int FOR_ITERATOR = 36; int EMPTY_STAT = 37; int FINAL = 38; int ABSTRACT = 39; int STRICTFP = 40; int SUPER_CTOR_CALL = 41; int CTOR_CALL = 42; int VARIABLE_PARAMETER_DEF = 43; int STATIC_IMPORT = 44; int ENUM_DEF = 45; int ENUM_CONSTANT_DEF = 46; int FOR_EACH_CLAUSE = 47; int ANNOTATION_DEF = 48; int ANNOTATIONS = 49; int ANNOTATION = 50; int ANNOTATION_MEMBER_VALUE_PAIR = 51; int ANNOTATION_FIELD_DEF = 52; int ANNOTATION_ARRAY_INIT = 53; int TYPE_ARGUMENTS = 54; int TYPE_ARGUMENT = 55; int TYPE_PARAMETERS = 56; int TYPE_PARAMETER = 57; int WILDCARD_TYPE = 58; int TYPE_UPPER_BOUNDS = 59; int TYPE_LOWER_BOUNDS = 60; int LITERAL_package = 61; int SEMI = 62; int LITERAL_import = 63; int LITERAL_static = 64; int LBRACK = 65; int RBRACK = 66; int IDENT = 67; int DOT = 68; int QUESTION = 69; int LITERAL_extends = 70; int LITERAL_super = 71; int LT = 72; int COMMA = 73; int GT = 74; int SR = 75; int BSR = 76; int LITERAL_void = 77; int LITERAL_boolean = 78; int LITERAL_byte = 79; int LITERAL_char = 80; int LITERAL_short = 81; int LITERAL_int = 82; int LITERAL_float = 83; int LITERAL_long = 84; int LITERAL_double = 85; int STAR = 86; int LITERAL_private = 87; int LITERAL_public = 88; int LITERAL_protected = 89; int LITERAL_transient = 90; int LITERAL_native = 91; int LITERAL_threadsafe = 92; int LITERAL_synchronized = 93; int LITERAL_volatile = 94; int AT = 95; int LPAREN = 96; int RPAREN = 97; int ASSIGN = 98; int LCURLY = 99; int RCURLY = 100; int LITERAL_class = 101; int LITERAL_interface = 102; int LITERAL_enum = 103; int BAND = 104; int LITERAL_default = 105; int LITERAL_implements = 106; int LITERAL_this = 107; int LITERAL_throws = 108; int TRIPLE_DOT = 109; int COLON = 110; int LITERAL_if = 111; int LITERAL_else = 112; int LITERAL_while = 113; int LITERAL_do = 114; int LITERAL_break = 115; int LITERAL_continue = 116; int LITERAL_return = 117; int LITERAL_switch = 118; int LITERAL_throw = 119; int LITERAL_assert = 120; int LITERAL_for = 121; int LITERAL_case = 122; int LITERAL_try = 123; int LITERAL_finally = 124; int LITERAL_catch = 125; int PLUS_ASSIGN = 126; int MINUS_ASSIGN = 127; int STAR_ASSIGN = 128; int DIV_ASSIGN = 129; int MOD_ASSIGN = 130; int SR_ASSIGN = 131; int BSR_ASSIGN = 132; int SL_ASSIGN = 133; int BAND_ASSIGN = 134; int BXOR_ASSIGN = 135; int BOR_ASSIGN = 136; int LOR = 137; int LAND = 138; int BOR = 139; int BXOR = 140; int NOT_EQUAL = 141; int EQUAL = 142; int LE = 143; int GE = 144; int LITERAL_instanceof = 145; int SL = 146; int PLUS = 147; int MINUS = 148; int DIV = 149; int MOD = 150; int INC = 151; int DEC = 152; int BNOT = 153; int LNOT = 154; int LITERAL_true = 155; int LITERAL_false = 156; int LITERAL_null = 157; int LITERAL_new = 158; int NUM_INT = 159; int CHAR_LITERAL = 160; int STRING_LITERAL = 161; int NUM_FLOAT = 162; int NUM_LONG = 163; int NUM_DOUBLE = 164; int WS = 165; int SL_COMMENT = 166; int ML_COMMENT = 167; int ESC = 168; int HEX_DIGIT = 169; int VOCAB = 170; int EXPONENT = 171; int FLOAT_SUFFIX = 172; } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/java/JavaTokenTypes.txt0000644001501200150120000000572311715044504025534 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): java.g -> JavaTokenTypes.txt$ Java // output token vocab name BLOCK=4 MODIFIERS=5 OBJBLOCK=6 SLIST=7 METHOD_DEF=8 VARIABLE_DEF=9 INSTANCE_INIT=10 STATIC_INIT=11 TYPE=12 CLASS_DEF=13 INTERFACE_DEF=14 PACKAGE_DEF=15 ARRAY_DECLARATOR=16 EXTENDS_CLAUSE=17 IMPLEMENTS_CLAUSE=18 PARAMETERS=19 PARAMETER_DEF=20 LABELED_STAT=21 TYPECAST=22 INDEX_OP=23 POST_INC=24 POST_DEC=25 METHOD_CALL=26 EXPR=27 ARRAY_INIT=28 IMPORT=29 UNARY_MINUS=30 UNARY_PLUS=31 CASE_GROUP=32 ELIST=33 FOR_INIT=34 FOR_CONDITION=35 FOR_ITERATOR=36 EMPTY_STAT=37 FINAL="final"=38 ABSTRACT="abstract"=39 STRICTFP="strictfp"=40 SUPER_CTOR_CALL=41 CTOR_CALL=42 VARIABLE_PARAMETER_DEF=43 STATIC_IMPORT=44 ENUM_DEF=45 ENUM_CONSTANT_DEF=46 FOR_EACH_CLAUSE=47 ANNOTATION_DEF=48 ANNOTATIONS=49 ANNOTATION=50 ANNOTATION_MEMBER_VALUE_PAIR=51 ANNOTATION_FIELD_DEF=52 ANNOTATION_ARRAY_INIT=53 TYPE_ARGUMENTS=54 TYPE_ARGUMENT=55 TYPE_PARAMETERS=56 TYPE_PARAMETER=57 WILDCARD_TYPE=58 TYPE_UPPER_BOUNDS=59 TYPE_LOWER_BOUNDS=60 LITERAL_package="package"=61 SEMI=62 LITERAL_import="import"=63 LITERAL_static="static"=64 LBRACK=65 RBRACK=66 IDENT=67 DOT=68 QUESTION=69 LITERAL_extends="extends"=70 LITERAL_super="super"=71 LT=72 COMMA=73 GT=74 SR=75 BSR=76 LITERAL_void="void"=77 LITERAL_boolean="boolean"=78 LITERAL_byte="byte"=79 LITERAL_char="char"=80 LITERAL_short="short"=81 LITERAL_int="int"=82 LITERAL_float="float"=83 LITERAL_long="long"=84 LITERAL_double="double"=85 STAR=86 LITERAL_private="private"=87 LITERAL_public="public"=88 LITERAL_protected="protected"=89 LITERAL_transient="transient"=90 LITERAL_native="native"=91 LITERAL_threadsafe="threadsafe"=92 LITERAL_synchronized="synchronized"=93 LITERAL_volatile="volatile"=94 AT=95 LPAREN=96 RPAREN=97 ASSIGN=98 LCURLY=99 RCURLY=100 LITERAL_class="class"=101 LITERAL_interface="interface"=102 LITERAL_enum="enum"=103 BAND=104 LITERAL_default="default"=105 LITERAL_implements="implements"=106 LITERAL_this="this"=107 LITERAL_throws="throws"=108 TRIPLE_DOT=109 COLON=110 LITERAL_if="if"=111 LITERAL_else="else"=112 LITERAL_while="while"=113 LITERAL_do="do"=114 LITERAL_break="break"=115 LITERAL_continue="continue"=116 LITERAL_return="return"=117 LITERAL_switch="switch"=118 LITERAL_throw="throw"=119 LITERAL_assert="assert"=120 LITERAL_for="for"=121 LITERAL_case="case"=122 LITERAL_try="try"=123 LITERAL_finally="finally"=124 LITERAL_catch="catch"=125 PLUS_ASSIGN=126 MINUS_ASSIGN=127 STAR_ASSIGN=128 DIV_ASSIGN=129 MOD_ASSIGN=130 SR_ASSIGN=131 BSR_ASSIGN=132 SL_ASSIGN=133 BAND_ASSIGN=134 BXOR_ASSIGN=135 BOR_ASSIGN=136 LOR=137 LAND=138 BOR=139 BXOR=140 NOT_EQUAL=141 EQUAL=142 LE=143 GE=144 LITERAL_instanceof="instanceof"=145 SL=146 PLUS=147 MINUS=148 DIV=149 MOD=150 INC=151 DEC=152 BNOT=153 LNOT=154 LITERAL_true="true"=155 LITERAL_false="false"=156 LITERAL_null="null"=157 LITERAL_new="new"=158 NUM_INT=159 CHAR_LITERAL=160 STRING_LITERAL=161 NUM_FLOAT=162 NUM_LONG=163 NUM_DOUBLE=164 WS=165 SL_COMMENT=166 ML_COMMENT=167 ESC=168 HEX_DIGIT=169 VOCAB=170 EXPONENT=171 FLOAT_SUFFIX=172 groovy-1.8.6/src/main/org/codehaus/groovy/antlr/AntlrASTProcessor.java0000644001501200150120000000212311627206700025325 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.collections.AST; /** * An interface for processing antlr AST objects * * @author Jeremy Rayner * @version $Revision$ */ public interface AntlrASTProcessor { /** * performs some processing on the supplied AST node. * @param t the AST node to process. * @return possibly returns the AST modified or null, depends on the implementation. */ AST process(AST t); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/LexerFrame.java0000644001501200150120000001613311627206700024035 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.reflect.*; import java.util.Hashtable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.text.BadLocationException; import org.codehaus.groovy.antlr.parser.*; import antlr.*; /** * @author Santhosh Kumar T * @version 1.0 */ public class LexerFrame extends JFrame implements ActionListener{ JSplitPane jSplitPane1 = new JSplitPane(); JScrollPane jScrollPane1 = new JScrollPane(); JScrollPane jScrollPane2 = new JScrollPane(); JTextPane tokenPane = new HScrollableTextPane(); JButton jbutton = new JButton("open"); JPanel mainPanel = new JPanel(new BorderLayout()); JTextArea scriptPane = new JTextArea(); Border border1; Border border2; Class lexerClass; public LexerFrame(Class lexerClass, Class tokenTypesClass){ super("Token Steam Viewer"); this.lexerClass = lexerClass; try{ jbInit(); setSize(500, 500); listTokens(tokenTypesClass); final JPopupMenu popup = new JPopupMenu(); popup.add(loadFileAction); jbutton.setSize(30,30); jbutton.addMouseListener(new MouseAdapter(){ public void mouseReleased(MouseEvent e) { //if(e.isPopupTrigger()) popup.show(scriptPane, e.getX(), e.getY()); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } catch(Exception e){ e.printStackTrace(); } } Hashtable tokens = new Hashtable(); private void listTokens(Class tokenTypes) throws Exception{ Field field[] = tokenTypes.getDeclaredFields(); for(int i = 0; iline){ tokenPane.getDocument().insertString(tokenPane.getDocument().getLength(), "\n", null); line = token.getLine(); } insertComponent(tokenButton); if(token.getType()==Token.EOF_TYPE) break; } tokenPane.setEditable(false); tokenPane.setCaretPosition(0); } private void insertComponent(JComponent comp){ try{ tokenPane.getDocument().insertString(tokenPane.getDocument().getLength(), " ", null); } catch(BadLocationException ex1){ // Ignore } try{ tokenPane.setCaretPosition(tokenPane.getDocument().getLength()-1); } catch(Exception ex){ tokenPane.setCaretPosition(0); } tokenPane.insertComponent(comp); } private void jbInit() throws Exception{ border1 = BorderFactory.createEmptyBorder(); border2 = BorderFactory.createEmptyBorder(); jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT); tokenPane.setEditable(false); tokenPane.setText(""); scriptPane.setFont(new java.awt.Font("DialogInput", 0, 12)); scriptPane.setEditable(false); scriptPane.setMargin(new Insets(5, 5, 5, 5)); scriptPane.setText(""); jScrollPane1.setBorder(border1); jScrollPane2.setBorder(border1); jSplitPane1.setMinimumSize(new Dimension(800,600)); mainPanel.add(jSplitPane1, BorderLayout.CENTER); mainPanel.add(jbutton,BorderLayout.NORTH); this.getContentPane().add(mainPanel); jSplitPane1.add(jScrollPane1, JSplitPane.LEFT); jScrollPane1.getViewport().add(tokenPane, null); jSplitPane1.add(jScrollPane2, JSplitPane.RIGHT); jScrollPane2.getViewport().add(scriptPane, null); jScrollPane1.setColumnHeaderView(new JLabel(" Token Stream:")); jScrollPane2.setColumnHeaderView(new JLabel(" Input Script:")); jSplitPane1.setResizeWeight(0.5); } public static void main(String[] args) throws Exception{ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ignore){ // Ignore } new LexerFrame(GroovyLexer.class, GroovyTokenTypes.class).setVisible(true); } } class HScrollableTextPane extends JTextPane{ public boolean getScrollableTracksViewportWidth(){ return(getSize().width package org.codehaus.groovy.antlr.*

      Parser related classes.

      groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/0000755001501200150120000000000011715044502022426 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyRecognizer.smap0000644001501200150120000032160111715044502026630 0ustar miguelmiguelSMAP GroovyRecognizer.java G *S G *F + 0 groovy.g groovy.g *L 2:3 2:4 2:5 2:6 2:7 2:8 2:9 2:10 2:11 2:12 233:220 234:221 235:222 236:223 237:224 238:225 239:226 240:227 241:228 242:229 243:230 244:231 245:232 246:233 247:234 249:236 251:238 252:239 254:241 255:242 256:243 257:244 258:245 259:246 260:247 262:249 263:250 264:251 265:252 266:253 267:254 268:255 269:256 270:257 271:258 272:259 273:260 274:261 275:262 276:263 277:264 278:265 280:267 281:268 282:269 283:270 284:271 285:272 286:273 287:274 288:275 289:276 290:277 292:279 293:280 294:281 296:283 297:284 298:285 300:287 301:288 302:289 304:291 305:292 306:293 307:294 308:295 309:296 310:297 311:298 312:299 315:302 316:303 317:304 318:305 319:306 320:307 321:308 322:309 323:310 324:311 325:312 327:314 328:315 329:316 330:317 331:318 332:319 333:320 334:321 335:322 336:323 337:324 338:325 339:326 340:327 341:328 342:329 343:330 344:331 345:332 346:333 347:334 349:336 350:337 351:338 352:339 353:340 355:342 356:343 357:344 358:345 359:346 360:347 361:348 362:349 363:350 365:352 366:353 367:354 368:355 370:357 371:358 372:359 373:360 375:362 376:363 377:364 379:366 380:367 381:368 382:369 383:370 384:371 385:372 386:373 387:374 388:375 389:376 390:377 391:378 393:380 394:381 395:382 397:384 398:385 399:386 400:387 401:388 402:389 403:390 405:392 406:393 407:394 408:395 409:396 410:397 411:398 413:400 414:401 415:402 417:404 418:405 419:406 420:407 421:408 422:409 424:411 425:412 426:413 428:415 429:416 430:417 431:418 433:420 434:421 435:422 436:423 438:425 439:426 440:427 442:429 443:430 444:431 446:433 447:434 448:435 449:436 450:437 451:438 453:440 454:441 455:442 456:443 457:444 458:445 459:446 461:448 462:449 463:450 464:451 465:452 466:453 467:454 468:455 469:456 470:457 471:458 472:459 473:460 478:491 478:493 478:494 478:495 478:782 478:783 481:498 481:499 481:500 481:501 481:572 481:573 481:574 481:575 481:576 484:578 487:580 487:581 487:582 487:583 487:584 487:585 487:587 487:588 487:590 487:591 487:592 487:593 487:594 487:595 487:596 487:597 487:598 487:599 487:600 487:682 487:683 487:684 487:685 488:601 488:603 488:604 488:605 488:606 488:607 488:608 488:609 488:610 488:611 488:612 488:613 488:614 488:615 488:616 488:617 488:618 488:619 488:620 488:621 488:622 488:623 488:624 488:625 488:626 488:627 488:628 488:629 488:630 488:631 488:632 488:633 488:634 488:635 488:636 488:637 488:638 488:639 488:640 488:641 488:642 488:643 488:644 488:645 488:646 488:647 488:648 488:649 488:650 488:651 488:652 488:653 488:654 488:655 488:656 488:657 488:658 488:659 488:660 488:661 488:662 488:663 488:664 488:665 488:666 488:667 488:676 488:677 488:678 488:679 488:680 493:688 493:689 493:690 493:691 493:692 493:694 493:695 493:696 493:697 493:698 493:699 493:700 493:701 493:702 493:703 493:704 493:705 493:706 493:707 493:708 493:709 493:710 493:711 493:712 493:713 493:714 493:715 493:716 493:717 493:718 493:719 493:720 493:721 493:722 493:723 493:724 493:725 493:726 493:727 493:728 493:729 493:730 493:731 493:732 493:733 493:734 493:735 493:736 493:737 493:738 493:739 493:740 493:741 493:742 493:743 493:744 493:745 493:746 493:747 493:748 493:749 493:750 493:751 493:752 493:753 493:754 493:755 493:756 493:757 493:758 493:767 493:768 493:769 493:770 493:771 493:773 493:774 493:775 493:776 493:778 493:779 494:780 496:781 498:1408 498:1409 498:1411 498:1412 498:1413 498:1419 498:1420 499:1415 499:1416 499:1417 499:1418 504:837 504:839 504:840 504:841 504:844 504:860 504:861 507:842 507:843 507:846 507:847 507:848 507:849 507:850 508:851 508:852 508:853 508:854 508:856 508:857 509:859 513:1658 513:1660 513:1661 513:1662 513:1665 513:1705 513:1706 516:1663 516:1664 516:1667 516:1668 516:1669 516:1670 516:1672 516:1673 516:1674 516:1675 516:1676 516:1677 516:1685 516:1686 516:1687 516:1688 516:1689 516:1691 516:1692 517:1693 517:1694 517:1695 517:1699 517:1701 517:1702 518:1696 518:1704 519:1697 520:1698 535:1807 535:1808 535:1809 535:1811 535:1812 535:1813 535:1819 535:1884 535:1885 535:1886 535:1887 535:1888 535:1889 535:1890 536:1814 536:1820 536:1821 536:1822 536:1823 536:1824 537:1825 537:1826 537:1827 537:1828 537:1830 537:1831 538:1815 538:1833 538:1836 538:1837 538:1838 538:1839 538:1840 539:1841 539:1842 539:1843 539:1844 539:1846 539:1847 540:1816 540:1849 540:1852 540:1853 540:1854 540:1855 540:1856 541:1857 541:1858 541:1859 541:1860 541:1862 541:1863 542:1817 542:1865 542:1868 542:1869 542:1870 542:1871 542:1872 543:1873 543:1874 543:1875 543:1876 543:1878 543:1879 544:1881 555:2090 555:2099 555:2101 555:2102 555:2103 555:2110 555:2177 555:2178 555:2179 555:2180 555:2181 555:2182 555:2183 556:2091 557:2092 558:2093 558:2104 558:2111 558:2112 558:2113 558:2114 558:2115 558:2116 558:2117 558:2118 558:2119 558:2120 558:2121 558:2122 558:2123 558:2124 558:2125 558:2126 558:2127 559:2094 559:2105 559:2129 559:2130 559:2131 559:2132 559:2134 559:2135 559:2136 559:2137 560:2095 560:2106 560:2140 560:2141 561:2096 561:2142 561:2143 561:2144 561:2145 561:2147 561:2148 562:2097 563:2098 564:2107 564:2152 564:2153 564:2154 564:2155 564:2156 564:2157 564:2158 564:2159 564:2160 564:2161 564:2162 564:2163 564:2164 565:2108 565:2165 565:2166 566:2167 566:2168 566:2169 566:2170 566:2172 566:2173 569:2395 569:2397 569:2398 569:2399 569:2426 569:2427 572:2400 572:2405 572:2406 573:2401 573:2407 573:2408 574:2402 574:2409 574:2410 575:2403 575:2411 575:2412 576:2413 576:2414 576:2421 576:2423 576:2424 577:2416 578:2417 579:2418 580:2419 591:2510 591:2513 591:2515 591:2516 591:2517 591:2524 591:2591 591:2592 591:2593 591:2594 591:2595 591:2596 591:2597 592:2511 593:2512 594:2518 594:2525 594:2526 594:2527 594:2528 594:2529 594:2530 594:2531 594:2532 594:2533 594:2534 594:2535 594:2536 594:2537 594:2538 594:2539 594:2540 594:2541 595:2519 595:2543 595:2544 595:2545 595:2546 595:2548 595:2549 595:2550 595:2551 596:2520 596:2554 596:2555 597:2556 597:2557 597:2558 597:2559 597:2561 597:2562 600:2521 600:2566 600:2567 600:2568 600:2569 600:2570 600:2571 600:2572 600:2573 600:2574 600:2575 600:2576 600:2577 600:2578 601:2522 601:2579 601:2580 602:2581 602:2582 602:2583 602:2584 602:2586 602:2587 609:2623 609:2627 609:2629 609:2630 609:2631 609:2667 609:2668 610:2624 610:2632 610:2634 610:2635 611:2625 611:2636 611:2637 611:2638 611:2639 611:2641 611:2642 612:2626 612:2645 612:2646 612:2647 612:2648 612:2649 612:2660 612:2661 612:2662 612:2663 612:2664 613:2666 635:2688 635:2708 635:2710 635:2711 635:2712 635:2857 635:2858 636:2689 636:2715 636:2716 636:2717 636:2718 636:2719 636:2720 636:2722 636:2723 636:2750 636:2827 636:2828 636:2829 636:2830 636:2831 636:2832 636:2833 636:2834 637:2690 637:2727 637:2728 637:2729 637:2730 637:2731 637:2732 637:2733 637:2734 637:2735 637:2736 637:2737 637:2738 637:2739 637:2740 637:2741 638:2691 638:2744 638:2745 638:2746 638:2747 639:2692 639:2751 639:2753 639:2754 639:2755 639:2758 639:2761 639:2762 639:2763 639:2764 640:2693 640:2756 640:2757 641:2694 641:2759 641:2760 642:2695 642:2768 642:2769 642:2770 642:2771 642:2803 642:2804 642:2805 642:2806 642:2807 642:2809 642:2810 642:2811 642:2812 642:2813 642:2814 642:2815 642:2816 642:2817 642:2818 642:2819 642:2820 642:2821 642:2822 642:2823 642:2825 642:2826 643:2696 644:2697 644:2836 644:2837 644:2838 644:2839 644:2840 644:2841 644:2844 644:2845 644:2846 644:2847 644:2848 644:2851 644:2852 644:2853 644:2854 644:2855 645:2698 646:2699 647:2700 648:2701 649:2702 650:2703 651:2704 652:2705 653:2706 654:2707 655:3347 655:3355 655:3357 655:3358 655:3359 655:3406 655:3407 656:3348 656:3362 656:3363 656:3364 656:3365 656:3366 656:3367 656:3368 656:3369 656:3395 656:3396 656:3397 656:3398 656:3399 656:3400 656:3401 656:3402 657:3349 657:3372 657:3373 657:3374 657:3375 657:3376 657:3377 657:3378 657:3379 657:3380 657:3381 657:3382 657:3383 657:3384 657:3385 657:3386 658:3350 658:3389 658:3390 658:3391 658:3392 659:3351 659:3403 659:3404 659:3405 660:3352 661:3353 662:3227 662:3229 662:3230 662:3231 662:3257 662:3258 662:3354 664:3233 664:3234 664:3235 664:3236 664:3237 664:3238 664:3239 664:3240 664:3241 664:3242 664:3243 664:3244 664:3245 664:3246 664:3247 664:3248 664:3249 664:3250 664:3251 664:3252 664:3254 664:3255 664:3256 669:3409 669:3411 669:3413 669:3414 669:3415 669:3427 669:3428 670:3410 671:3416 671:3417 671:3419 671:3420 671:3421 671:3422 671:3423 671:3424 671:3425 671:3426 691:3462 691:3463 691:3465 691:3466 691:3467 691:3501 691:3502 692:3469 692:3471 692:3472 692:3473 692:3474 692:3477 692:3478 692:3479 692:3482 692:3483 692:3484 692:3487 692:3488 692:3489 692:3490 692:3491 692:3492 692:3495 692:3496 692:3497 692:3498 692:3499 698:3112 698:3115 698:3117 698:3118 698:3119 698:3121 698:3122 698:3128 698:3129 699:3113 700:3114 700:3123 700:3124 700:3125 700:3126 702:3127 706:2207 706:2208 706:2209 706:2211 706:2212 706:2213 706:2215 706:2238 706:2239 706:2240 706:2241 706:2242 706:2243 706:2244 707:2216 707:2217 707:2218 707:2219 707:2220 708:2223 708:2224 708:2225 708:2226 708:2227 708:2228 708:2229 708:2230 708:2231 708:2232 708:2233 708:2234 708:2235 717:3504 717:3505 717:3506 717:3508 717:3509 717:3510 717:3512 717:3531 717:3532 718:3511 718:3514 718:3515 719:3516 719:3517 720:3518 720:3519 720:3525 720:3527 720:3528 721:3521 721:3530 722:3522 723:3523 728:3564 728:3565 728:3566 728:3568 728:3569 728:3570 728:3578 728:3768 728:3769 729:3571 729:3572 729:3580 729:3581 729:3582 729:3583 729:3585 729:3586 729:3587 729:3588 729:3589 729:3590 729:3591 729:3592 729:3594 729:3595 729:3596 729:3597 731:3600 731:3601 731:3602 731:3747 731:3748 731:3749 731:3750 731:3752 731:3753 732:3573 732:3574 732:3603 732:3604 732:3605 732:3606 733:3575 733:3576 733:3577 733:3607 733:3608 733:3609 733:3611 733:3612 733:3613 733:3614 733:3615 733:3738 733:3739 733:3740 733:3741 733:3742 734:3744 734:3745 736:3754 736:3755 736:3762 736:3764 736:3765 737:3757 737:3767 738:3758 739:3759 740:3760 745:3830 745:3832 745:3833 745:3834 745:3836 745:3859 745:3860 745:3861 745:3862 745:3863 745:3864 745:3865 746:3837 746:3838 746:3839 746:3840 746:3841 747:3844 747:3845 747:3846 747:3847 747:3848 747:3849 747:3850 747:3851 747:3852 747:3853 747:3854 747:3855 747:3856 751:3929 751:3931 751:3932 751:3933 751:3934 751:3974 751:3975 752:3937 752:3938 752:3939 752:3940 752:3941 752:3942 752:3943 752:3944 752:3945 752:3946 752:3947 752:3948 752:3949 752:3950 752:3959 752:3960 752:3961 752:3962 752:3963 753:3953 753:3954 753:3955 753:3956 755:3965 755:3966 755:3967 755:3968 755:3970 755:3971 756:3973 759:3977 759:3979 759:3980 759:3981 759:4035 759:4036 760:3983 760:3984 760:3985 760:3986 761:3988 761:3989 761:3990 761:3991 761:3992 761:3993 761:3995 761:3996 761:3997 761:3998 761:4001 761:4002 761:4003 761:4006 761:4007 761:4008 761:4009 761:4010 761:4012 761:4013 761:4014 761:4015 761:4016 761:4017 761:4018 761:4019 761:4020 761:4021 761:4022 761:4024 761:4025 761:4026 761:4027 762:4030 762:4031 762:4032 765:3816 765:3818 765:3819 765:3820 765:3821 765:3827 765:3828 765:4034 767:3823 767:3824 767:3825 769:3826 771:3260 771:3262 771:3263 771:3264 771:3265 771:3318 771:3319 772:3266 775:3268 775:3269 776:3271 776:3272 776:3273 776:3275 777:3276 777:3277 778:3278 778:3279 778:3280 778:3286 778:3287 778:3288 778:3289 778:3291 778:3292 780:3281 780:3282 780:3283 780:3284 780:3285 782:3293 783:3298 783:3300 783:3301 783:3302 783:3303 786:3295 786:3296 786:3297 791:3306 791:3307 791:3308 794:3309 794:3310 794:3311 794:3312 794:3314 794:3315 795:3317 799:4091 799:4093 799:4094 799:4095 799:4097 799:4125 799:4126 799:4127 799:4128 799:4129 799:4130 799:4131 800:4098 800:4099 800:4100 800:4101 800:4102 801:4107 801:4108 801:4109 801:4110 801:4111 802:4116 802:4117 802:4118 802:4119 802:4120 803:4104 804:4113 805:4122 806:4038 806:4040 806:4041 806:4042 806:4043 806:4088 806:4089 809:4046 809:4047 809:4048 809:4049 809:4050 809:4051 809:4055 809:4056 809:4057 809:4060 809:4061 809:4062 809:4063 809:4064 809:4066 809:4067 809:4068 809:4069 810:4070 810:4071 810:4082 810:4084 810:4085 811:4073 811:4087 812:4074 813:4075 814:4076 815:4077 816:4078 817:4079 818:4080 823:3867 823:3868 823:3869 823:3871 823:3872 823:3873 823:3875 823:3926 823:3927 824:3874 824:3877 824:3878 825:3880 825:3881 825:3882 825:3883 825:3884 825:3885 825:3887 825:3889 825:3890 825:3891 825:3892 825:3893 825:3894 825:3895 825:3896 825:3899 825:3907 825:3908 825:3909 825:3910 826:3897 826:3898 827:3900 827:3901 827:3902 828:3903 829:3904 830:3905 832:3913 832:3914 832:3920 832:3922 832:3923 833:3916 833:3925 834:3917 835:3918 841:3534 841:3535 841:3536 841:3538 841:3539 841:3540 841:3542 841:3561 841:3562 842:3541 842:3544 842:3545 843:3546 843:3547 844:3548 844:3549 844:3555 844:3557 844:3558 845:3551 845:3560 846:3552 847:3553 853:4133 853:4135 853:4136 853:4137 853:4139 853:4162 853:4163 853:4164 853:4165 853:4166 853:4167 853:4168 854:4140 854:4141 854:4142 854:4143 854:4144 855:4147 855:4148 855:4149 855:4150 855:4151 855:4152 855:4153 855:4154 855:4155 855:4156 855:4157 855:4158 855:4159 859:3131 859:3133 859:3134 859:3135 859:3137 859:3219 859:3220 859:3221 859:3222 859:3223 859:3224 859:3225 860:3138 860:3139 860:3140 860:3141 860:3142 860:3143 860:3144 861:3147 861:3148 861:3149 861:3150 861:3151 861:3152 861:3153 862:3156 862:3157 862:3158 862:3159 862:3160 862:3161 862:3162 863:3165 863:3166 863:3167 863:3168 863:3169 863:3170 863:3171 864:3174 864:3175 864:3176 864:3177 864:3178 864:3179 864:3180 865:3183 865:3184 865:3185 865:3186 865:3187 865:3188 865:3189 866:3192 866:3193 866:3194 866:3195 866:3196 866:3197 866:3198 867:3201 867:3202 867:3203 867:3204 867:3205 867:3206 867:3207 868:3210 868:3211 868:3212 868:3213 868:3214 868:3215 868:3216 873:1609 873:1611 873:1612 873:1613 873:1620 873:1655 873:1656 874:1614 874:1615 874:1622 874:1623 874:1624 875:1625 875:1626 875:1627 875:1639 875:1640 875:1641 875:1642 875:1644 875:1645 876:1616 876:1617 876:1618 876:1619 876:1628 876:1629 876:1630 876:1631 876:1632 876:1633 876:1634 876:1635 877:1636 877:1637 879:1646 879:1647 879:1648 879:1649 879:1651 879:1652 880:1654 882:1708 882:1710 882:1711 882:1712 882:1725 882:1804 882:1805 883:1713 883:1714 883:1727 883:1728 883:1729 884:1730 884:1731 884:1732 884:1744 884:1745 884:1746 884:1747 884:1749 884:1750 885:1715 885:1716 885:1717 885:1718 885:1733 885:1734 885:1735 885:1736 885:1737 885:1738 885:1739 885:1740 886:1741 886:1742 888:1719 888:1720 888:1721 888:1722 888:1752 888:1753 888:1754 888:1755 888:1756 888:1757 888:1758 888:1759 888:1760 888:1761 888:1789 888:1790 888:1791 888:1792 888:1793 889:1762 889:1763 890:1723 890:1724 890:1767 890:1768 890:1769 890:1770 890:1771 890:1772 890:1773 891:1774 891:1775 893:1795 893:1796 893:1797 893:1798 893:1800 893:1801 894:1803 896:4170 896:4172 896:4173 896:4174 896:4175 896:4216 896:4217 899:4178 899:4179 899:4180 899:4184 899:4189 899:4202 899:4207 899:4208 899:4209 899:4210 899:4212 899:4213 899:4214 899:4215 908:4181 908:4182 908:4183 911:4185 911:4186 911:4187 911:4188 913:4190 913:4191 913:4192 914:4194 914:4195 914:4196 914:4197 914:4198 914:4199 914:4200 914:4201 916:4203 916:4204 916:4205 916:4206 921:2185 921:2186 921:2188 921:2189 921:2190 921:2191 921:2204 921:2205 922:2193 922:2194 923:2195 923:2196 923:2197 923:2198 923:2200 923:2201 924:2203 927:3430 927:3431 927:3433 927:3434 927:3435 927:3436 927:3459 927:3460 928:3442 928:3444 928:3445 928:3446 928:3447 931:3439 931:3440 931:3441 933:3450 933:3451 933:3452 933:3453 933:3455 933:3456 934:3458 937:2860 937:2862 937:2863 937:2864 937:2866 937:2975 937:2976 937:2977 937:2978 937:2979 937:2980 937:2981 938:2867 938:2868 938:2869 938:2870 938:2871 938:2872 938:2873 939:2876 939:2877 939:2878 939:2879 939:2880 939:2881 939:2882 940:2885 940:2886 940:2887 940:2888 940:2889 940:2890 940:2891 941:2894 941:2895 941:2896 941:2897 941:2898 941:2899 941:2900 942:2903 942:2904 942:2905 942:2906 942:2907 942:2908 942:2909 943:2912 943:2913 943:2914 943:2915 943:2916 943:2917 943:2918 944:2921 944:2922 944:2923 944:2924 944:2925 944:2926 944:2927 945:2930 945:2931 945:2932 945:2933 945:2934 945:2935 945:2936 946:2939 946:2940 946:2941 946:2942 946:2943 946:2944 946:2945 947:2948 947:2949 947:2950 947:2951 947:2952 947:2953 947:2954 948:2957 948:2958 948:2959 948:2960 948:2961 948:2962 948:2963 949:2966 949:2967 949:2968 949:2969 949:2970 949:2971 949:2972 952:2983 952:2985 952:2986 952:2987 952:2990 952:3109 952:3110 953:2988 953:2989 953:2992 953:2993 953:2994 953:2995 953:2997 953:2998 953:3000 953:3001 953:3002 953:3003 953:3004 953:3005 953:3006 953:3007 953:3008 953:3009 953:3010 953:3011 953:3012 953:3013 953:3014 953:3015 953:3016 953:3017 953:3018 953:3019 953:3020 953:3021 953:3022 953:3023 953:3024 953:3025 953:3026 953:3027 953:3028 953:3029 953:3030 953:3031 953:3032 953:3033 953:3034 953:3035 953:3036 953:3037 953:3038 953:3039 953:3040 953:3041 953:3042 953:3043 953:3044 953:3045 953:3046 953:3047 953:3048 953:3049 953:3050 953:3051 953:3052 953:3053 953:3054 953:3055 953:3056 953:3057 953:3058 953:3059 953:3060 953:3061 953:3062 953:3063 953:3064 953:3065 953:3066 953:3067 953:3068 953:3069 953:3070 953:3071 953:3072 953:3073 953:3074 953:3075 953:3076 953:3077 953:3078 953:3079 953:3086 953:3087 953:3088 953:3089 953:3090 953:3092 953:3093 953:3095 953:3096 953:3097 953:3098 954:3101 954:3102 954:3103 954:3104 954:3106 954:3107 957:4255 957:4257 957:4258 957:4259 957:4289 957:4290 958:4261 958:4262 958:4263 958:4276 958:4281 958:4282 958:4283 958:4284 958:4286 958:4287 958:4288 960:4264 960:4265 960:4266 961:4268 961:4269 961:4270 961:4271 961:4272 961:4273 961:4274 961:4275 963:4277 963:4278 963:4279 963:4280 966:806 966:808 966:809 966:810 966:811 966:834 966:835 967:817 967:819 967:820 967:821 967:822 970:814 970:815 970:816 972:825 972:826 972:827 972:828 972:830 972:831 973:833 975:4219 975:4221 975:4222 975:4223 975:4242 975:4247 975:4248 975:4249 975:4250 975:4252 975:4253 976:4224 976:4226 976:4227 976:4228 976:4229 977:4230 977:4231 977:4232 977:4236 977:4238 977:4239 978:4233 978:4241 979:4234 980:4235 981:4243 981:4244 981:4245 981:4246 984:4353 984:4355 984:4356 984:4357 984:4377 984:4378 985:4359 985:4360 985:4361 985:4362 985:4363 985:4364 985:4365 985:4366 985:4367 985:4368 985:4369 985:4370 985:4371 985:4372 985:4374 985:4375 985:4376 988:4380 988:4382 988:4383 988:4384 988:4387 988:4403 988:4404 989:4385 989:4386 989:4389 989:4390 989:4391 989:4392 989:4393 989:4394 990:4395 990:4396 990:4397 990:4398 990:4400 990:4401 993:4406 993:4408 993:4409 993:4410 993:4412 993:4485 993:4486 993:4487 993:4488 993:4489 993:4490 993:4491 994:4413 994:4414 994:4415 994:4416 994:4417 994:4418 995:4422 995:4423 995:4424 995:4425 995:4426 995:4427 995:4428 995:4429 995:4430 995:4431 995:4432 995:4433 995:4434 995:4435 995:4436 995:4437 995:4438 995:4439 995:4440 995:4441 995:4442 995:4443 995:4444 995:4445 995:4446 995:4447 995:4448 995:4449 995:4450 995:4451 995:4452 995:4453 995:4454 995:4455 995:4456 995:4457 995:4458 995:4459 995:4460 995:4461 995:4462 995:4463 995:4464 995:4465 995:4466 995:4467 995:4468 995:4469 995:4470 995:4471 995:4472 995:4473 995:4474 995:4475 995:4476 995:4477 995:4478 995:4479 995:4480 995:4481 995:4482 996:4419 998:4292 998:4294 998:4295 998:4296 998:4298 998:4345 998:4346 998:4347 998:4348 998:4349 998:4350 998:4351 999:4299 999:4300 999:4301 999:4302 999:4303 999:4304 999:4305 999:4306 999:4307 999:4308 999:4309 999:4310 999:4311 999:4312 999:4313 999:4314 999:4315 999:4316 999:4317 999:4318 999:4319 999:4320 999:4321 999:4322 999:4323 999:4324 999:4325 999:4326 999:4327 999:4328 999:4329 999:4330 999:4331 999:4332 999:4333 999:4334 999:4335 999:4338 999:4339 999:4340 999:4341 999:4342 1026:4983 1026:4985 1026:4986 1026:4987 1026:4989 1026:5037 1026:5038 1026:5039 1026:5040 1026:5041 1026:5042 1026:5043 1027:4990 1027:4991 1027:4992 1027:4993 1027:4994 1027:4995 1027:4996 1027:4997 1027:4998 1027:4999 1027:5000 1027:5001 1027:5002 1027:5003 1027:5004 1027:5005 1027:5006 1027:5007 1027:5008 1027:5009 1027:5010 1027:5011 1027:5012 1027:5013 1027:5014 1027:5015 1027:5016 1027:5017 1027:5018 1027:5019 1027:5020 1027:5021 1027:5022 1027:5023 1027:5024 1027:5025 1027:5026 1028:5029 1028:5030 1028:5031 1028:5032 1028:5033 1030:5034 1031:5045 1031:5047 1031:5048 1031:5049 1031:5051 1031:5083 1031:5084 1034:5050 1034:5054 1034:5055 1034:5056 1034:5057 1034:5058 1034:5059 1034:5060 1034:5061 1034:5069 1034:5070 1034:5071 1034:5072 1034:5073 1035:5075 1035:5076 1035:5077 1035:5078 1035:5080 1035:5081 1039:1892 1039:1893 1039:1894 1039:1896 1039:1897 1039:1898 1039:1903 1039:1955 1039:1956 1040:1904 1041:1905 1042:1906 1043:1907 1045:1909 1045:1910 1045:1911 1045:1912 1045:1913 1046:1914 1046:1915 1048:1899 1048:1918 1048:1919 1048:1920 1048:1921 1048:1922 1048:1923 1048:1932 1048:1933 1048:1934 1048:1935 1048:1936 1050:1900 1050:1938 1050:1939 1052:1901 1052:1940 1052:1941 1054:1902 1054:1942 1054:1943 1055:1944 1055:1945 1055:1946 1055:1947 1055:1949 1055:1950 1057:1952 1057:1953 1063:1958 1063:1959 1063:1960 1063:1962 1063:1963 1063:1964 1063:1968 1063:2011 1063:2012 1064:1969 1065:1970 1066:1971 1067:1972 1068:1974 1068:1975 1068:1976 1068:1977 1068:1978 1070:1965 1070:1980 1070:1981 1070:1982 1070:1983 1070:1984 1070:1985 1070:1993 1070:1994 1070:1995 1070:1996 1070:1997 1072:1966 1072:1999 1072:2000 1074:1967 1074:2001 1074:2002 1075:2003 1075:2004 1075:2005 1075:2006 1075:2008 1075:2009 1079:2014 1079:2015 1079:2016 1079:2018 1079:2019 1079:2020 1079:2023 1079:2053 1079:2054 1080:2024 1081:2025 1082:2026 1083:2027 1084:2029 1084:2030 1084:2031 1084:2032 1085:2033 1085:2034 1086:2036 1088:2021 1088:2037 1088:2038 1089:2039 1091:2022 1091:2040 1091:2041 1092:2042 1092:2043 1092:2044 1092:2045 1092:2047 1092:2048 1094:2050 1094:2051 1097:2056 1097:2057 1097:2058 1097:2060 1097:2061 1097:2062 1097:2064 1097:2087 1097:2088 1098:2065 1099:2066 1100:2067 1101:2068 1102:2070 1102:2071 1102:2072 1102:2073 1102:2074 1102:2075 1102:2076 1104:2063 1104:2077 1104:2078 1105:2079 1105:2080 1105:2081 1105:2082 1105:2084 1105:2085 1109:2429 1109:2431 1109:2432 1109:2433 1109:2434 1109:2507 1109:2508 1112:2436 1112:2437 1113:2439 1113:2440 1113:2441 1113:2443 1114:2444 1114:2445 1114:2446 1114:2447 1114:2448 1114:2449 1114:2450 1114:2451 1114:2452 1114:2453 1114:2454 1114:2455 1114:2456 1114:2457 1114:2459 1114:2460 1115:2461 1116:2463 1116:2464 1116:2465 1116:2466 1116:2467 1116:2468 1116:2469 1116:2489 1116:2490 1116:2491 1116:2492 1116:2493 1120:2495 1120:2496 1120:2497 1123:2498 1123:2499 1123:2500 1123:2501 1123:2503 1123:2504 1124:2506 1126:5738 1126:5740 1126:5741 1126:5742 1126:5745 1126:5774 1126:5775 1129:5743 1129:5744 1129:5748 1129:5749 1129:5750 1129:5751 1129:5754 1129:5755 1129:5756 1129:5757 1129:5759 1129:5760 1129:5761 1129:5762 1130:5765 1130:5766 1130:5767 1130:5768 1130:5770 1130:5771 1131:5773 1133:5777 1133:5779 1133:5780 1133:5781 1133:5782 1133:5812 1133:5813 1135:5784 1135:5785 1135:5786 1135:5787 1136:5788 1136:5789 1136:5790 1136:5791 1136:5792 1136:5793 1136:5794 1136:5795 1136:5796 1136:5797 1136:5798 1136:5799 1136:5801 1136:5802 1137:5803 1137:5804 1137:5805 1137:5806 1137:5808 1137:5809 1138:5811 1141:5146 1141:5148 1141:5149 1141:5150 1141:5151 1141:5270 1141:5271 1142:5153 1143:5155 1143:5156 1143:5157 1143:5158 1143:5159 1143:5160 1143:5161 1143:5162 1143:5163 1143:5164 1143:5165 1143:5166 1143:5167 1143:5168 1143:5169 1143:5170 1143:5171 1143:5172 1143:5173 1143:5174 1143:5175 1143:5176 1143:5177 1143:5178 1143:5179 1143:5180 1143:5181 1143:5182 1143:5183 1143:5184 1143:5185 1143:5186 1143:5195 1143:5196 1143:5197 1143:5198 1143:5199 1143:5201 1143:5202 1143:5203 1143:5204 1143:5205 1143:5207 1143:5208 1143:5209 1143:5210 1143:5211 1143:5212 1143:5213 1143:5214 1143:5215 1143:5216 1143:5217 1143:5218 1143:5219 1143:5220 1143:5221 1143:5222 1143:5223 1143:5224 1143:5225 1143:5226 1143:5227 1143:5228 1143:5229 1143:5230 1143:5231 1143:5232 1143:5233 1143:5234 1143:5235 1143:5236 1143:5237 1143:5238 1143:5247 1143:5248 1143:5249 1143:5250 1143:5251 1143:5253 1143:5254 1143:5255 1143:5256 1143:5258 1143:5259 1144:5260 1145:5261 1145:5262 1145:5263 1145:5264 1145:5266 1145:5267 1146:5269 1149:5332 1149:5334 1149:5335 1149:5336 1149:5337 1149:5454 1149:5455 1150:5339 1151:5341 1151:5342 1151:5343 1151:5344 1151:5345 1151:5346 1151:5347 1151:5348 1151:5349 1151:5350 1151:5351 1151:5352 1151:5353 1151:5354 1151:5355 1151:5356 1151:5357 1151:5358 1151:5359 1151:5360 1151:5361 1151:5362 1151:5363 1151:5364 1151:5365 1151:5366 1151:5367 1151:5368 1151:5369 1151:5370 1151:5371 1151:5380 1151:5381 1151:5382 1151:5383 1151:5384 1151:5386 1151:5387 1151:5388 1151:5389 1151:5390 1151:5392 1151:5393 1151:5394 1151:5395 1151:5396 1151:5397 1151:5398 1151:5399 1151:5400 1151:5401 1151:5402 1151:5403 1151:5404 1151:5405 1151:5406 1151:5407 1151:5408 1151:5409 1151:5410 1151:5411 1151:5412 1151:5413 1151:5414 1151:5415 1151:5416 1151:5417 1151:5418 1151:5419 1151:5420 1151:5421 1151:5422 1151:5431 1151:5432 1151:5433 1151:5434 1151:5435 1151:5437 1151:5438 1151:5439 1151:5440 1151:5442 1151:5443 1152:5444 1153:5445 1153:5446 1153:5447 1153:5448 1153:5450 1153:5451 1154:5453 1158:5613 1158:5615 1158:5616 1158:5617 1158:5618 1158:5735 1158:5736 1159:5620 1160:5622 1160:5623 1160:5624 1160:5625 1160:5626 1160:5627 1160:5628 1160:5629 1160:5630 1160:5631 1160:5632 1160:5633 1160:5634 1160:5635 1160:5636 1160:5637 1160:5638 1160:5639 1160:5640 1160:5641 1160:5642 1160:5643 1160:5644 1160:5645 1160:5646 1160:5647 1160:5648 1160:5649 1160:5650 1160:5651 1160:5652 1160:5661 1160:5662 1160:5663 1160:5664 1160:5665 1160:5667 1160:5668 1160:5669 1160:5670 1160:5671 1160:5673 1160:5674 1160:5675 1160:5676 1160:5677 1160:5678 1160:5679 1160:5680 1160:5681 1160:5682 1160:5683 1160:5684 1160:5685 1160:5686 1160:5687 1160:5688 1160:5689 1160:5690 1160:5691 1160:5692 1160:5693 1160:5694 1160:5695 1160:5696 1160:5697 1160:5698 1160:5699 1160:5700 1160:5701 1160:5702 1160:5703 1160:5712 1160:5713 1160:5714 1160:5715 1160:5716 1160:5718 1160:5719 1160:5720 1160:5721 1160:5723 1160:5724 1161:5725 1162:5726 1162:5727 1162:5728 1162:5729 1162:5731 1162:5732 1163:5734 1167:5457 1167:5459 1167:5460 1167:5461 1167:5462 1167:5610 1167:5611 1168:5464 1168:5465 1169:5486 1169:5535 1169:5536 1169:5537 1169:5538 1174:5467 1174:5468 1174:5469 1174:5470 1174:5471 1174:5472 1174:5474 1174:5476 1174:5477 1174:5478 1174:5479 1174:5480 1174:5481 1174:5482 1174:5483 1174:5484 1174:5485 1175:5487 1175:5489 1175:5490 1175:5491 1175:5492 1175:5493 1175:5494 1175:5495 1175:5496 1175:5497 1175:5498 1175:5499 1175:5500 1175:5501 1175:5502 1175:5503 1175:5504 1175:5505 1175:5506 1175:5507 1175:5508 1175:5509 1175:5510 1175:5511 1175:5512 1175:5513 1175:5514 1175:5515 1175:5516 1175:5517 1175:5518 1175:5519 1175:5520 1175:5529 1175:5530 1175:5531 1175:5532 1175:5533 1177:5541 1177:5542 1177:5543 1177:5544 1177:5545 1177:5547 1177:5548 1177:5549 1177:5550 1177:5551 1177:5552 1177:5553 1177:5554 1177:5555 1177:5556 1177:5557 1177:5558 1177:5559 1177:5560 1177:5561 1177:5562 1177:5563 1177:5564 1177:5565 1177:5566 1177:5567 1177:5568 1177:5569 1177:5570 1177:5571 1177:5572 1177:5573 1177:5574 1177:5575 1177:5576 1177:5577 1177:5578 1177:5587 1177:5588 1177:5589 1177:5590 1177:5591 1177:5593 1177:5594 1177:5595 1177:5596 1177:5598 1177:5599 1178:5600 1179:5601 1179:5602 1179:5603 1179:5604 1179:5606 1179:5607 1180:5609 1183:6253 1183:6254 1183:6256 1183:6257 1183:6258 1183:6385 1183:6386 1184:6260 1184:6261 1184:6262 1184:6263 1184:6264 1184:6265 1184:6267 1184:6268 1184:6269 1184:6270 1184:6271 1184:6272 1184:6273 1184:6276 1184:6277 1184:6278 1184:6279 1184:6280 1184:6281 1184:6284 1184:6285 1184:6286 1184:6287 1184:6288 1184:6289 1184:6290 1184:6291 1184:6292 1184:6293 1184:6294 1184:6295 1184:6296 1184:6297 1184:6298 1184:6299 1184:6300 1184:6301 1184:6302 1184:6303 1184:6304 1184:6305 1184:6306 1184:6307 1184:6308 1184:6309 1184:6310 1184:6311 1184:6312 1184:6313 1184:6314 1184:6316 1184:6317 1184:6318 1184:6319 1184:6320 1184:6321 1184:6322 1184:6325 1184:6326 1184:6327 1184:6328 1184:6329 1184:6330 1184:6333 1184:6334 1184:6335 1184:6336 1184:6337 1184:6338 1184:6339 1184:6340 1184:6341 1184:6342 1184:6343 1184:6344 1184:6345 1184:6346 1184:6347 1184:6348 1184:6349 1184:6350 1184:6351 1184:6352 1184:6353 1184:6354 1184:6355 1184:6356 1184:6357 1184:6358 1184:6359 1184:6362 1184:6363 1184:6364 1184:6365 1184:6366 1184:6367 1184:6370 1184:6371 1184:6372 1184:6373 1184:6374 1184:6378 1184:6379 1184:6380 1184:6381 1184:6382 1185:6384 1188:6388 1188:6389 1188:6391 1188:6392 1188:6393 1188:6573 1188:6574 1190:6395 1190:6396 1191:6397 1191:6398 1191:6399 1191:6465 1191:6565 1191:6566 1191:6567 1191:6568 1191:6570 1191:6571 1191:6572 1192:6400 1192:6401 1192:6402 1192:6403 1192:6404 1192:6405 1192:6407 1192:6409 1192:6410 1192:6411 1192:6412 1192:6415 1192:6416 1192:6417 1192:6418 1192:6419 1192:6420 1192:6421 1192:6422 1192:6423 1192:6424 1192:6425 1192:6426 1192:6427 1192:6428 1192:6429 1192:6430 1192:6431 1192:6432 1192:6433 1192:6434 1192:6435 1192:6436 1192:6437 1192:6438 1192:6439 1192:6440 1192:6441 1192:6442 1192:6443 1192:6444 1192:6447 1192:6448 1192:6449 1192:6450 1192:6451 1192:6454 1192:6455 1192:6456 1192:6457 1192:6458 1192:6459 1192:6460 1192:6461 1192:6462 1192:6463 1193:6466 1193:6467 1193:6468 1194:6535 1194:6559 1194:6560 1194:6561 1194:6562 1194:6563 1195:6470 1195:6471 1195:6472 1195:6473 1195:6474 1195:6475 1195:6477 1195:6479 1195:6480 1195:6481 1195:6482 1195:6485 1195:6486 1195:6487 1195:6488 1195:6489 1195:6490 1195:6491 1195:6492 1195:6493 1195:6494 1195:6495 1195:6496 1195:6497 1195:6498 1195:6499 1195:6500 1195:6501 1195:6502 1195:6503 1195:6504 1195:6505 1195:6506 1195:6507 1195:6508 1195:6509 1195:6510 1195:6511 1195:6512 1195:6513 1195:6514 1195:6517 1195:6518 1195:6519 1195:6520 1195:6521 1195:6524 1195:6525 1195:6526 1195:6527 1195:6528 1195:6529 1195:6530 1195:6531 1195:6532 1195:6533 1197:6536 1197:6537 1197:6538 1197:6539 1197:6540 1197:6541 1197:6542 1197:6544 1197:6545 1197:6546 1197:6548 1197:6549 1197:6550 1197:6551 1197:6552 1197:6553 1197:6554 1197:6555 1197:6556 1197:6557 1197:6558 1203:6121 1203:6123 1203:6124 1203:6125 1203:6133 1203:6250 1203:6251 1204:6126 1204:6135 1204:6136 1205:6127 1205:6138 1205:6139 1205:6140 1205:6141 1205:6142 1205:6143 1205:6144 1205:6145 1205:6244 1205:6245 1205:6246 1205:6247 1205:6248 1206:6146 1206:6147 1206:6148 1206:6149 1206:6151 1206:6152 1207:6128 1207:6156 1207:6157 1207:6158 1207:6159 1207:6160 1207:6161 1207:6162 1207:6163 1207:6164 1207:6165 1207:6166 1207:6167 1207:6168 1208:6224 1208:6236 1208:6237 1208:6238 1208:6239 1212:6170 1212:6171 1212:6172 1212:6173 1212:6174 1212:6175 1212:6177 1212:6178 1212:6180 1212:6181 1212:6182 1212:6183 1212:6184 1212:6185 1212:6186 1212:6187 1213:6129 1213:6130 1213:6188 1213:6189 1213:6190 1214:6191 1214:6192 1218:6131 1218:6194 1218:6195 1218:6196 1218:6197 1218:6198 1218:6199 1218:6200 1218:6209 1218:6210 1218:6211 1218:6212 1218:6213 1220:6215 1220:6216 1220:6217 1220:6219 1220:6221 1220:6222 1221:6218 1226:6132 1226:6225 1226:6226 1226:6227 1227:6228 1227:6229 1227:6230 1227:6231 1227:6233 1227:6234 1234:6576 1234:6578 1234:6579 1234:6580 1234:6586 1234:6646 1234:6647 1235:6581 1235:6588 1235:6589 1236:6582 1236:6583 1236:6590 1236:6591 1236:6592 1237:6594 1237:6595 1237:6596 1237:6597 1237:6611 1237:6612 1237:6613 1237:6614 1237:6615 1238:6584 1238:6598 1238:6599 1239:6600 1241:6585 1241:6618 1241:6619 1241:6620 1241:6621 1241:6622 1241:6632 1241:6633 1241:6634 1241:6635 1241:6636 1242:6638 1242:6639 1242:6640 1242:6641 1242:6643 1242:6644 1246:7027 1246:7029 1246:7030 1246:7031 1246:7032 1246:7153 1246:7154 1247:7034 1248:7036 1248:7037 1248:7038 1248:7039 1248:7040 1248:7041 1248:7042 1248:7043 1248:7044 1248:7045 1248:7046 1248:7047 1248:7048 1248:7049 1248:7050 1248:7051 1248:7052 1248:7053 1248:7054 1248:7055 1248:7056 1248:7057 1248:7058 1248:7059 1248:7060 1248:7061 1248:7062 1248:7063 1248:7064 1248:7065 1248:7066 1248:7067 1248:7068 1248:7077 1248:7078 1248:7079 1248:7080 1248:7081 1248:7083 1248:7084 1248:7085 1248:7086 1248:7087 1248:7089 1248:7090 1248:7091 1248:7092 1248:7093 1248:7094 1248:7095 1248:7096 1248:7097 1248:7098 1248:7099 1248:7100 1248:7101 1248:7102 1248:7103 1248:7104 1248:7105 1248:7106 1248:7107 1248:7108 1248:7109 1248:7110 1248:7111 1248:7112 1248:7113 1248:7114 1248:7115 1248:7116 1248:7117 1248:7118 1248:7119 1248:7120 1248:7121 1248:7130 1248:7131 1248:7132 1248:7133 1248:7134 1248:7136 1248:7137 1248:7138 1248:7139 1248:7141 1248:7142 1249:7143 1250:7144 1250:7145 1250:7146 1250:7147 1250:7149 1250:7150 1251:7152 1258:7156 1258:7158 1258:7159 1258:7160 1258:7170 1258:7172 1258:7389 1258:7390 1258:7391 1258:7392 1258:7393 1258:7394 1258:7395 1259:7161 1259:7173 1259:7174 1259:7175 1259:7176 1259:7177 1259:7178 1259:7179 1259:7180 1259:7181 1259:7182 1259:7183 1259:7184 1259:7185 1259:7186 1259:7187 1259:7188 1259:7189 1259:7190 1259:7191 1259:7192 1259:7193 1259:7194 1259:7195 1259:7196 1259:7197 1259:7198 1259:7199 1259:7200 1259:7201 1259:7202 1259:7203 1260:7162 1260:7205 1260:7206 1260:7207 1260:7208 1260:7209 1260:7210 1260:7211 1260:7212 1260:7367 1260:7368 1260:7369 1260:7370 1260:7371 1261:7213 1261:7214 1261:7215 1261:7216 1261:7218 1261:7219 1265:7163 1265:7164 1265:7223 1265:7224 1265:7225 1265:7226 1265:7227 1265:7228 1265:7229 1265:7230 1265:7231 1265:7232 1265:7233 1265:7234 1265:7236 1265:7237 1265:7238 1265:7239 1265:7240 1265:7256 1265:7257 1265:7258 1265:7259 1265:7260 1265:7262 1265:7263 1266:7347 1266:7359 1266:7360 1266:7361 1266:7362 1270:7265 1270:7266 1270:7267 1270:7268 1270:7269 1270:7270 1270:7272 1270:7273 1270:7275 1270:7276 1270:7277 1270:7278 1270:7279 1270:7280 1270:7281 1270:7282 1272:7283 1272:7284 1272:7285 1275:7165 1275:7286 1275:7287 1275:7288 1275:7289 1281:7166 1281:7291 1281:7292 1281:7293 1281:7294 1281:7295 1281:7296 1281:7298 1281:7299 1281:7301 1281:7302 1281:7303 1281:7304 1281:7305 1281:7306 1281:7307 1281:7308 1281:7309 1281:7310 1281:7311 1281:7313 1281:7314 1281:7315 1281:7316 1283:7167 1283:7320 1283:7321 1283:7322 1283:7323 1283:7324 1283:7333 1283:7334 1283:7335 1283:7336 1283:7337 1285:7339 1285:7340 1285:7341 1285:7342 1285:7344 1285:7345 1294:7168 1294:7348 1294:7349 1294:7350 1295:7351 1295:7352 1295:7353 1295:7354 1295:7356 1295:7357 1300:7169 1300:7375 1300:7376 1300:7377 1300:7378 1301:7379 1301:7380 1301:7381 1301:7382 1301:7384 1301:7385 1305:5273 1305:5275 1305:5276 1305:5277 1305:5280 1305:5329 1305:5330 1306:5283 1306:5314 1306:5315 1306:5316 1306:5317 1306:5318 1307:5278 1307:5279 1307:5284 1307:5285 1307:5286 1307:5287 1307:5288 1307:5289 1308:5290 1308:5291 1308:5292 1308:5293 1308:5294 1308:5295 1308:5296 1308:5297 1308:5298 1308:5299 1308:5300 1308:5301 1308:5302 1308:5303 1308:5305 1308:5306 1308:5307 1310:5320 1310:5321 1310:5322 1310:5323 1310:5325 1310:5326 1311:5328 1315:5086 1315:5088 1315:5089 1315:5090 1315:5093 1315:5143 1315:5144 1316:5096 1316:5128 1316:5129 1316:5130 1316:5131 1316:5132 1317:5091 1317:5092 1317:5097 1317:5098 1317:5099 1317:5100 1317:5101 1317:5102 1318:5103 1318:5104 1318:5105 1318:5106 1318:5107 1318:5108 1318:5109 1318:5110 1318:5111 1318:5112 1318:5113 1318:5114 1318:5115 1318:5116 1318:5118 1318:5119 1318:5120 1320:5134 1320:5135 1320:5136 1320:5137 1320:5139 1320:5140 1321:5142 1325:5815 1325:5817 1325:5818 1325:5819 1325:5829 1325:5860 1325:5889 1325:5918 1325:5947 1325:5980 1325:5994 1325:6006 1325:6007 1325:6008 1325:6009 1325:6010 1325:6011 1325:6012 1327:5831 1327:5832 1327:5833 1327:5834 1327:5835 1327:5836 1327:5838 1327:5840 1327:5841 1327:5842 1327:5843 1327:5844 1327:5845 1327:5846 1327:5847 1328:5820 1328:5821 1328:5848 1328:5849 1328:5850 1328:5851 1329:5852 1329:5853 1329:5854 1329:5855 1329:5857 1329:5858 1331:5861 1331:5862 1331:5863 1331:5864 1331:5865 1331:5866 1331:5867 1331:5869 1331:5871 1331:5872 1331:5873 1331:5874 1331:5875 1331:5876 1331:5877 1331:5878 1332:5822 1332:5879 1332:5880 1333:5881 1333:5882 1333:5883 1333:5884 1333:5886 1333:5887 1335:5890 1335:5891 1335:5892 1335:5893 1335:5894 1335:5895 1335:5896 1335:5898 1335:5900 1335:5901 1335:5902 1335:5903 1335:5904 1335:5905 1335:5906 1335:5907 1336:5823 1336:5908 1336:5909 1337:5910 1337:5911 1337:5912 1337:5913 1337:5915 1337:5916 1339:5919 1339:5920 1339:5921 1339:5922 1339:5923 1339:5924 1339:5925 1339:5927 1339:5929 1339:5930 1339:5931 1339:5932 1339:5933 1339:5934 1339:5935 1339:5936 1340:5824 1340:5937 1340:5938 1341:5939 1341:5940 1341:5941 1341:5942 1341:5944 1341:5945 1345:5948 1345:5949 1345:5950 1345:5951 1345:5952 1345:5953 1345:5954 1345:5956 1345:5958 1345:5959 1345:5960 1345:5961 1345:5962 1345:5963 1345:5964 1345:5965 1346:5825 1346:5966 1346:5967 1347:5826 1347:5969 1347:5970 1348:5971 1348:5972 1348:5973 1348:5974 1348:5976 1348:5977 1352:5827 1352:5981 1352:5982 1352:5983 1352:5984 1352:5985 1353:5986 1353:5987 1353:5988 1353:5989 1353:5991 1353:5992 1356:5828 1356:5995 1356:5996 1356:5997 1357:5998 1357:5999 1357:6000 1357:6001 1357:6003 1357:6004 1361:6014 1361:6016 1361:6017 1361:6018 1361:6051 1361:6080 1361:6113 1361:6114 1361:6115 1361:6116 1361:6117 1361:6118 1361:6119 1363:6024 1363:6025 1363:6026 1363:6027 1363:6028 1363:6029 1363:6031 1363:6033 1363:6034 1363:6035 1363:6036 1363:6037 1363:6038 1363:6039 1363:6040 1364:6019 1364:6041 1364:6042 1365:6043 1365:6044 1365:6045 1365:6046 1365:6048 1365:6049 1367:6052 1367:6053 1367:6054 1367:6055 1367:6056 1367:6057 1367:6058 1367:6060 1367:6062 1367:6063 1367:6064 1367:6065 1367:6066 1367:6067 1367:6068 1367:6069 1368:6020 1368:6070 1368:6071 1369:6072 1369:6073 1369:6074 1369:6075 1369:6077 1369:6078 1373:6081 1373:6082 1373:6083 1373:6084 1373:6085 1373:6086 1373:6087 1373:6089 1373:6091 1373:6092 1373:6093 1373:6094 1373:6095 1373:6096 1373:6097 1373:6098 1374:6021 1374:6099 1374:6100 1375:6022 1375:6102 1375:6103 1376:6104 1376:6105 1376:6106 1376:6107 1376:6109 1376:6110 1380:7716 1380:7718 1380:7719 1380:7720 1380:7724 1380:7791 1380:7792 1381:7726 1381:7727 1382:7729 1382:7730 1382:7731 1382:7732 1382:7733 1382:7734 1382:7736 1382:7738 1382:7739 1382:7740 1382:7741 1382:7742 1382:7743 1382:7744 1382:7745 1382:7768 1382:7772 1382:7773 1382:7774 1382:7775 1383:7721 1383:7722 1383:7746 1383:7747 1383:7749 1383:7750 1383:7751 1383:7752 1383:7753 1383:7754 1383:7755 1383:7762 1383:7763 1383:7764 1383:7765 1383:7766 1384:7723 1384:7769 1384:7770 1384:7771 1386:7778 1387:7779 1387:7780 1387:7781 1387:7785 1387:7787 1387:7788 1388:7782 1388:7790 1389:7783 1390:7784 1395:7794 1395:7795 1395:7797 1395:7798 1395:7799 1395:7863 1395:7864 1396:7806 1396:7807 1396:7808 1396:7809 1396:7810 1396:7818 1396:7819 1396:7820 1396:7821 1396:7822 1397:7800 1397:7801 1397:7825 1397:7826 1397:7827 1397:7828 1397:7829 1397:7830 1397:7831 1397:7832 1397:7833 1397:7834 1397:7835 1397:7856 1397:7857 1397:7858 1397:7859 1397:7860 1398:7836 1398:7837 1398:7862 1399:7802 1399:7803 1399:7841 1399:7842 1399:7843 1399:7844 1399:7845 1399:7846 1399:7847 1399:7848 1399:7849 1399:7850 1400:7851 1400:7852 1404:7866 1404:7867 1404:7868 1404:7870 1404:7871 1404:7872 1404:7897 1404:7898 1406:7874 1406:7875 1406:7876 1407:7875 1408:7877 1408:7878 1408:7879 1408:7880 1408:7881 1408:7882 1408:7889 1408:7890 1408:7891 1408:7892 1408:7894 1408:7895 1408:7896 1409:7883 1409:7884 1410:7886 1410:7887 1410:7888 1411:7887 1415:7593 1415:7595 1415:7596 1415:7597 1415:7648 1415:7649 1417:7599 1417:7600 1417:7601 1417:7602 1417:7603 1417:7604 1417:7605 1417:7606 1417:7607 1417:7608 1417:7609 1417:7610 1417:7611 1417:7612 1417:7613 1417:7614 1417:7615 1417:7616 1417:7617 1417:7618 1417:7619 1417:7622 1417:7623 1417:7624 1417:7625 1417:7626 1417:7627 1417:7630 1417:7631 1417:7632 1417:7633 1417:7634 1417:7635 1417:7636 1417:7637 1417:7638 1417:7639 1417:7640 1417:7641 1417:7642 1417:7643 1417:7644 1417:7645 1417:7646 1419:7647 1420:7953 1420:7954 1420:7955 1420:7957 1420:7958 1420:7959 1420:8008 1420:8009 1422:7960 1422:7964 1422:7965 1422:7966 1422:7967 1422:7969 1422:7970 1422:7971 1422:7972 1423:7975 1423:7976 1424:7977 1424:7978 1424:7979 1424:7980 1424:7981 1424:7982 1424:8000 1424:8001 1424:8002 1424:8003 1424:8005 1424:8006 1424:8007 1425:7983 1425:7984 1426:7961 1426:7987 1426:7988 1426:7989 1426:7990 1426:7992 1426:7993 1426:7994 1426:7995 1427:7998 1427:7999 1431:7651 1431:7653 1431:7654 1431:7655 1431:7658 1431:7713 1431:7714 1433:7656 1433:7660 1433:7661 1434:7657 1434:7663 1434:7664 1434:7665 1434:7666 1434:7667 1434:7668 1434:7669 1434:7670 1434:7671 1434:7672 1434:7673 1434:7674 1434:7675 1434:7676 1434:7683 1434:7684 1434:7685 1434:7686 1434:7687 1435:7689 1435:7690 1435:7691 1435:7692 1435:7693 1435:7694 1435:7695 1435:7696 1436:7697 1436:7698 1436:7699 1436:7700 1436:7701 1437:7702 1437:7703 1438:7704 1438:7705 1438:7706 1438:7707 1438:7709 1438:7710 1439:7712 1449:2246 1449:2254 1449:2255 1449:2256 1449:2258 1449:2259 1449:2260 1449:2268 1449:2281 1449:2387 1449:2388 1449:2389 1449:2390 1449:2392 1449:2393 1450:2247 1450:2269 1451:2248 1451:2270 1452:2249 1452:2271 1453:2250 1453:2272 1454:2251 1454:2273 1455:2252 1455:2274 1456:2253 1456:2275 1458:2277 1458:2278 1458:2279 1458:2280 1462:2261 1462:2262 1462:2282 1462:2284 1462:2285 1462:2286 1462:2287 1462:2288 1462:2289 1462:2290 1462:2304 1462:2305 1462:2306 1462:2307 1462:2308 1463:2263 1463:2264 1463:2293 1463:2294 1463:2295 1463:2296 1463:2297 1463:2298 1463:2299 1463:2300 1467:2265 1467:2310 1467:2311 1467:2312 1467:2313 1473:2266 1473:2315 1473:2316 1473:2317 1473:2318 1473:2319 1473:2320 1473:2322 1473:2323 1473:2325 1473:2326 1473:2327 1473:2328 1473:2329 1473:2330 1473:2331 1473:2332 1473:2333 1473:2334 1473:2335 1473:2337 1473:2338 1473:2339 1473:2340 1481:2267 1481:2344 1481:2345 1481:2346 1481:2347 1481:2348 1481:2349 1481:2351 1481:2352 1481:2354 1481:2355 1481:2356 1481:2357 1481:2358 1481:2359 1481:2360 1481:2361 1481:2363 1481:2364 1481:2365 1481:2367 1481:2369 1481:2370 1481:2371 1481:2372 1483:2375 1483:2376 1483:2377 1483:2381 1483:2383 1483:2384 1484:2378 1484:2386 1485:2379 1493:7516 1493:7519 1493:7520 1493:7521 1493:7523 1493:7524 1493:7525 1493:7531 1493:7590 1493:7591 1494:7517 1494:7532 1495:7518 1495:7533 1496:7534 1497:7535 1499:7526 1499:7527 1499:7537 1499:7538 1499:7539 1499:7540 1502:7528 1502:7541 1502:7542 1502:7543 1502:7544 1508:7529 1508:7546 1508:7547 1508:7548 1508:7549 1508:7550 1508:7551 1508:7553 1508:7554 1508:7556 1508:7557 1508:7558 1508:7559 1508:7560 1508:7561 1508:7562 1508:7563 1508:7564 1508:7565 1508:7566 1508:7568 1508:7569 1508:7570 1508:7571 1508:7574 1513:7575 1513:7576 1515:7530 1515:7578 1515:7579 1516:7580 1516:7581 1516:7582 1516:7584 1516:7586 1516:7587 1517:7589 1524:7900 1524:7904 1524:7905 1524:7906 1524:7908 1524:7909 1524:7910 1524:7950 1524:7951 1525:7901 1526:7902 1526:7911 1526:7914 1526:7915 1527:7903 1528:7912 1528:7917 1528:7918 1528:7919 1528:7920 1528:7921 1528:7936 1528:7937 1528:7938 1528:7939 1528:7940 1529:7942 1529:7943 1529:7944 1529:7945 1529:7947 1529:7948 1533:2599 1533:2600 1533:2601 1533:2602 1533:2604 1533:2605 1533:2606 1533:2608 1533:2620 1533:2621 1535:2607 1535:2610 1535:2611 1536:2612 1536:2613 1536:2614 1536:2615 1536:2617 1536:2618 1539:8322 1539:8324 1539:8325 1539:8326 1539:8333 1539:8334 1540:8328 1540:8329 1540:8330 1540:8331 1542:8332 1547:3771 1547:3775 1547:3776 1547:3777 1547:3779 1547:3780 1547:3781 1547:3813 1547:3814 1548:3772 1548:3783 1548:3784 1548:3785 1548:3786 1548:3788 1548:3789 1549:3773 1549:3791 1549:3792 1549:3793 1549:3805 1549:3806 1549:3807 1549:3808 1549:3810 1549:3811 1549:3812 1550:3774 1552:3794 1552:3795 1553:3796 1554:3797 1554:3798 1554:3799 1554:3800 1554:3802 1554:3803 1560:2670 1560:2671 1560:2673 1560:2674 1560:2675 1560:2685 1560:2686 1561:2677 1561:2678 1561:2679 1561:2680 1561:2681 1561:2682 1561:2683 1561:2684 1612:7471 1612:7473 1612:7474 1612:7475 1612:7501 1612:7502 1613:7477 1613:7478 1613:7479 1613:7480 1613:7481 1613:7482 1613:7483 1613:7484 1613:7485 1613:7486 1613:7487 1613:7488 1613:7489 1613:7490 1613:7491 1613:7492 1613:7493 1613:7494 1613:7495 1613:7496 1613:7498 1613:7499 1613:7500 1623:7397 1623:7404 1623:7406 1623:7407 1623:7408 1623:7409 1623:7468 1623:7469 1624:7398 1625:7399 1625:7412 1625:7453 1625:7454 1625:7455 1625:7456 1625:7457 1626:7400 1626:7413 1626:7414 1626:7415 1626:7416 1626:7417 1626:7418 1626:7419 1626:7420 1626:7421 1626:7422 1626:7423 1626:7424 1626:7425 1626:7426 1626:7427 1626:7428 1626:7429 1627:7401 1627:7430 1627:7431 1627:7432 1627:7433 1627:7434 1627:7435 1627:7438 1627:7439 1627:7440 1627:7441 1627:7443 1627:7444 1628:7402 1628:7436 1628:7437 1629:7403 1631:7459 1631:7460 1631:7461 1631:7462 1631:7464 1631:7465 1632:7467 1636:8377 1636:8378 1636:8380 1636:8381 1636:8382 1636:8388 1636:8462 1636:8463 1639:8383 1639:8390 1639:8391 1640:8396 1640:8398 1640:8399 1640:8400 1640:8401 1641:8384 1641:8393 1641:8394 1641:8395 1647:8405 1647:8406 1647:8407 1647:8408 1647:8409 1647:8410 1647:8418 1647:8419 1647:8420 1647:8421 1647:8422 1649:8385 1649:8386 1649:8424 1649:8425 1649:8426 1652:8387 1652:8428 1652:8429 1652:8430 1652:8431 1652:8432 1652:8442 1652:8443 1652:8444 1652:8445 1652:8446 1655:8448 1655:8449 1655:8457 1655:8459 1655:8460 1656:8451 1657:8452 1658:8453 1659:8454 1660:8455 1676:8465 1676:8467 1676:8468 1676:8469 1676:8470 1676:8512 1676:8513 1679:8472 1679:8473 1679:8474 1679:8475 1679:8492 1679:8496 1679:8497 1679:8498 1679:8499 1679:8500 1679:8501 1679:8502 1680:8493 1680:8494 1680:8495 1681:8476 1681:8477 1681:8478 1681:8479 1681:8480 1681:8481 1681:8482 1682:8485 1682:8486 1682:8487 1682:8488 1682:8489 1684:8503 1684:8504 1684:8505 1684:8506 1684:8508 1684:8509 1685:8511 1693:8515 1693:8520 1693:8521 1693:8522 1693:8524 1693:8525 1693:8526 1693:8553 1693:8558 1693:8561 1693:8562 1693:8563 1693:8564 1693:8566 1693:8567 1694:8516 1694:8528 1694:8529 1694:8530 1694:8531 1694:8532 1694:8533 1694:8535 1694:8536 1694:8537 1694:8539 1694:8540 1694:8541 1694:8542 1694:8543 1694:8544 1694:8545 1694:8546 1694:8560 1695:8517 1695:8547 1695:8548 1695:8549 1695:8550 1695:8551 1696:8518 1697:8519 1697:8552 1697:8554 1697:8555 1697:8556 1697:8557 1703:8592 1703:8593 1703:8595 1703:8596 1703:8597 1703:8605 1703:8606 1705:8599 1705:8600 1705:8601 1705:8602 1705:8603 1705:8604 1709:8608 1709:8609 1709:8611 1709:8612 1709:8613 1709:8616 1709:8629 1709:8630 1710:8614 1710:8615 1710:8618 1710:8619 1710:8620 1711:8621 1711:8622 1711:8623 1711:8624 1711:8626 1711:8627 1726:7504 1726:7506 1726:7507 1726:7508 1726:7513 1726:7514 1727:7510 1727:7511 1727:7512 1731:8296 1731:8297 1731:8299 1731:8300 1731:8301 1731:8303 1731:8319 1731:8320 1732:8305 1732:8306 1734:8302 1734:8307 1734:8308 1735:8309 1736:8310 1736:8311 1736:8312 1736:8313 1736:8315 1736:8316 1737:8318 1741:1422 1741:1423 1741:1424 1741:1425 1741:1427 1741:1428 1741:1429 1741:1606 1741:1607 1743:1432 1743:1433 1743:1434 1743:1435 1743:1436 1743:1437 1743:1438 1743:1439 1743:1440 1743:1441 1743:1442 1743:1443 1743:1444 1743:1445 1743:1446 1743:1447 1743:1448 1743:1449 1743:1450 1743:1451 1743:1452 1743:1453 1743:1454 1743:1455 1743:1456 1743:1457 1743:1458 1743:1459 1743:1460 1743:1461 1743:1462 1743:1463 1743:1464 1743:1465 1743:1466 1743:1467 1743:1468 1743:1469 1743:1470 1743:1471 1743:1472 1743:1473 1743:1474 1743:1475 1743:1476 1743:1477 1743:1478 1743:1479 1743:1480 1743:1481 1743:1482 1743:1483 1743:1484 1743:1485 1743:1486 1743:1487 1743:1488 1743:1489 1743:1490 1743:1491 1743:1492 1743:1493 1743:1494 1743:1495 1743:1496 1743:1506 1743:1507 1743:1508 1743:1509 1743:1510 1743:1512 1743:1513 1743:1514 1743:1515 1743:1516 1743:1518 1743:1519 1743:1520 1743:1521 1743:1522 1743:1523 1743:1524 1743:1525 1743:1526 1743:1527 1743:1528 1743:1529 1743:1530 1743:1531 1743:1532 1743:1533 1743:1534 1743:1535 1743:1536 1743:1537 1743:1538 1743:1539 1743:1540 1743:1541 1743:1542 1743:1543 1743:1544 1743:1545 1743:1546 1743:1547 1743:1548 1743:1549 1743:1550 1743:1551 1743:1552 1743:1553 1743:1554 1743:1555 1743:1556 1743:1557 1743:1558 1743:1559 1743:1560 1743:1561 1743:1562 1743:1563 1743:1564 1743:1565 1743:1566 1743:1567 1743:1568 1743:1569 1743:1570 1743:1571 1743:1572 1743:1573 1743:1574 1743:1575 1743:1576 1743:1577 1743:1578 1743:1579 1743:1580 1743:1581 1743:1582 1743:1592 1743:1593 1743:1594 1743:1595 1743:1596 1743:1598 1743:1599 1743:1600 1743:1601 1743:1603 1743:1604 1743:1605 1750:8632 1750:8636 1750:8638 1750:8639 1750:8640 1750:8643 1750:8661 1750:8662 1751:8633 1751:8645 1751:8646 1752:8634 1752:8641 1752:8647 1752:8648 1753:8635 1753:8642 1753:8649 1753:8650 1754:8651 1755:8652 1755:8653 1755:8654 1755:8655 1755:8657 1755:8658 1756:8660 1762:8569 1762:8573 1762:8575 1762:8576 1762:8577 1762:8578 1762:8589 1762:8590 1763:8570 1763:8580 1763:8581 1763:8582 1763:8583 1763:8585 1763:8586 1764:8571 1764:8588 1765:8572 1771:8664 1771:8669 1771:8671 1771:8672 1771:8673 1771:8676 1771:8697 1771:8698 1772:8665 1772:8678 1772:8679 1773:8666 1773:8674 1773:8680 1773:8681 1774:8667 1774:8675 1774:8682 1774:8683 1775:8668 1775:8684 1776:8685 1776:8686 1776:8691 1776:8693 1776:8694 1777:8688 1777:8696 1778:8689 1786:863 1786:867 1786:868 1786:869 1786:871 1786:872 1786:873 1786:888 1786:890 1786:1146 1786:1167 1786:1189 1786:1211 1786:1272 1786:1278 1786:1301 1786:1308 1786:1327 1786:1328 1786:1329 1786:1330 1786:1331 1786:1332 1786:1333 1787:864 1788:865 1789:866 1790:1147 1790:1148 1790:1149 1790:1150 1790:1151 1790:1152 1790:1154 1790:1156 1790:1157 1790:1158 1790:1159 1790:1160 1790:1161 1790:1162 1790:1163 1791:1164 1791:1165 1791:1166 1793:1168 1793:1169 1793:1170 1793:1171 1793:1172 1793:1173 1793:1174 1793:1176 1793:1178 1793:1179 1793:1180 1793:1181 1793:1182 1793:1183 1793:1184 1793:1185 1794:1186 1794:1187 1794:1188 1800:1190 1800:1191 1800:1192 1800:1193 1800:1194 1800:1195 1800:1196 1800:1198 1800:1200 1800:1201 1800:1202 1800:1203 1800:1204 1800:1205 1800:1206 1800:1207 1801:1208 1801:1209 1801:1210 1806:1212 1806:1213 1806:1214 1806:1215 1806:1216 1806:1217 1806:1218 1806:1220 1806:1221 1806:1223 1806:1224 1806:1225 1806:1226 1806:1227 1806:1228 1806:1229 1806:1230 1807:874 1807:1231 1807:1232 1808:1233 1808:1234 1808:1235 1808:1236 1808:1238 1808:1239 1809:1242 1809:1243 1809:1244 1809:1245 1809:1246 1809:1247 1809:1249 1809:1251 1809:1252 1809:1253 1809:1254 1809:1255 1809:1256 1809:1257 1809:1258 1809:1259 1809:1260 1809:1261 1809:1265 1809:1266 1809:1267 1809:1268 1810:1262 1810:1263 1810:1264 1810:1271 1817:875 1817:1273 1817:1274 1817:1275 1817:1276 1817:1277 1821:876 1821:877 1821:891 1821:892 1821:893 1821:894 1821:895 1821:896 1821:897 1821:898 1821:899 1821:900 1822:959 1822:961 1822:962 1822:963 1822:964 1830:902 1830:903 1830:904 1830:905 1830:906 1830:907 1830:910 1830:911 1830:912 1830:913 1830:914 1830:921 1830:922 1830:923 1830:924 1830:925 1830:927 1830:929 1830:930 1830:931 1830:932 1830:933 1830:934 1830:935 1830:936 1831:938 1831:939 1831:940 1831:941 1831:942 1831:949 1831:950 1831:951 1831:952 1831:953 1832:878 1832:955 1832:956 1832:957 1832:958 1834:967 1834:968 1834:969 1834:970 1834:972 1834:973 1835:975 1837:978 1837:979 1837:980 1837:981 1837:982 1840:879 1840:985 1840:986 1840:987 1840:988 1840:989 1840:990 1840:991 1840:992 1841:880 1841:881 1841:882 1841:994 1841:995 1841:996 1841:997 1841:998 1841:999 1841:1002 1841:1003 1841:1004 1841:1005 1841:1006 1841:1007 1841:1008 1841:1009 1841:1010 1841:1011 1841:1012 1841:1013 1841:1014 1841:1015 1841:1016 1841:1017 1841:1018 1841:1019 1841:1020 1841:1021 1841:1022 1841:1023 1841:1024 1841:1025 1841:1026 1841:1027 1841:1028 1841:1029 1841:1030 1841:1031 1841:1032 1841:1033 1841:1034 1841:1035 1841:1036 1841:1037 1841:1038 1841:1039 1841:1040 1841:1041 1841:1042 1841:1043 1841:1044 1841:1045 1841:1046 1841:1047 1841:1048 1841:1049 1841:1050 1841:1051 1841:1052 1841:1053 1841:1054 1841:1055 1841:1056 1841:1057 1841:1058 1841:1059 1841:1060 1841:1061 1841:1062 1841:1063 1841:1064 1841:1065 1841:1068 1841:1069 1841:1070 1841:1071 1841:1072 1842:1074 1842:1075 1842:1082 1842:1084 1842:1085 1843:1077 1843:1087 1844:1078 1845:1079 1846:1080 1855:1279 1855:1280 1855:1281 1855:1282 1855:1283 1855:1284 1855:1285 1855:1287 1855:1288 1855:1290 1855:1291 1855:1292 1855:1293 1855:1294 1855:1295 1855:1296 1855:1297 1855:1298 1855:1299 1855:1300 1858:883 1858:1302 1858:1303 1858:1304 1858:1305 1858:1306 1858:1307 1861:884 1861:1090 1861:1091 1861:1092 1861:1093 1861:1094 1861:1095 1861:1096 1861:1097 1861:1098 1861:1099 1862:885 1862:1100 1862:1101 1862:1102 1862:1103 1862:1104 1862:1105 1862:1109 1862:1110 1862:1111 1862:1112 1862:1114 1862:1115 1864:1106 1864:1107 1865:1116 1866:1117 1866:1118 1866:1119 1866:1120 1866:1122 1866:1123 1867:1125 1869:1128 1869:1129 1869:1130 1869:1131 1869:1132 1872:886 1872:887 1872:1309 1872:1310 1872:1311 1872:1312 1872:1313 1872:1314 1872:1315 1872:1316 1872:1317 1873:1318 1873:1319 1873:1320 1873:1321 1873:1323 1873:1324 1874:1326 1880:1135 1880:1136 1880:1137 1880:1138 1880:1139 1880:1140 1880:1141 1880:1142 1880:1143 1883:8850 1883:8852 1883:8853 1883:8854 1883:8860 1883:9067 1883:9068 1884:8862 1885:8863 1886:8855 1886:8865 1886:8866 1886:8867 1886:8868 1886:8869 1886:8870 1886:8872 1886:8873 1886:8874 1886:8875 1886:8878 1886:8879 1886:8880 1886:8881 1886:8882 1886:8883 1886:8884 1886:8885 1886:8886 1886:8887 1886:8888 1886:8889 1886:8890 1886:8891 1886:8892 1886:8893 1886:8894 1886:8895 1886:8896 1886:8897 1886:8898 1886:8899 1886:8900 1886:8901 1886:8902 1886:8903 1886:8904 1886:8905 1886:8906 1886:8907 1886:8908 1886:8909 1886:8910 1886:8911 1886:8912 1886:8913 1886:8914 1886:8915 1886:8916 1886:8917 1886:8918 1886:8919 1886:8920 1886:8921 1886:8922 1886:8923 1886:8924 1886:8925 1886:8926 1886:8927 1886:8928 1886:8929 1886:8930 1886:8932 1886:8933 1886:8937 1886:8938 1886:8939 1886:8940 1886:8941 1886:8943 1886:8944 1886:8945 1886:8946 1886:8947 1886:8948 1886:8949 1886:8950 1886:8951 1886:8952 1886:8953 1886:8957 1886:8958 1886:8959 1886:8960 1893:8856 1893:8954 1893:8955 1893:8956 1895:8963 1895:8964 1896:8857 1896:8858 1896:8859 1896:8966 1896:8967 1896:8968 1896:8969 1896:8970 1896:8971 1896:8974 1896:8975 1896:8976 1896:8977 1896:8978 1896:8979 1896:8980 1896:8981 1896:8982 1896:8983 1896:8984 1896:8985 1896:8986 1896:8987 1896:8988 1896:8989 1896:8990 1896:8991 1896:8992 1896:8993 1896:8994 1896:8995 1896:8996 1896:8997 1896:8998 1896:8999 1896:9000 1896:9001 1896:9002 1896:9003 1896:9004 1896:9005 1896:9006 1896:9007 1896:9008 1896:9009 1896:9010 1896:9011 1896:9012 1896:9013 1896:9014 1896:9015 1896:9016 1896:9017 1896:9018 1896:9019 1896:9020 1896:9021 1896:9022 1896:9023 1896:9024 1896:9025 1896:9026 1896:9027 1896:9028 1896:9029 1896:9030 1896:9031 1896:9032 1896:9033 1896:9034 1896:9035 1896:9036 1896:9037 1896:9040 1896:9041 1896:9042 1896:9043 1896:9044 1897:9046 1897:9047 1897:9061 1897:9063 1897:9064 1898:9049 1898:9066 1899:9050 1900:9051 1901:9052 1902:9053 1903:9054 1904:9055 1905:9056 1906:9057 1907:9058 1908:9059 1913:9480 1913:9482 1913:9483 1913:9484 1913:9485 1913:9590 1913:9591 1917:9488 1917:9489 1917:9490 1917:9491 1917:9492 1917:9493 1917:9494 1917:9495 1917:9496 1917:9497 1917:9498 1917:9499 1917:9500 1917:9501 1917:9502 1917:9503 1917:9504 1917:9505 1917:9506 1917:9507 1917:9508 1917:9509 1917:9510 1917:9511 1917:9512 1917:9513 1917:9514 1917:9515 1917:9516 1917:9517 1917:9518 1917:9519 1917:9520 1917:9521 1917:9522 1917:9523 1917:9524 1917:9525 1917:9526 1917:9527 1917:9528 1917:9529 1917:9530 1917:9531 1917:9532 1917:9533 1917:9534 1917:9535 1917:9536 1917:9537 1917:9538 1917:9539 1917:9540 1917:9541 1917:9542 1917:9543 1917:9553 1917:9554 1917:9555 1917:9556 1917:9557 1918:9546 1918:9547 1918:9548 1918:9549 1920:9560 1920:9561 1920:9562 1920:9567 1920:9573 1920:9574 1920:9575 1920:9576 1920:9578 1920:9579 1920:9580 1921:9563 1921:9564 1921:9565 1921:9566 1922:9568 1922:9569 1922:9570 1922:9571 1924:9581 1924:9582 1924:9583 1924:9584 1924:9586 1924:9587 1925:9589 1935:9593 1935:9595 1935:9596 1935:9597 1935:9684 1935:9685 1936:9605 1936:9606 1936:9607 1936:9608 1936:9609 1936:9610 1936:9612 1936:9614 1936:9615 1936:9616 1936:9617 1936:9618 1936:9619 1936:9620 1936:9621 1936:9625 1936:9631 1936:9632 1936:9633 1936:9634 1937:9598 1937:9622 1937:9623 1937:9624 1938:9626 1938:9627 1938:9628 1938:9629 1938:9630 1940:9638 1940:9677 1940:9678 1940:9679 1940:9680 1940:9681 1941:9599 1941:9600 1941:9639 1941:9640 1941:9641 1941:9642 1941:9643 1941:9644 1941:9645 1941:9646 1941:9683 1942:9648 1942:9649 1944:9652 1944:9653 1944:9654 1944:9655 1945:9656 1946:9657 1947:9658 1948:9659 1949:9660 1950:9661 1951:9662 1952:9663 1954:9601 1954:9602 1954:9666 1954:9667 1954:9668 1954:9669 1954:9670 1954:9671 1955:9673 1955:9674 1962:8808 1962:8811 1962:8813 1962:8814 1962:8815 1962:8837 1962:8842 1962:8843 1962:8844 1962:8845 1962:8847 1962:8848 1963:8809 1963:8817 1963:8818 1963:8819 1963:8820 1963:8821 1963:8822 1963:8824 1963:8826 1963:8827 1963:8828 1963:8829 1963:8830 1963:8831 1963:8832 1963:8833 1964:8810 1964:8834 1964:8835 1964:8836 1966:8838 1966:8839 1966:8840 1966:8841 1973:9231 1973:9235 1973:9237 1973:9238 1973:9239 1973:9248 1973:9250 1973:9472 1973:9473 1973:9474 1973:9475 1973:9476 1973:9477 1973:9478 1974:9232 1975:9233 1976:9234 1976:9251 1976:9252 1976:9253 1977:9240 1977:9255 1977:9256 1977:9257 1977:9258 1977:9259 1977:9260 1977:9261 1977:9262 1977:9263 1977:9264 1977:9265 1977:9266 1977:9267 1977:9268 1977:9269 1977:9270 1977:9271 1977:9272 1977:9273 1977:9274 1977:9275 1977:9276 1977:9277 1977:9278 1977:9279 1977:9280 1977:9281 1977:9282 1977:9283 1977:9284 1977:9285 1977:9286 1977:9287 1977:9288 1977:9289 1977:9290 1977:9291 1977:9307 1977:9308 1977:9309 1977:9310 1977:9311 1978:9313 1978:9314 1978:9315 1978:9316 1978:9318 1978:9319 1979:9321 1983:9324 1983:9325 1983:9326 1984:9241 1984:9242 1984:9328 1984:9329 1984:9330 1984:9331 1984:9332 1984:9333 1984:9349 1984:9350 1984:9351 1984:9352 1984:9353 1985:9355 1985:9356 1985:9357 1985:9358 1985:9360 1985:9361 1986:9363 1987:9366 1987:9367 1987:9368 1988:9243 1988:9244 1988:9370 1988:9371 1988:9372 1988:9373 1988:9374 1988:9375 1988:9391 1988:9392 1988:9393 1988:9394 1988:9395 1989:9397 1989:9398 1989:9399 1989:9400 1989:9402 1989:9403 1990:9405 1992:9245 1992:9408 1992:9409 1992:9410 1992:9411 1992:9412 1993:9413 1993:9414 1993:9415 1993:9416 1993:9418 1993:9419 1994:9421 2002:9246 2002:9424 2002:9425 2002:9426 2002:9427 2002:9428 2003:9453 2003:9455 2003:9456 2003:9457 2003:9458 2004:9430 2004:9432 2004:9433 2004:9434 2004:9435 2004:9436 2004:9445 2004:9446 2004:9447 2004:9448 2004:9449 2005:9439 2005:9440 2005:9441 2005:9442 2007:9247 2007:9451 2007:9452 2009:9461 2009:9462 2009:9463 2009:9464 2009:9466 2009:9467 2010:9469 2014:8700 2014:8701 2014:8703 2014:8704 2014:8705 2014:8722 2014:8723 2015:8706 2015:8707 2015:8709 2015:8710 2015:8711 2015:8712 2015:8713 2015:8714 2015:8715 2015:8716 2015:8717 2015:8718 2015:8720 2017:8721 2027:8725 2027:8732 2027:8733 2027:8734 2027:8736 2027:8737 2027:8738 2027:8740 2027:8782 2027:8783 2028:8726 2029:8727 2030:8728 2030:8743 2030:8744 2030:8745 2030:8746 2030:8747 2030:8748 2030:8750 2030:8752 2030:8753 2030:8754 2030:8755 2030:8756 2030:8757 2030:8758 2030:8759 2030:8762 2030:8764 2030:8765 2030:8766 2030:8767 2031:8729 2031:8760 2031:8761 2032:8730 2033:8731 2033:8739 2033:8770 2033:8771 2033:8772 2034:8773 2034:8774 2034:8775 2034:8776 2034:8778 2034:8779 2035:8781 2037:8336 2037:8338 2037:8339 2037:8340 2037:8343 2037:8374 2037:8375 2041:8341 2041:8345 2041:8346 2041:8347 2042:8348 2042:8349 2043:8365 2043:8367 2043:8368 2043:8369 2043:8370 2044:8373 2046:8342 2046:8352 2046:8353 2046:8354 2047:8355 2047:8356 2047:8360 2047:8362 2047:8363 2048:8358 2069:9969 2069:9985 2069:9986 2069:9987 2069:9989 2069:9990 2069:9991 2069:10037 2069:10050 2069:10061 2069:10062 2069:10063 2069:10064 2069:10066 2069:10067 2070:9970 2071:9971 2071:9993 2071:9994 2071:9995 2071:9996 2071:9997 2071:9998 2071:10000 2071:10001 2071:10002 2071:10003 2071:10004 2071:10005 2071:10006 2071:10007 2071:10008 2071:10009 2071:10012 2071:10013 2071:10014 2071:10015 2071:10016 2071:10017 2071:10018 2071:10019 2072:9972 2073:9973 2073:10028 2073:10030 2073:10031 2073:10032 2073:10033 2074:9974 2074:10021 2074:10022 2074:10023 2074:10036 2075:9975 2075:10024 2076:9976 2076:10025 2077:9977 2078:9978 2079:9979 2080:9980 2081:9981 2082:9982 2083:9983 2084:9984 2087:10038 2087:10039 2087:10040 2088:10041 2089:10042 2090:10043 2091:10044 2092:10045 2093:10046 2097:10049 2101:10051 2101:10052 2101:10053 2102:10054 2103:10055 2104:10056 2105:10057 2109:10060 2110:9883 2110:9884 2110:9886 2110:9887 2110:9888 2110:9966 2110:9967 2112:9891 2112:9892 2112:9893 2112:9894 2112:9896 2112:9897 2112:9898 2112:9899 2112:9900 2112:9901 2112:9902 2112:9905 2112:9906 2112:9907 2112:9908 2112:9909 2112:9910 2112:9913 2112:9914 2112:9915 2112:9916 2112:9917 2112:9959 2112:9960 2112:9961 2112:9962 2112:9963 2113:9921 2113:9922 2113:9923 2113:9924 2113:9926 2113:9927 2113:9928 2113:9929 2113:9930 2113:9931 2113:9932 2113:9935 2113:9936 2113:9937 2113:9938 2113:9939 2113:9940 2113:9943 2113:9944 2113:9945 2113:9946 2113:9947 2113:9948 2113:9951 2113:9952 2113:9953 2113:9954 2113:9955 2113:9965 2119:9139 2119:9141 2119:9142 2119:9143 2119:9144 2119:9172 2119:9173 2120:9147 2120:9148 2120:9149 2120:9153 2120:9154 2120:9155 2120:9156 2120:9158 2120:9159 2120:9160 2128:9150 2128:9151 2128:9152 2130:9161 2130:9162 2131:9163 2131:9164 2131:9165 2131:9166 2131:9168 2131:9169 2132:9171 2134:10191 2134:10193 2134:10194 2134:10195 2134:10226 2134:10227 2135:10198 2135:10199 2135:10200 2135:10201 2135:10202 2135:10203 2135:10204 2135:10205 2135:10206 2135:10209 2135:10210 2135:10211 2135:10212 2135:10213 2135:10214 2135:10217 2135:10218 2135:10219 2135:10220 2135:10221 2135:10223 2135:10224 2137:10225 2138:10229 2138:10231 2138:10232 2138:10233 2138:10234 2138:10341 2138:10342 2139:10236 2139:10237 2139:10238 2139:10239 2139:10240 2139:10241 2139:10242 2139:10244 2139:10245 2139:10246 2139:10247 2139:10248 2139:10249 2139:10250 2139:10251 2139:10252 2139:10253 2139:10254 2139:10255 2139:10256 2139:10257 2139:10258 2139:10259 2139:10260 2139:10261 2139:10262 2139:10263 2139:10264 2139:10265 2139:10266 2139:10267 2139:10268 2139:10269 2139:10270 2139:10271 2139:10272 2139:10273 2139:10274 2139:10275 2139:10276 2139:10277 2139:10278 2139:10279 2139:10280 2139:10281 2139:10282 2139:10283 2139:10284 2139:10285 2139:10286 2139:10287 2139:10288 2139:10289 2139:10290 2139:10291 2139:10292 2139:10293 2139:10294 2139:10295 2139:10296 2139:10297 2139:10298 2139:10299 2139:10300 2139:10301 2139:10302 2139:10303 2139:10304 2139:10305 2139:10306 2139:10307 2139:10308 2139:10319 2139:10320 2139:10321 2139:10322 2139:10323 2139:10325 2139:10326 2139:10327 2139:10328 2139:10330 2139:10331 2140:10332 2140:10333 2140:10334 2140:10335 2140:10337 2140:10338 2141:10340 2144:10344 2144:10346 2144:10347 2144:10348 2144:10349 2144:10371 2144:10451 2144:10452 2144:10453 2144:10454 2144:10456 2144:10457 2146:10351 2146:10352 2146:10353 2146:10354 2146:10355 2146:10356 2146:10358 2146:10360 2146:10361 2146:10362 2146:10363 2146:10364 2146:10365 2146:10366 2146:10367 2146:10368 2146:10369 2146:10370 2148:10372 2148:10374 2148:10375 2148:10376 2148:10377 2148:10378 2148:10379 2148:10380 2148:10381 2148:10382 2148:10383 2148:10384 2148:10385 2148:10386 2148:10387 2148:10388 2148:10389 2148:10390 2148:10391 2148:10392 2148:10393 2148:10394 2148:10395 2148:10396 2148:10397 2148:10398 2148:10399 2148:10400 2148:10401 2148:10402 2148:10403 2148:10404 2148:10405 2148:10406 2148:10407 2148:10408 2148:10409 2148:10410 2148:10411 2148:10412 2148:10413 2148:10414 2148:10415 2148:10416 2148:10417 2148:10418 2148:10419 2148:10420 2148:10421 2148:10422 2148:10423 2148:10424 2148:10425 2148:10426 2148:10427 2148:10428 2148:10429 2148:10436 2148:10437 2148:10438 2148:10439 2148:10440 2149:10442 2149:10443 2149:10444 2149:10445 2149:10447 2149:10448 2150:10450 2152:10495 2152:10497 2152:10498 2152:10499 2152:10500 2152:10580 2152:10581 2153:10503 2153:10504 2153:10505 2153:10506 2153:10507 2153:10508 2153:10509 2153:10510 2153:10511 2153:10512 2153:10513 2153:10514 2153:10515 2153:10516 2153:10517 2153:10518 2153:10519 2153:10520 2153:10521 2153:10522 2153:10523 2153:10524 2153:10525 2153:10526 2153:10527 2153:10528 2153:10529 2153:10530 2153:10531 2153:10532 2153:10533 2153:10534 2153:10535 2153:10536 2153:10537 2153:10538 2153:10539 2153:10540 2153:10541 2153:10542 2153:10543 2153:10544 2153:10545 2153:10546 2153:10547 2153:10548 2153:10549 2153:10550 2153:10551 2153:10552 2153:10553 2153:10554 2153:10555 2153:10556 2153:10557 2153:10558 2153:10565 2153:10566 2153:10567 2153:10568 2153:10569 2154:10571 2154:10572 2154:10573 2154:10574 2154:10576 2154:10577 2155:10579 2157:10583 2157:10585 2157:10586 2157:10587 2157:10588 2157:10668 2157:10669 2158:10591 2158:10592 2158:10593 2158:10594 2158:10595 2158:10596 2158:10597 2158:10598 2158:10599 2158:10600 2158:10601 2158:10602 2158:10603 2158:10604 2158:10605 2158:10606 2158:10607 2158:10608 2158:10609 2158:10610 2158:10611 2158:10612 2158:10613 2158:10614 2158:10615 2158:10616 2158:10617 2158:10618 2158:10619 2158:10620 2158:10621 2158:10622 2158:10623 2158:10624 2158:10625 2158:10626 2158:10627 2158:10628 2158:10629 2158:10630 2158:10631 2158:10632 2158:10633 2158:10634 2158:10635 2158:10636 2158:10637 2158:10638 2158:10639 2158:10640 2158:10641 2158:10642 2158:10643 2158:10644 2158:10645 2158:10646 2158:10653 2158:10654 2158:10655 2158:10656 2158:10657 2159:10659 2159:10660 2159:10661 2159:10662 2159:10664 2159:10665 2160:10667 2163:9175 2163:9177 2163:9178 2163:9179 2163:9183 2163:9228 2163:9229 2164:9180 2164:9185 2164:9186 2164:9187 2164:9188 2165:9181 2165:9189 2165:9190 2165:9191 2165:9192 2165:9193 2165:9194 2165:9195 2165:9199 2165:9200 2165:9201 2165:9202 2165:9204 2165:9205 2168:9196 2168:9197 2169:9182 2169:9207 2169:9208 2169:9209 2169:9210 2169:9211 2169:9213 2169:9214 2169:9215 2169:9216 2171:9219 2171:9220 2171:9221 2171:9222 2171:9224 2171:9225 2172:9227 2174:10700 2174:10702 2174:10703 2174:10704 2174:10706 2174:10721 2174:10722 2175:10705 2175:10708 2175:10709 2175:10710 2175:10711 2176:10712 2176:10713 2176:10714 2176:10715 2176:10717 2176:10718 2177:10720 2180:10671 2180:10673 2180:10674 2180:10675 2180:10678 2180:10697 2180:10698 2181:10676 2181:10677 2181:10680 2181:10681 2181:10682 2181:10683 2181:10684 2181:10685 2181:10686 2181:10687 2182:10688 2182:10689 2182:10690 2182:10691 2182:10693 2182:10694 2183:10696 2190:10724 2190:10729 2190:10730 2190:10731 2190:10733 2190:10734 2190:10735 2190:10770 2190:10771 2191:10725 2191:10737 2192:10726 2193:10727 2194:10728 2195:10740 2195:10741 2195:10742 2195:10743 2195:10744 2195:10745 2195:10746 2195:10747 2195:10748 2195:10749 2195:10750 2195:10751 2195:10752 2195:10753 2195:10755 2195:10756 2204:10757 2204:10758 2204:10764 2204:10766 2204:10767 2205:10760 2205:10769 2206:10761 2207:10762 2211:10069 2211:10070 2211:10071 2211:10073 2211:10074 2211:10075 2211:10188 2211:10189 2212:10081 2218:10085 2218:10086 2218:10087 2218:10088 2218:10089 2218:10090 2218:10092 2218:10093 2218:10094 2218:10096 2218:10097 2218:10098 2218:10099 2218:10100 2218:10101 2218:10102 2218:10103 2218:10111 2218:10113 2218:10114 2218:10115 2218:10116 2219:10076 2219:10105 2219:10106 2220:10107 2220:10108 2227:10120 2227:10121 2227:10122 2227:10171 2227:10172 2227:10173 2227:10174 2227:10176 2227:10177 2229:10077 2229:10123 2229:10124 2229:10125 2230:10126 2230:10127 2245:10154 2245:10163 2245:10165 2245:10166 2245:10167 2245:10168 2246:10130 2246:10131 2246:10132 2246:10133 2246:10134 2246:10135 2246:10137 2246:10139 2246:10140 2246:10141 2246:10142 2246:10143 2246:10144 2246:10145 2246:10146 2248:10078 2248:10148 2248:10149 2249:10150 2249:10151 2252:10079 2252:10155 2252:10157 2252:10158 2253:10159 2253:10160 2257:10179 2257:10180 2257:10181 2257:10182 2257:10184 2257:10185 2258:10187 2260:10773 2260:10775 2260:10776 2260:10777 2260:10815 2260:10820 2260:10821 2260:10822 2260:10823 2260:10825 2260:10826 2262:10781 2262:10782 2262:10783 2262:10784 2262:10785 2262:10786 2262:10788 2262:10789 2262:10790 2262:10792 2262:10793 2262:10794 2262:10795 2262:10796 2262:10797 2262:10798 2262:10799 2263:10778 2263:10779 2263:10801 2263:10802 2263:10803 2263:10804 2263:10805 2263:10806 2263:10807 2263:10808 2263:10809 2263:10810 2263:10811 2265:10816 2265:10817 2265:10818 2265:10819 2267:10814 2310:9777 2310:9778 2310:9779 2310:9781 2310:9782 2310:9783 2310:9821 2310:9870 2310:9875 2310:9876 2310:9877 2310:9878 2310:9879 2310:9880 2310:9881 2312:9788 2312:9789 2312:9790 2312:9791 2312:9792 2312:9793 2312:9795 2312:9796 2312:9797 2312:9798 2312:9800 2312:9801 2312:9802 2312:9803 2312:9804 2312:9805 2312:9806 2312:9807 2313:9784 2313:9785 2313:9808 2313:9809 2313:9810 2313:9811 2313:9812 2313:9813 2313:9815 2313:9816 2313:9817 2314:9818 2314:9819 2314:9820 2316:9822 2316:9823 2316:9824 2316:9825 2316:9826 2316:9827 2316:9828 2316:9830 2316:9831 2316:9832 2316:9833 2316:9834 2316:9835 2316:9836 2316:9837 2316:9838 2316:9839 2316:9840 2316:9841 2316:9842 2316:9843 2316:9845 2316:9846 2316:9847 2316:9848 2316:9850 2316:9851 2316:9852 2316:9853 2316:9854 2316:9855 2316:9856 2316:9857 2317:9786 2317:9858 2317:9859 2317:9860 2317:9861 2317:9862 2317:9863 2317:9864 2317:9866 2317:9867 2318:9869 2318:9871 2318:9872 2318:9873 2318:9874 2321:11177 2321:11178 2321:11179 2321:11181 2321:11182 2321:11183 2321:11184 2321:11202 2321:11203 2322:11186 2322:11187 2322:11188 2322:11189 2322:11190 2322:11191 2322:11192 2322:11193 2323:11194 2323:11195 2323:11196 2323:11197 2323:11198 2324:11199 2324:11200 2324:11201 2331:10459 2331:10461 2331:10462 2331:10463 2331:10464 2331:10492 2331:10493 2332:10466 2332:10467 2332:10468 2332:10469 2332:10470 2332:10471 2332:10472 2332:10473 2332:10474 2332:10475 2332:10476 2332:10477 2332:10478 2332:10479 2332:10481 2332:10482 2333:10483 2333:10484 2333:10485 2333:10486 2333:10488 2333:10489 2334:10491 2336:11014 2336:11015 2336:11016 2336:11018 2336:11019 2336:11020 2336:11094 2336:11095 2338:11025 2338:11026 2338:11027 2338:11051 2338:11077 2338:11078 2338:11079 2338:11080 2338:11081 2338:11082 2338:11083 2338:11084 2352:11028 2352:11029 2352:11030 2352:11031 2352:11032 2352:11033 2352:11035 2352:11037 2352:11038 2352:11039 2352:11040 2352:11041 2352:11042 2352:11043 2352:11044 2353:11045 2354:11021 2354:11046 2354:11047 2355:11048 2355:11049 2358:11052 2358:11053 2358:11054 2358:11055 2358:11056 2358:11057 2358:11058 2358:11060 2358:11061 2358:11063 2358:11064 2358:11065 2358:11066 2358:11067 2358:11068 2358:11069 2358:11070 2359:11071 2360:11022 2360:11072 2360:11073 2361:11074 2361:11075 2364:11085 2364:11086 2364:11087 2364:11088 2364:11090 2364:11091 2365:11093 2375:11446 2375:11454 2375:11455 2375:11456 2375:11458 2375:11459 2375:11460 2375:11464 2375:11542 2375:11543 2376:11447 2377:11448 2378:11449 2378:11461 2378:11466 2378:11467 2379:11450 2379:11468 2379:11469 2380:11451 2380:11471 2380:11472 2380:11473 2380:11497 2380:11523 2380:11524 2380:11525 2380:11526 2380:11527 2380:11528 2380:11529 2381:11452 2382:11453 2394:11474 2394:11475 2394:11476 2394:11477 2394:11478 2394:11479 2394:11481 2394:11483 2394:11484 2394:11485 2394:11486 2394:11487 2394:11488 2394:11489 2394:11490 2395:11491 2396:11462 2396:11492 2396:11493 2397:11494 2397:11495 2400:11498 2400:11499 2400:11500 2400:11501 2400:11502 2400:11503 2400:11504 2400:11506 2400:11507 2400:11509 2400:11510 2400:11511 2400:11512 2400:11513 2400:11514 2400:11515 2400:11516 2401:11517 2402:11463 2402:11518 2402:11519 2403:11520 2403:11521 2405:11530 2405:11531 2405:11536 2405:11538 2405:11539 2406:11533 2406:11541 2407:11534 2411:11205 2411:11206 2411:11207 2411:11209 2411:11210 2411:11211 2411:11217 2411:11219 2411:11405 2411:11406 2411:11407 2411:11408 2411:11409 2411:11410 2411:11411 2414:11220 2414:11221 2414:11222 2414:11223 2414:11224 2414:11225 2414:11226 2414:11227 2414:11228 2414:11229 2414:11231 2414:11232 2415:11235 2415:11260 2415:11261 2415:11262 2415:11263 2415:11264 2416:11236 2416:11237 2416:11238 2418:11241 2418:11242 2418:11243 2420:11246 2420:11247 2420:11248 2422:11251 2422:11252 2422:11253 2422:11255 2422:11256 2423:11266 2424:11212 2424:11268 2424:11269 2424:11270 2424:11271 2424:11272 2424:11341 2424:11342 2424:11343 2424:11344 2424:11345 2425:11213 2425:11347 2425:11348 2426:11349 2426:11350 2426:11351 2426:11352 2426:11354 2426:11355 2427:11357 2429:11214 2429:11360 2429:11361 2429:11362 2429:11363 2430:11364 2430:11365 2430:11366 2430:11367 2430:11369 2430:11370 2431:11372 2433:11215 2433:11375 2433:11376 2433:11377 2433:11378 2434:11379 2434:11380 2434:11381 2434:11382 2434:11384 2434:11385 2435:11387 2439:11216 2439:11390 2439:11391 2439:11392 2439:11393 2440:11394 2440:11395 2440:11396 2440:11397 2440:11399 2440:11400 2441:11402 2461:10946 2461:10948 2461:10949 2461:10950 2461:10952 2461:11006 2461:11007 2461:11008 2461:11009 2461:11010 2461:11011 2461:11012 2462:10953 2462:10954 2462:10955 2462:10957 2462:10958 2462:10959 2462:10960 2463:10964 2463:10965 2463:10966 2463:10967 2463:10968 2464:10971 2464:10972 2464:10973 2464:10974 2464:10975 2465:10978 2465:10979 2465:10980 2465:10981 2465:10982 2466:10985 2466:10986 2466:10987 2466:10988 2466:10989 2467:10992 2467:10993 2467:10994 2467:10995 2467:10996 2468:10999 2468:11000 2468:11001 2468:11002 2468:11003 2474:11545 2474:11548 2474:11550 2474:11551 2474:11552 2474:11557 2474:11746 2474:11747 2475:11546 2476:11547 2476:11553 2476:11554 2476:11560 2476:11561 2476:11562 2476:11563 2476:11564 2476:11565 2476:11566 2476:11567 2476:11568 2476:11637 2476:11638 2476:11639 2476:11640 2476:11641 2479:11644 2479:11645 2479:11646 2479:11647 2479:11648 2479:11649 2479:11650 2479:11739 2479:11740 2479:11741 2479:11742 2479:11743 2480:11555 2480:11556 2480:11653 2480:11654 2480:11655 2480:11656 2480:11657 2480:11658 2480:11659 2480:11660 2480:11745 2482:11664 2482:11665 2482:11666 2482:11667 2482:11668 2484:11671 2484:11672 2484:11673 2484:11674 2490:11677 2490:11678 2490:11679 2490:11680 2490:11681 2490:11682 2490:11683 2490:11684 2490:11685 2490:11686 2490:11687 2490:11688 2490:11689 2490:11690 2490:11691 2490:11692 2490:11693 2490:11694 2490:11695 2490:11696 2490:11697 2490:11698 2490:11699 2490:11700 2490:11701 2490:11702 2490:11703 2490:11704 2490:11705 2490:11706 2490:11707 2490:11708 2490:11709 2490:11710 2490:11711 2490:11712 2490:11713 2490:11714 2490:11715 2490:11716 2490:11717 2490:11718 2490:11719 2490:11720 2490:11721 2490:11722 2490:11723 2490:11724 2490:11725 2490:11726 2490:11727 2490:11728 2490:11729 2490:11730 2490:11731 2490:11732 2490:11733 2490:11734 2490:11735 2490:11736 2500:4493 2500:4495 2500:4496 2500:4497 2500:4831 2500:4832 2501:4500 2501:4820 2501:4821 2501:4822 2501:4823 2501:4824 2502:4501 2502:4502 2502:4503 2502:4504 2502:4505 2502:4506 2503:4509 2503:4510 2503:4511 2503:4512 2503:4513 2503:4514 2504:4517 2504:4518 2504:4519 2504:4520 2504:4521 2504:4522 2505:4525 2505:4526 2505:4527 2505:4528 2505:4529 2505:4530 2506:4533 2506:4534 2506:4535 2506:4536 2506:4537 2506:4538 2507:4541 2507:4542 2507:4543 2507:4544 2507:4545 2507:4546 2508:4549 2508:4550 2508:4551 2508:4552 2508:4553 2508:4554 2509:4557 2509:4558 2509:4559 2509:4560 2509:4561 2509:4562 2510:4565 2510:4566 2510:4567 2510:4568 2510:4569 2510:4570 2511:4573 2511:4574 2511:4575 2511:4576 2511:4577 2511:4578 2512:4581 2512:4582 2512:4583 2512:4584 2512:4585 2512:4586 2513:4589 2513:4590 2513:4591 2513:4592 2513:4593 2513:4594 2514:4597 2514:4598 2514:4599 2514:4600 2514:4601 2514:4602 2515:4605 2515:4606 2515:4607 2515:4608 2515:4609 2515:4610 2516:4613 2516:4614 2516:4615 2516:4616 2516:4617 2516:4618 2517:4621 2517:4622 2517:4623 2517:4624 2517:4625 2517:4626 2518:4629 2518:4630 2518:4631 2518:4632 2518:4633 2518:4634 2519:4637 2519:4638 2519:4639 2519:4640 2519:4641 2519:4642 2520:4645 2520:4646 2520:4647 2520:4648 2520:4649 2520:4650 2521:4653 2521:4654 2521:4655 2521:4656 2521:4657 2521:4658 2522:4661 2522:4662 2522:4663 2522:4664 2522:4665 2522:4666 2523:4669 2523:4670 2523:4671 2523:4672 2523:4673 2523:4674 2524:4677 2524:4678 2524:4679 2524:4680 2524:4681 2524:4682 2525:4685 2525:4686 2525:4687 2525:4688 2525:4689 2525:4690 2526:4693 2526:4694 2526:4695 2526:4696 2526:4697 2526:4698 2527:4701 2527:4702 2527:4703 2527:4704 2527:4705 2527:4706 2528:4709 2528:4710 2528:4711 2528:4712 2528:4713 2528:4714 2529:4717 2529:4718 2529:4719 2529:4720 2529:4721 2529:4722 2530:4725 2530:4726 2530:4727 2530:4728 2530:4729 2530:4730 2531:4733 2531:4734 2531:4735 2531:4736 2531:4737 2531:4738 2532:4741 2532:4742 2532:4743 2532:4744 2532:4745 2532:4746 2533:4749 2533:4750 2533:4751 2533:4752 2533:4753 2533:4754 2534:4757 2534:4758 2534:4759 2534:4760 2534:4761 2534:4762 2535:4765 2535:4766 2535:4767 2535:4768 2535:4769 2535:4770 2536:4773 2536:4774 2536:4775 2536:4776 2536:4777 2536:4778 2537:4781 2537:4782 2537:4783 2537:4784 2537:4785 2537:4786 2538:4789 2538:4790 2538:4791 2538:4792 2538:4793 2538:4794 2538:4795 2538:4796 2538:4797 2538:4798 2538:4799 2538:4800 2538:4801 2538:4802 2538:4803 2539:4806 2539:4807 2539:4808 2539:4809 2539:4810 2539:4811 2539:4812 2539:4813 2539:4814 2539:4815 2539:4816 2539:4817 2541:4826 2541:4827 2541:4828 2544:4830 2547:11846 2547:11849 2547:11851 2547:11852 2547:11853 2547:11855 2547:11894 2547:11895 2548:11847 2548:11854 2548:11858 2548:11859 2548:11860 2548:11861 2548:11862 2548:11879 2548:11880 2548:11881 2548:11882 2548:11883 2549:11848 2549:11863 2549:11864 2549:11865 2549:11866 2549:11868 2549:11869 2550:11873 2550:11874 2550:11875 2550:11876 2552:11885 2552:11886 2552:11887 2552:11888 2552:11890 2552:11891 2553:11893 2581:11749 2581:11771 2581:11772 2581:11773 2581:11775 2581:11776 2581:11777 2581:11800 2581:11801 2582:11750 2583:11751 2583:11780 2584:11752 2584:11778 2584:11781 2584:11782 2585:11753 2585:11783 2586:11754 2586:11784 2586:11785 2586:11786 2586:11794 2586:11796 2586:11797 2587:11755 2587:11787 2587:11799 2588:11756 2588:11788 2589:11757 2589:11789 2590:11758 2590:11790 2591:11759 2591:11791 2592:11760 2592:11792 2593:11761 2594:11762 2595:11763 2596:11764 2597:11765 2598:11766 2599:11413 2599:11416 2599:11417 2599:11418 2599:11420 2599:11421 2599:11422 2599:11443 2599:11444 2599:11767 2600:11414 2600:11768 2601:11415 2601:11769 2602:11770 2605:11423 2605:11425 2605:11426 2606:11427 2606:11428 2606:11437 2606:11439 2606:11440 2607:11430 2607:11442 2608:11431 2609:11432 2610:11433 2611:11434 2612:11435 2623:11803 2623:11809 2623:11810 2623:11811 2623:11813 2623:11814 2623:11815 2623:11843 2623:11844 2624:11804 2625:11805 2625:11816 2625:11817 2625:11820 2625:11821 2625:11822 2625:11823 2626:11806 2626:11818 2626:11824 2626:11825 2627:11807 2627:11826 2628:11808 2628:11827 2628:11828 2628:11829 2628:11837 2628:11839 2628:11840 2629:11830 2629:11842 2630:11831 2631:11832 2632:11833 2633:11834 2634:11835 2639:8011 2639:8012 2639:8013 2639:8015 2639:8016 2639:8017 2639:8248 2639:8249 2640:8019 2640:8020 2641:8022 2641:8241 2641:8242 2641:8243 2641:8244 2641:8245 2642:8023 2642:8024 2642:8025 2642:8026 2642:8027 2642:8028 2642:8029 2642:8030 2642:8031 2642:8032 2642:8033 2642:8034 2642:8035 2642:8036 2642:8038 2642:8039 2642:8040 2642:8041 2642:8042 2642:8043 2642:8044 2642:8143 2642:8144 2642:8145 2642:8146 2642:8147 2642:8247 2643:8047 2643:8048 2643:8049 2643:8050 2643:8051 2643:8052 2644:8055 2644:8056 2644:8057 2644:8058 2644:8059 2644:8060 2645:8063 2645:8064 2645:8065 2645:8066 2645:8067 2645:8068 2646:8071 2646:8072 2646:8073 2646:8074 2646:8075 2646:8076 2647:8079 2647:8080 2647:8081 2647:8082 2647:8083 2647:8084 2648:8087 2648:8088 2648:8089 2648:8090 2648:8091 2648:8092 2649:8095 2649:8096 2649:8097 2649:8098 2649:8099 2649:8100 2650:8103 2650:8104 2650:8105 2650:8106 2650:8107 2650:8108 2651:8111 2651:8112 2651:8113 2651:8114 2651:8115 2651:8116 2652:8119 2652:8120 2652:8121 2652:8122 2652:8123 2652:8124 2653:8127 2653:8128 2653:8129 2653:8130 2653:8131 2653:8132 2654:8135 2654:8136 2654:8137 2654:8138 2654:8139 2654:8140 2657:8149 2658:8150 2658:8151 2665:4834 2665:4835 2665:4836 2665:4838 2665:4839 2665:4840 2665:4980 2665:4981 2666:4842 2666:4843 2667:4845 2667:4973 2667:4974 2667:4975 2667:4976 2667:4977 2668:4846 2668:4847 2668:4848 2668:4849 2668:4850 2668:4851 2668:4852 2668:4853 2668:4854 2668:4979 2669:4857 2669:4858 2669:4859 2669:4860 2669:4861 2669:4862 2669:4863 2669:4864 2669:4865 2669:4866 2669:4867 2669:4868 2669:4869 2669:4870 2675:12087 2675:12088 2675:12089 2675:12091 2675:12092 2675:12093 2675:12116 2675:12117 2676:12095 2676:12096 2676:12097 2676:12098 2676:12099 2676:12100 2676:12101 2676:12102 2676:12103 2676:12104 2676:12105 2676:12106 2676:12107 2676:12108 2676:12109 2676:12110 2676:12111 2676:12113 2676:12114 2676:12115 2681:12119 2681:12120 2681:12121 2681:12123 2681:12124 2681:12125 2681:12148 2681:12149 2682:12127 2682:12128 2682:12129 2682:12130 2682:12131 2682:12132 2682:12133 2682:12134 2682:12135 2682:12136 2682:12137 2682:12138 2682:12139 2682:12140 2682:12141 2682:12142 2682:12143 2682:12145 2682:12146 2682:12147 2686:12151 2686:12152 2686:12153 2686:12155 2686:12156 2686:12157 2686:12180 2686:12181 2687:12159 2687:12160 2687:12161 2687:12162 2687:12163 2687:12164 2687:12165 2687:12166 2687:12167 2687:12168 2687:12169 2687:12170 2687:12171 2687:12172 2687:12173 2687:12174 2687:12175 2687:12177 2687:12178 2687:12179 2692:12183 2692:12184 2692:12185 2692:12187 2692:12188 2692:12189 2692:12212 2692:12213 2693:12191 2693:12192 2693:12193 2693:12194 2693:12195 2693:12196 2693:12197 2693:12198 2693:12199 2693:12200 2693:12201 2693:12202 2693:12203 2693:12204 2693:12205 2693:12206 2693:12207 2693:12209 2693:12210 2693:12211 2698:12215 2698:12216 2698:12217 2698:12219 2698:12220 2698:12221 2698:12244 2698:12245 2699:12223 2699:12224 2699:12225 2699:12226 2699:12227 2699:12228 2699:12229 2699:12230 2699:12231 2699:12232 2699:12233 2699:12234 2699:12235 2699:12236 2699:12237 2699:12238 2699:12239 2699:12241 2699:12242 2699:12243 2705:12247 2705:12248 2705:12249 2705:12251 2705:12252 2705:12253 2705:12296 2705:12297 2706:12255 2706:12256 2706:12257 2706:12258 2706:12259 2706:12260 2706:12262 2706:12263 2706:12264 2706:12265 2706:12266 2706:12267 2706:12268 2706:12271 2706:12272 2706:12273 2706:12274 2706:12275 2706:12276 2706:12279 2706:12280 2706:12281 2706:12282 2706:12283 2706:12285 2706:12286 2706:12287 2706:12288 2706:12289 2706:12290 2706:12291 2706:12293 2706:12294 2706:12295 2710:12299 2710:12300 2710:12301 2710:12303 2710:12304 2710:12305 2710:12372 2710:12373 2711:12307 2711:12308 2711:12309 2711:12310 2711:12311 2711:12312 2711:12314 2711:12315 2711:12316 2711:12317 2711:12318 2711:12319 2711:12320 2711:12323 2711:12324 2711:12325 2711:12326 2711:12327 2711:12328 2711:12331 2711:12332 2711:12333 2711:12334 2711:12335 2711:12336 2711:12339 2711:12340 2711:12341 2711:12342 2711:12343 2711:12344 2711:12347 2711:12348 2711:12349 2711:12350 2711:12351 2711:12352 2711:12355 2711:12356 2711:12357 2711:12358 2711:12359 2711:12361 2711:12362 2711:12363 2711:12364 2711:12365 2711:12366 2711:12367 2711:12369 2711:12370 2711:12371 2715:12375 2715:12376 2715:12377 2715:12379 2715:12380 2715:12381 2715:12467 2715:12468 2716:12383 2716:12384 2717:12386 2717:12440 2717:12449 2717:12458 2717:12460 2717:12461 2717:12462 2717:12463 2718:12389 2718:12390 2718:12391 2718:12392 2718:12393 2718:12394 2718:12395 2718:12430 2718:12431 2718:12432 2718:12433 2718:12434 2718:12466 2719:12398 2719:12399 2719:12400 2719:12401 2719:12402 2719:12403 2720:12406 2720:12407 2720:12408 2720:12409 2720:12410 2720:12411 2721:12414 2721:12415 2721:12416 2721:12417 2721:12418 2721:12419 2722:12422 2722:12423 2722:12424 2722:12425 2722:12426 2722:12427 2724:12436 2725:12437 2725:12438 2728:12441 2728:12442 2728:12443 2728:12444 2728:12445 2728:12446 2728:12447 2728:12448 2729:12450 2729:12451 2729:12452 2729:12453 2729:12454 2729:12455 2729:12456 2729:12457 2736:9687 2736:9688 2736:9689 2736:9691 2736:9692 2736:9693 2736:9774 2736:9775 2737:9695 2737:9696 2738:9697 2738:9698 2738:9699 2738:9766 2738:9767 2738:9768 2738:9769 2738:9771 2738:9772 2738:9773 2739:9700 2739:9702 2739:9703 2739:9704 2739:9705 2739:9706 2739:9708 2739:9709 2739:9710 2739:9711 2739:9712 2739:9713 2739:9714 2739:9717 2739:9718 2739:9719 2739:9720 2739:9721 2739:9722 2739:9725 2739:9726 2739:9727 2739:9728 2739:9729 2739:9730 2739:9733 2739:9734 2739:9735 2739:9736 2739:9737 2739:9757 2739:9758 2739:9759 2739:9760 2739:9761 2740:9741 2740:9742 2740:9743 2740:9744 2740:9745 2740:9746 2741:9749 2741:9750 2741:9751 2741:9752 2741:9753 2741:9754 2743:9763 2744:9764 2744:9765 2750:12470 2750:12471 2750:12472 2750:12474 2750:12475 2750:12476 2750:12519 2750:12520 2751:12478 2751:12479 2752:12480 2752:12481 2752:12482 2752:12511 2752:12512 2752:12513 2752:12514 2752:12516 2752:12517 2752:12518 2755:12483 2755:12485 2755:12486 2755:12487 2755:12488 2755:12489 2755:12490 2755:12491 2755:12494 2755:12495 2755:12496 2755:12497 2755:12498 2755:12499 2755:12502 2755:12503 2755:12504 2755:12505 2755:12506 2755:12508 2756:12509 2756:12510 2762:12522 2762:12523 2762:12524 2762:12526 2762:12527 2762:12528 2762:12530 2762:12860 2762:12861 2762:12862 2762:12863 2762:12864 2762:12865 2762:12866 2763:12531 2763:12532 2763:12534 2763:12535 2763:12536 2763:12537 2763:12538 2763:12539 2763:12540 2763:12541 2763:12542 2763:12543 2763:12544 2763:12546 2763:12547 2763:12548 2763:12549 2763:12550 2763:12551 2763:12552 2763:12555 2763:12556 2763:12557 2763:12558 2763:12559 2763:12560 2763:12563 2763:12564 2763:12565 2763:12566 2763:12567 2763:12568 2763:12571 2763:12572 2763:12573 2763:12574 2763:12575 2763:12577 2763:12578 2763:12579 2763:12580 2763:12581 2763:12582 2763:12583 2763:12585 2763:12586 2764:12588 2764:12591 2764:12592 2764:12594 2764:12595 2764:12596 2764:12597 2764:12598 2764:12599 2764:12600 2764:12601 2764:12602 2764:12603 2764:12604 2764:12606 2764:12607 2764:12608 2764:12609 2764:12610 2764:12611 2764:12612 2764:12615 2764:12616 2764:12617 2764:12618 2764:12619 2764:12620 2764:12623 2764:12624 2764:12625 2764:12626 2764:12627 2764:12628 2764:12631 2764:12632 2764:12633 2764:12634 2764:12635 2764:12637 2764:12638 2764:12639 2764:12640 2764:12641 2764:12642 2764:12643 2764:12645 2764:12646 2765:12648 2765:12651 2765:12652 2765:12654 2765:12655 2765:12656 2765:12657 2765:12658 2765:12659 2765:12661 2765:12662 2765:12663 2765:12664 2765:12665 2765:12666 2765:12667 2765:12669 2765:12670 2765:12671 2765:12672 2765:12673 2765:12674 2765:12675 2765:12678 2765:12679 2765:12680 2765:12681 2765:12682 2765:12683 2765:12686 2765:12687 2765:12688 2765:12689 2765:12690 2765:12691 2765:12694 2765:12695 2765:12696 2765:12697 2765:12698 2765:12700 2765:12701 2765:12702 2765:12703 2765:12704 2765:12705 2765:12706 2765:12708 2765:12709 2766:12711 2766:12714 2766:12715 2766:12717 2766:12718 2766:12719 2766:12720 2766:12721 2766:12722 2766:12724 2766:12725 2766:12726 2766:12727 2766:12728 2766:12729 2766:12730 2766:12732 2766:12733 2766:12734 2766:12735 2766:12736 2766:12737 2766:12738 2766:12741 2766:12742 2766:12743 2766:12744 2766:12745 2766:12746 2766:12749 2766:12750 2766:12751 2766:12752 2766:12753 2766:12754 2766:12757 2766:12758 2766:12759 2766:12760 2766:12761 2766:12763 2766:12764 2766:12765 2766:12766 2766:12767 2766:12768 2766:12769 2766:12771 2766:12772 2767:12774 2767:12777 2767:12778 2767:12779 2767:12780 2767:12781 2767:12782 2767:12783 2767:12784 2767:12785 2767:12786 2767:12787 2767:12788 2767:12789 2767:12790 2767:12791 2767:12792 2767:12793 2767:12794 2767:12795 2767:12796 2767:12797 2767:12798 2767:12799 2767:12800 2767:12801 2767:12802 2767:12803 2767:12804 2767:12805 2767:12806 2767:12808 2767:12809 2767:12810 2767:12811 2767:12812 2767:12813 2767:12815 2767:12816 2767:12817 2767:12818 2767:12819 2767:12820 2767:12821 2767:12824 2767:12825 2767:12826 2767:12827 2767:12828 2767:12829 2767:12832 2767:12833 2767:12834 2767:12835 2767:12836 2767:12837 2767:12840 2767:12841 2767:12842 2767:12843 2767:12844 2767:12846 2767:12847 2767:12848 2767:12849 2767:12850 2767:12851 2767:12852 2767:12854 2767:12855 2768:12857 2771:12900 2771:12901 2771:12902 2771:12904 2771:12905 2771:12906 2771:12929 2771:12930 2772:12908 2772:12909 2772:12910 2772:12911 2772:12912 2772:12913 2772:12914 2772:12915 2772:12916 2772:12917 2772:12918 2772:12919 2772:12920 2772:12921 2772:12922 2772:12923 2772:12924 2772:12926 2772:12927 2772:12928 2779:12868 2779:12869 2779:12870 2779:12872 2779:12873 2779:12874 2779:12897 2779:12898 2780:12876 2780:12877 2780:12878 2780:12879 2780:12880 2780:12881 2780:12882 2780:12883 2780:12884 2780:12885 2780:12886 2780:12887 2780:12888 2780:12889 2780:12890 2780:12891 2780:12892 2780:12894 2780:12895 2780:12896 2784:12932 2784:12933 2784:12934 2784:12936 2784:12937 2784:12938 2784:12940 2784:13030 2784:13031 2784:13032 2784:13033 2784:13034 2784:13035 2784:13036 2785:12941 2785:12942 2785:12943 2785:12944 2785:12945 2785:12946 2785:12947 2785:12948 2785:12949 2785:12950 2786:12953 2786:12954 2786:12955 2786:12956 2786:12957 2786:12958 2786:12959 2786:12960 2786:12961 2786:12962 2787:12965 2787:12966 2787:12967 2787:12968 2787:12969 2787:12970 2787:12971 2787:12972 2787:12974 2787:12975 2787:12976 2787:12977 2788:12980 2788:12981 2788:12982 2788:12983 2788:12984 2788:12985 2788:12986 2788:12987 2788:12989 2788:12990 2788:12991 2788:12992 2789:12995 2789:12996 2789:12997 2789:12998 2789:12999 2789:13000 2789:13001 2789:13002 2789:13003 2789:13004 2789:13005 2789:13006 2789:13007 2789:13008 2789:13009 2789:13010 2789:13011 2789:13012 2789:13013 2789:13014 2789:13015 2789:13016 2789:13017 2789:13018 2789:13019 2789:13020 2789:13021 2789:13022 2789:13023 2789:13024 2789:13025 2789:13026 2789:13027 2793:13038 2793:13039 2793:13040 2793:13042 2793:13043 2793:13044 2793:13050 2793:13183 2793:13184 2793:13185 2793:13186 2793:13187 2793:13188 2793:13189 2796:13051 2796:13052 2796:13053 2796:13054 2796:13055 2796:13056 2796:13057 2796:13058 2796:13059 2796:13060 2797:13063 2797:13064 2797:13065 2797:13066 2797:13067 2797:13068 2797:13069 2797:13070 2797:13071 2797:13072 2798:13075 2798:13076 2798:13077 2798:13078 2798:13079 2798:13080 2798:13081 2798:13082 2798:13083 2798:13084 2798:13085 2798:13086 2798:13087 2798:13088 2798:13089 2798:13090 2798:13091 2798:13092 2798:13093 2798:13094 2798:13095 2798:13096 2798:13097 2798:13098 2798:13099 2798:13100 2798:13101 2798:13102 2798:13136 2798:13170 2798:13174 2798:13175 2798:13176 2798:13177 2798:13178 2799:13180 2807:13104 2807:13105 2807:13106 2807:13107 2807:13108 2807:13109 2807:13111 2807:13112 2807:13113 2807:13114 2807:13116 2807:13117 2807:13118 2807:13119 2807:13120 2807:13121 2807:13122 2807:13123 2808:13045 2808:13046 2808:13124 2808:13125 2808:13126 2808:13127 2808:13128 2808:13129 2808:13131 2808:13132 2808:13133 2809:13134 2809:13135 2816:13137 2816:13138 2816:13139 2816:13140 2816:13141 2816:13142 2816:13143 2816:13145 2816:13146 2816:13147 2816:13148 2816:13150 2816:13151 2816:13152 2816:13153 2816:13154 2816:13155 2816:13156 2816:13157 2817:13047 2817:13048 2817:13158 2817:13159 2817:13160 2817:13161 2817:13162 2817:13163 2817:13165 2817:13166 2817:13167 2818:13168 2818:13169 2820:13171 2820:13172 2820:13173 2825:13191 2825:13192 2825:13193 2825:13195 2825:13196 2825:13197 2825:13232 2825:13233 2827:13203 2827:13204 2828:13214 2828:13223 2828:13225 2828:13226 2828:13227 2828:13228 2829:13231 2832:13198 2832:13199 2832:13206 2832:13207 2832:13208 2832:13209 2832:13210 2832:13211 2832:13212 2833:13200 2833:13201 2833:13215 2833:13216 2833:13217 2833:13218 2833:13219 2833:13220 2833:13221 2840:10828 2840:10830 2840:10831 2840:10832 2840:10834 2840:10836 2840:10938 2840:10939 2840:10940 2840:10941 2840:10942 2840:10943 2840:10944 2841:10837 2841:10838 2841:10839 2841:10840 2841:10841 2841:10842 2843:10843 2845:10846 2845:10847 2845:10848 2845:10849 2845:10850 2845:10851 2845:10852 2845:10853 2845:10854 2845:10855 2845:10856 2845:10857 2845:10858 2845:10859 2846:10862 2846:10863 2846:10864 2846:10865 2846:10866 2847:10869 2847:10870 2847:10871 2847:10872 2847:10873 2847:10874 2847:10875 2848:10878 2848:10879 2848:10880 2848:10881 2848:10882 2848:10883 2848:10884 2849:10833 2849:10887 2849:10888 2849:10889 2849:10890 2850:10891 2850:10892 2850:10893 2850:10894 2850:10896 2850:10897 2851:10899 2851:10902 2851:10903 2851:10904 2851:10905 2851:10906 2852:10909 2852:10910 2852:10911 2852:10912 2852:10913 2853:10916 2853:10917 2853:10918 2853:10919 2853:10920 2855:10923 2855:10924 2855:10925 2855:10926 2855:10927 2855:10928 2855:10929 2855:10930 2855:10931 2855:10932 2855:10933 2855:10934 2855:10935 2867:11897 2867:11899 2867:11900 2867:11901 2867:11902 2867:12023 2867:12024 2868:11903 2869:11904 2870:11905 2871:11906 2874:11909 2875:11910 2875:11911 2876:11913 2876:11914 2877:11915 2877:11916 2877:11917 2877:11918 2877:11919 2877:11996 2877:11997 2877:11998 2877:11999 2877:12001 2877:12002 2878:11920 2878:11921 2879:11924 2879:11925 2879:11926 2879:11927 2879:11928 2879:11929 2879:11930 2879:11931 2879:11932 2879:11933 2879:11934 2879:11935 2879:11936 2879:11937 2879:11938 2879:11939 2879:11940 2879:11941 2879:11942 2879:11943 2879:11944 2879:11945 2879:11946 2879:11947 2879:11948 2879:11949 2879:11950 2879:11951 2879:11952 2879:11953 2879:11954 2879:11955 2879:11956 2879:11957 2879:11958 2879:11959 2879:11960 2879:11961 2879:11962 2879:11963 2879:11964 2879:11965 2879:11966 2879:11967 2879:11968 2879:11969 2879:11970 2879:11971 2879:11972 2879:11973 2879:11974 2879:11975 2879:11976 2879:11977 2879:11978 2879:11979 2879:11982 2879:11983 2879:11984 2879:11985 2879:11986 2879:11990 2879:11991 2879:11992 2879:11993 2879:11994 2887:12003 2888:12005 2889:12006 2891:12009 2892:12010 2892:12011 2892:12017 2892:12019 2892:12020 2893:12013 2893:12022 2894:12014 2895:12015 2902:9070 2902:9073 2902:9074 2902:9075 2902:9076 2902:9078 2902:9079 2902:9080 2902:9081 2902:9135 2902:9136 2902:9137 2903:9071 2904:9072 2906:9084 2906:9085 2906:9086 2906:9087 2906:9088 2906:9089 2906:9091 2906:9092 2906:9093 2906:9095 2906:9096 2906:9097 2906:9098 2906:9099 2906:9100 2906:9101 2906:9102 2906:9108 2906:9112 2906:9116 2906:9120 2906:9121 2906:9122 2906:9123 2907:9103 2907:9104 2907:9106 2907:9107 2908:9109 2908:9110 2908:9111 2909:9113 2909:9114 2909:9115 2910:9117 2910:9118 2910:9119 2913:9126 2913:9127 2913:9128 2913:9129 2913:9131 2913:9132 2914:9134 2916:8785 2916:8787 2916:8788 2916:8789 2916:8790 2916:8805 2916:8806 2918:8793 2918:8794 2921:8796 2921:8797 2921:8798 2921:8799 2921:8801 2921:8802 2922:8804 2925:13447 2925:13449 2925:13450 2925:13451 2925:13456 2925:13457 2926:13453 2926:13454 2926:13455 2930:12026 2930:12028 2930:12029 2930:12030 2930:12037 2930:12084 2930:12085 2931:12031 2931:12032 2931:12039 2931:12040 2931:12041 2931:12042 2932:12043 2932:12044 2934:12046 2934:12047 2936:12033 2936:12034 2936:12048 2936:12049 2936:12050 2936:12051 2936:12052 2936:12053 2936:12054 2936:12055 2936:12061 2936:12062 2936:12063 2936:12064 2936:12066 2936:12067 2937:12056 2937:12057 2938:12059 2938:12060 2941:12035 2941:12036 2941:12068 2941:12069 2941:12070 2941:12071 2942:12072 2942:12073 2942:12074 2942:12078 2942:12080 2942:12081 2943:12075 2943:12083 2944:12076 2948:13531 2948:13533 2948:13534 2948:13535 2948:13574 2948:13575 2950:13538 2950:13539 2950:13540 2950:13541 2950:13542 2950:13567 2950:13568 2950:13569 2950:13570 2950:13571 2951:13545 2951:13546 2951:13547 2951:13548 2951:13549 2951:13550 2951:13553 2951:13554 2951:13555 2951:13556 2951:13557 2951:13558 2951:13573 2952:13561 2952:13562 2952:13563 2952:13564 2976:13459 2976:13477 2976:13479 2976:13480 2976:13481 2976:13487 2976:13511 2976:13523 2976:13524 2976:13525 2976:13526 2976:13528 2976:13529 2977:13460 2978:13461 2978:13482 2978:13483 2978:13489 2978:13490 2978:13491 2978:13492 2979:13462 2979:13484 2979:13493 2979:13494 2979:13495 2979:13496 2979:13497 2980:13463 2980:13499 2981:13464 2981:13500 2981:13501 2981:13502 2981:13505 2981:13507 2981:13508 2982:13465 2982:13503 2982:13510 2983:13466 2984:13467 2985:13468 2986:13469 2986:13485 2986:13486 2986:13512 2986:13513 2986:13514 2986:13515 2986:13516 2986:13517 2986:13518 2986:13519 2986:13520 2987:13470 2988:13471 2989:13472 2989:13522 2990:13473 2991:13474 2992:13475 2993:13476 3090:13299 3090:13348 3090:13350 3090:13351 3090:13352 3090:13358 3090:13444 3090:13445 3091:13300 3091:13353 3091:13354 3091:13360 3091:13361 3091:13363 3091:13364 3091:13365 3091:13366 3091:13367 3091:13383 3091:13384 3091:13385 3091:13386 3091:13387 3091:13389 3091:13390 3092:13301 3092:13392 3092:13393 3092:13394 3092:13395 3092:13396 3092:13437 3092:13438 3092:13439 3092:13440 3092:13441 3093:13302 3093:13355 3093:13397 3093:13398 3093:13443 3094:13303 3095:13304 3095:13404 3095:13406 3095:13407 3095:13408 3095:13409 3096:13305 3097:13306 3097:13356 3097:13400 3097:13401 3097:13402 3097:13403 3098:13307 3099:13308 3100:13309 3100:13412 3100:13413 3100:13414 3100:13416 3100:13418 3100:13419 3101:13310 3101:13415 3102:13311 3103:13312 3104:13313 3105:13314 3106:13315 3107:13316 3108:13317 3109:13318 3110:13319 3110:13357 3110:13423 3110:13424 3110:13425 3110:13426 3111:13320 3112:13321 3113:13322 3113:13427 3113:13428 3113:13429 3113:13430 3113:13432 3113:13433 3114:13323 3115:13324 3116:13325 3117:13326 3118:6649 3118:6651 3118:6652 3118:6653 3118:7024 3118:7025 3118:13327 3119:6655 3119:13328 3120:6656 3120:13329 3121:6657 3121:13330 3122:6658 3122:13331 3123:6659 3123:13332 3124:6660 3124:13333 3125:13334 3126:13335 3127:13336 3128:13337 3129:13338 3130:6664 3130:6665 3130:6666 3130:6667 3130:6668 3130:6669 3130:6670 3130:6671 3130:6672 3130:6673 3130:6674 3130:6675 3130:6676 3130:6677 3130:6678 3130:6679 3130:6680 3130:6681 3130:6682 3130:6683 3130:6684 3130:6685 3130:6686 3130:6687 3130:6688 3130:6689 3130:6690 3130:6691 3130:6692 3130:6693 3130:6694 3130:6695 3130:6696 3130:6697 3130:6698 3130:6699 3130:6700 3130:6701 3130:6702 3130:6703 3130:6704 3130:6705 3130:6706 3130:6707 3130:6708 3130:6709 3130:6710 3130:6711 3130:6712 3130:6713 3130:6714 3130:6715 3130:6716 3130:6717 3130:6718 3130:6719 3130:6720 3130:6721 3130:6722 3130:6723 3130:6724 3130:6725 3130:6726 3130:6727 3130:6728 3130:6729 3130:6730 3130:6731 3130:6732 3130:6733 3130:6734 3130:6735 3130:6736 3130:6737 3130:6738 3130:6739 3130:6740 3130:6741 3130:6742 3130:6743 3130:6744 3130:7014 3130:7015 3130:7016 3130:7017 3130:7018 3130:13339 3131:6746 3131:6747 3131:6748 3131:6991 3131:6992 3131:6993 3131:6994 3131:6995 3131:13340 3132:6751 3132:6752 3132:6753 3132:6833 3132:6834 3132:6835 3132:6836 3132:6838 3132:6839 3132:6840 3132:13341 3133:6754 3133:6755 3133:6756 3133:6757 3133:13342 3134:6760 3134:6827 3134:6828 3134:6829 3134:6830 3134:6831 3134:13343 3135:6761 3135:6762 3135:6763 3135:6764 3135:6765 3135:6766 3135:6767 3135:6768 3135:6769 3135:6770 3135:6771 3135:6772 3135:6773 3135:6774 3135:6775 3135:6776 3135:6777 3135:6778 3135:6779 3135:6780 3135:6781 3135:6782 3135:6783 3135:6784 3135:6785 3135:6786 3135:6787 3135:6788 3135:6789 3135:6790 3135:6791 3135:6792 3135:6793 3135:6794 3135:6795 3135:6796 3135:6797 3135:6798 3135:6799 3135:6800 3135:6801 3135:6802 3135:6803 3135:6804 3135:6805 3135:6806 3135:6807 3135:6808 3135:6809 3135:6810 3135:6811 3135:6812 3135:6813 3135:6814 3135:6815 3135:13344 3136:6818 3136:6819 3136:6820 3136:6821 3136:6822 3136:6823 3136:13345 3137:13346 3138:13347 3139:6841 3139:6842 3139:6843 3139:6844 3139:6846 3139:6847 3140:6852 3140:6853 3140:6854 3140:6855 3141:6857 3141:6858 3141:6859 3141:6860 3141:6861 3141:6862 3141:6973 3141:6974 3141:6975 3141:6976 3141:6978 3141:6979 3142:6864 3143:6866 3143:6967 3143:6968 3143:6969 3143:6970 3143:6971 3144:6867 3144:6868 3144:6869 3144:6870 3144:6871 3144:6872 3144:6873 3144:6874 3144:6875 3144:6876 3144:6877 3144:6878 3144:6879 3144:6880 3144:6881 3144:6882 3144:6883 3144:6884 3144:6885 3144:6886 3144:6887 3144:6888 3144:6889 3144:6890 3144:6891 3144:6892 3144:6893 3144:6894 3144:6895 3144:6896 3144:6897 3144:6898 3144:6899 3144:6900 3144:6901 3144:6902 3144:6903 3144:6904 3144:6905 3144:6906 3144:6907 3144:6908 3144:6909 3144:6910 3144:6911 3144:6912 3144:6913 3144:6914 3144:6915 3144:6916 3144:6917 3144:6918 3144:6919 3144:6920 3144:6921 3144:6922 3144:6923 3144:6924 3144:6925 3144:6926 3144:6927 3144:6928 3144:6929 3144:6930 3144:6931 3144:6932 3144:6933 3144:6934 3144:6935 3144:6936 3144:6937 3144:6938 3144:6939 3144:6940 3144:6941 3144:6942 3144:6943 3144:6944 3144:6946 3144:6947 3144:6948 3144:6949 3146:6954 3146:6955 3146:6956 3146:6957 3147:6959 3147:6960 3148:6961 3154:6980 3154:6981 3154:6982 3154:6983 3154:6985 3154:6986 3156:6999 3156:7000 3156:7001 3157:7003 3157:7004 3157:7005 3157:7006 3157:7008 3157:7009 3160:7020 3160:7021 3163:7023 3166:13660 3166:13663 3166:13664 3166:13666 3166:13667 3166:13668 3166:13673 3166:13809 3166:13810 3166:13811 3167:13661 3168:13662 3172:13676 3172:13677 3172:13678 3172:13679 3172:13680 3172:13681 3172:13683 3172:13685 3172:13686 3172:13687 3172:13688 3172:13689 3172:13690 3172:13691 3172:13692 3172:13705 3172:13791 3172:13793 3172:13794 3172:13795 3172:13796 3173:13669 3173:13670 3173:13693 3173:13694 3173:13695 3173:13696 3173:13697 3173:13698 3173:13699 3173:13700 3175:13702 3175:13703 3178:13671 3178:13672 3178:13706 3178:13707 3178:13708 3178:13709 3178:13710 3178:13711 3178:13712 3179:13714 3179:13715 3181:13718 3181:13785 3181:13786 3181:13787 3181:13788 3181:13789 3182:13719 3182:13720 3182:13721 3182:13722 3182:13723 3183:13725 3183:13726 3187:13799 3187:13800 3188:13801 3189:13803 3190:13804 3191:13805 3195:13808 3202:11097 3202:11104 3202:11106 3202:11107 3202:11108 3202:11138 3202:11164 3202:11169 3202:11170 3202:11171 3202:11172 3202:11173 3202:11174 3202:11175 3203:11098 3203:11113 3203:11114 3203:11115 3203:11116 3203:11117 3203:11118 3203:11120 3203:11122 3203:11123 3203:11124 3203:11125 3203:11126 3203:11127 3203:11128 3203:11129 3204:11099 3204:11109 3204:11110 3204:11130 3204:11131 3204:11132 3204:11133 3204:11134 3204:11135 3205:11100 3205:11139 3205:11140 3205:11141 3205:11142 3205:11143 3205:11144 3205:11145 3205:11147 3205:11149 3205:11150 3205:11151 3205:11152 3205:11153 3205:11154 3205:11155 3205:11156 3206:11101 3206:11111 3206:11157 3206:11158 3206:11159 3206:11160 3206:11161 3207:11102 3207:11137 3207:11165 3207:11166 3207:11167 3207:11168 3208:11103 3209:11163 3211:13813 3211:13814 3211:13816 3211:13817 3211:13818 3211:13924 3211:13925 3213:13821 3213:13915 3213:13916 3213:13917 3213:13918 3213:13919 3214:13822 3214:13823 3214:13824 3214:13825 3214:13826 3214:13829 3214:13830 3214:13831 3214:13832 3214:13833 3214:13834 3214:13835 3214:13836 3214:13837 3214:13838 3214:13839 3214:13840 3214:13841 3214:13842 3214:13843 3214:13844 3214:13845 3214:13846 3214:13847 3214:13848 3214:13849 3214:13850 3214:13851 3214:13852 3214:13853 3214:13854 3214:13855 3214:13856 3214:13857 3214:13858 3214:13859 3214:13860 3214:13861 3214:13862 3214:13863 3214:13864 3214:13865 3214:13866 3214:13867 3214:13868 3214:13869 3214:13870 3214:13871 3214:13872 3214:13873 3214:13874 3214:13875 3214:13876 3214:13877 3214:13878 3214:13879 3214:13880 3214:13881 3214:13882 3214:13883 3214:13884 3214:13885 3214:13886 3214:13887 3215:13890 3215:13891 3215:13892 3215:13893 3215:13894 3215:13895 3215:13896 3215:13897 3215:13900 3215:13901 3215:13902 3215:13903 3215:13904 3216:13907 3216:13908 3216:13909 3216:13910 3216:13911 3216:13912 3218:13921 3218:13922 3218:13923 3221:13577 3221:13579 3221:13580 3221:13581 3221:13657 3221:13658 3222:13586 3222:13587 3222:13588 3222:13648 3222:13649 3222:13650 3222:13651 3222:13653 3222:13654 3222:13655 3222:13656 3232:13582 3232:13583 3232:13589 3232:13590 3232:13591 3232:13592 3232:13593 3232:13594 3232:13595 3233:13598 3233:13599 3233:13600 3233:13601 3233:13602 3233:13603 3233:13604 3233:13605 3233:13606 3233:13607 3233:13608 3233:13609 3233:13610 3233:13611 3233:13612 3233:13613 3233:13614 3233:13615 3233:13616 3233:13617 3233:13618 3233:13619 3233:13620 3233:13621 3233:13622 3233:13623 3233:13624 3233:13625 3233:13626 3233:13627 3233:13628 3233:13629 3233:13630 3233:13631 3233:13632 3233:13633 3233:13634 3233:13641 3233:13642 3233:13643 3233:13644 3233:13645 3234:13647 3239:13235 3239:13236 3239:13238 3239:13239 3239:13240 3239:13242 3239:13291 3239:13292 3239:13293 3239:13294 3239:13295 3239:13296 3239:13297 3240:13243 3240:13244 3240:13245 3240:13246 3240:13247 3240:13248 3240:13249 3240:13250 3240:13251 3240:13252 3241:13255 3241:13256 3241:13257 3241:13258 3241:13259 3241:13260 3242:13264 3242:13265 3242:13266 3242:13267 3242:13268 3242:13269 3242:13270 3243:13261 3243:13273 3243:13274 3243:13275 3243:13276 3243:13277 3243:13278 3243:13279 3244:13282 3244:13283 3244:13284 3244:13285 3244:13286 3244:13287 3244:13288 3248:13927 3248:13928 3248:13930 3248:13931 3248:13932 3248:13934 3248:13989 3248:13990 3248:13991 3248:13992 3248:13993 3248:13994 3248:13995 3249:13935 3249:13936 3249:13937 3249:13938 3249:13939 3249:13940 3250:13944 3250:13945 3250:13946 3250:13947 3250:13948 3250:13949 3251:13941 3251:13953 3251:13954 3251:13955 3251:13956 3251:13957 3251:13958 3252:13950 3252:13962 3252:13963 3252:13964 3252:13965 3252:13966 3252:13967 3253:13959 3253:13971 3253:13972 3253:13973 3253:13974 3253:13975 3253:13976 3254:13968 3254:13980 3254:13981 3254:13982 3254:13983 3254:13984 3254:13985 3255:13977 3256:13986 3258:13997 3258:13998 3258:14000 3258:14001 3258:14002 3258:14004 3258:14049 3258:14050 3258:14051 3258:14052 3258:14053 3258:14054 3258:14055 3259:14005 3259:14006 3259:14007 3259:14008 3259:14009 3259:14010 3259:14011 3259:14012 3259:14013 3260:14016 3260:14017 3260:14018 3260:14019 3260:14020 3260:14021 3260:14022 3260:14023 3260:14024 3261:14027 3261:14028 3261:14029 3261:14030 3261:14031 3261:14032 3261:14033 3261:14034 3261:14035 3262:14038 3262:14039 3262:14040 3262:14041 3262:14042 3262:14043 3262:14044 3262:14045 3262:14046 3265:3321 3265:3323 3265:3324 3265:3325 3265:3344 3265:3345 3266:3327 3266:3328 3266:3329 3266:3330 3266:3331 3266:3332 3266:3337 3266:3338 3266:3339 3266:3340 3266:3342 3266:3343 3267:3333 3267:3335 3277:1335 3277:1338 3277:1340 3277:1341 3277:1342 3277:1344 3277:1400 3277:1401 3277:1402 3277:1403 3277:1404 3277:1405 3277:1406 3278:1336 3278:1345 3278:1346 3278:1347 3279:1337 3279:1348 3279:1349 3279:1350 3279:1351 3279:1352 3279:1353 3279:1354 3279:1355 3279:1356 3279:1358 3279:1359 3280:1360 3280:1361 3281:1365 3281:1366 3281:1367 3282:1368 3282:1369 3283:1371 3283:1372 3283:1373 3283:1391 3283:1392 3283:1393 3283:1394 3283:1396 3283:1397 3285:1374 3285:1375 3286:1376 3286:1377 3286:1378 3286:1379 3286:1380 3286:1381 3286:1382 3286:1383 3286:1384 3286:1386 3286:1387 3287:1388 3287:1389 3292:785 3292:786 3292:788 3292:789 3292:790 3292:803 3292:804 3294:793 3294:794 3294:795 3294:797 3294:798 3294:799 3294:800 3305:8251 3305:8254 3305:8256 3305:8257 3305:8258 3305:8293 3305:8294 3306:8252 3307:8253 3307:8261 3307:8262 3307:8263 3307:8264 3307:8265 3307:8266 3307:8268 3307:8270 3307:8271 3307:8272 3307:8273 3307:8274 3307:8275 3307:8276 3307:8277 3307:8284 3307:8286 3307:8287 3307:8288 3307:8289 3308:8278 3308:8279 3309:8280 3310:8281 3311:8282 3313:8292 *E groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyLexer.java0000644001501200150120000032166711715044502025575 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "groovy.g" -> "GroovyLexer.java"$ package org.codehaus.groovy.antlr.parser; import org.codehaus.groovy.antlr.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import antlr.CommonToken; import org.codehaus.groovy.GroovyBugError; import antlr.TokenStreamRecognitionException; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; public class GroovyLexer extends antlr.CharScanner implements GroovyTokenTypes, TokenStream { /** flag for enabling the "assert" keyword */ private boolean assertEnabled = true; /** flag for enabling the "enum" keyword */ private boolean enumEnabled = true; /** flag for including whitespace tokens (for IDE preparsing) */ private boolean whitespaceIncluded = false; /** Enable the "assert" keyword */ public void enableAssert(boolean shouldEnable) { assertEnabled = shouldEnable; } /** Query the "assert" keyword state */ public boolean isAssertEnabled() { return assertEnabled; } /** Enable the "enum" keyword */ public void enableEnum(boolean shouldEnable) { enumEnabled = shouldEnable; } /** Query the "enum" keyword state */ public boolean isEnumEnabled() { return enumEnabled; } /** Include whitespace tokens. Note that this breaks the parser. */ public void setWhitespaceIncluded(boolean z) { whitespaceIncluded = z; } /** Are whitespace tokens included? */ public boolean isWhitespaceIncluded() { return whitespaceIncluded; } { // Initialization actions performed on construction. setTabSize(1); // get rid of special tab interpretation, for IDEs and general clarity } /** Bumped when inside '[x]' or '(x)', reset inside '{x}'. See ONE_NL. */ protected int parenLevel = 0; protected int suppressNewline = 0; // be really mean to newlines inside strings protected static final int SCS_TYPE = 3, SCS_VAL = 4, SCS_LIT = 8, SCS_LIMIT = 16; protected static final int SCS_SQ_TYPE = 0, SCS_TQ_TYPE = 1, SCS_RE_TYPE = 2, SCS_DRE_TYPE = 3; protected int stringCtorState = 0; // hack string and regexp constructor boundaries /** Push parenLevel here and reset whenever inside '{x}'. */ protected ArrayList parenLevelStack = new ArrayList(); protected int lastSigTokenType = EOF; // last returned non-whitespace token public void setTokenObjectClass(String name) {/*ignore*/} protected Token makeToken(int t) { GroovySourceToken tok = new GroovySourceToken(t); tok.setColumn(inputState.getTokenStartColumn()); tok.setLine(inputState.getTokenStartLine()); tok.setColumnLast(inputState.getColumn()); tok.setLineLast(inputState.getLine()); return tok; } protected void pushParenLevel() { parenLevelStack.add(Integer.valueOf(parenLevel*SCS_LIMIT + stringCtorState)); parenLevel = 0; stringCtorState = 0; } protected void popParenLevel() { int npl = parenLevelStack.size(); if (npl == 0) return; int i = ((Integer) parenLevelStack.remove(--npl)).intValue(); parenLevel = i / SCS_LIMIT; stringCtorState = i % SCS_LIMIT; } protected void restartStringCtor(boolean expectLiteral) { if (stringCtorState != 0) { stringCtorState = (expectLiteral? SCS_LIT: SCS_VAL) + (stringCtorState & SCS_TYPE); } } protected boolean allowRegexpLiteral() { return !isExpressionEndingToken(lastSigTokenType); } /** Return true for an operator or punctuation which can end an expression. * Return true for keywords, identifiers, and literals. * Return true for tokens which can end expressions (right brackets, ++, --). * Return false for EOF and all other operator and punctuation tokens. * Used to suppress the recognition of /foo/ as opposed to the simple division operator '/'. */ // Cf. 'constant' and 'balancedBrackets' rules in the grammar.) protected static boolean isExpressionEndingToken(int ttype) { switch (ttype) { case INC: // x++ / y case DEC: // x-- / y case RPAREN: // (x) / y case RBRACK: // f[x] / y case RCURLY: // f{x} / y case STRING_LITERAL: // "x" / y case STRING_CTOR_END: // "$x" / y case NUM_INT: // 0 / y case NUM_FLOAT: // 0f / y case NUM_LONG: // 0l / y case NUM_DOUBLE: // 0.0 / y case NUM_BIG_INT: // 0g / y case NUM_BIG_DECIMAL: // 0.0g / y case IDENT: // x / y // and a bunch of keywords (all of them; no sense picking and choosing): case LITERAL_as: case LITERAL_assert: case LITERAL_boolean: case LITERAL_break: case LITERAL_byte: case LITERAL_case: case LITERAL_catch: case LITERAL_char: case LITERAL_class: case LITERAL_continue: case LITERAL_def: case LITERAL_default: case LITERAL_double: case LITERAL_else: case LITERAL_enum: case LITERAL_extends: case LITERAL_false: case LITERAL_finally: case LITERAL_float: case LITERAL_for: case LITERAL_if: case LITERAL_implements: case LITERAL_import: case LITERAL_in: case LITERAL_instanceof: case LITERAL_int: case LITERAL_interface: case LITERAL_long: case LITERAL_native: case LITERAL_new: case LITERAL_null: case LITERAL_package: case LITERAL_private: case LITERAL_protected: case LITERAL_public: case LITERAL_return: case LITERAL_short: case LITERAL_static: case LITERAL_super: case LITERAL_switch: case LITERAL_synchronized: case LITERAL_this: case LITERAL_threadsafe: case LITERAL_throw: case LITERAL_throws: case LITERAL_transient: case LITERAL_true: case LITERAL_try: case LITERAL_void: case LITERAL_volatile: case LITERAL_while: return true; default: return false; } } protected void newlineCheck(boolean check) throws RecognitionException { if (check && suppressNewline > 0) { require(suppressNewline == 0, "end of line reached within a simple string 'x' or \"x\" or /x/", "for multi-line literals, use triple quotes '''x''' or \"\"\"x\"\"\" or /x/ or $/x/$"); suppressNewline = 0; // shut down any flood of errors } newline(); } protected boolean atValidDollarEscape() throws CharStreamException { // '$' (('*')? ('{' | LETTER)) => int k = 1; char lc = LA(k++); if (lc != '$') return false; lc = LA(k++); if (lc == '*') lc = LA(k++); return (lc == '{' || (lc != '$' && Character.isJavaIdentifierStart(lc))); } protected boolean atDollarDollarEscape() throws CharStreamException { return LA(1) == '$' && LA(2) == '$'; } protected boolean atDollarSlashEscape() throws CharStreamException { return LA(1) == '$' && LA(2) == '/'; } /** This is a bit of plumbing which resumes collection of string constructor bodies, * after an embedded expression has been parsed. * Usage: new GroovyRecognizer(new GroovyLexer(in).plumb()). */ public TokenStream plumb() { return new TokenStream() { public Token nextToken() throws TokenStreamException { if (stringCtorState >= SCS_LIT) { // This goo is modeled upon the ANTLR code for nextToken: int quoteType = (stringCtorState & SCS_TYPE); stringCtorState = 0; // get out of this mode, now resetText(); try { switch (quoteType) { case SCS_SQ_TYPE: mSTRING_CTOR_END(true, /*fromStart:*/false, false); break; case SCS_TQ_TYPE: mSTRING_CTOR_END(true, /*fromStart:*/false, true); break; case SCS_RE_TYPE: mREGEXP_CTOR_END(true, /*fromStart:*/false); break; case SCS_DRE_TYPE: mDOLLAR_REGEXP_CTOR_END(true, /*fromStart:*/false); break; default: throw new AssertionError(false); } lastSigTokenType = _returnToken.getType(); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } Token token = GroovyLexer.this.nextToken(); int lasttype = token.getType(); if (whitespaceIncluded) { switch (lasttype) { // filter out insignificant types case WS: case ONE_NL: case SL_COMMENT: case ML_COMMENT: lasttype = lastSigTokenType; // back up! } } lastSigTokenType = lasttype; return token; } }; } // stuff to adjust ANTLR's tracing machinery public static boolean tracing = false; // only effective if antlr.Tool is run with -traceLexer public void traceIn(String rname) throws CharStreamException { if (!GroovyLexer.tracing) return; super.traceIn(rname); } public void traceOut(String rname) throws CharStreamException { if (!GroovyLexer.tracing) return; if (_returnToken != null) rname += tokenStringOf(_returnToken); super.traceOut(rname); } private static java.util.HashMap ttypes; private static String tokenStringOf(Token t) { if (ttypes == null) { java.util.HashMap map = new java.util.HashMap(); java.lang.reflect.Field[] fields = GroovyTokenTypes.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getType() != int.class) continue; try { map.put(fields[i].get(null), fields[i].getName()); } catch (IllegalAccessException ee) { } } ttypes = map; } Integer tt = Integer.valueOf(t.getType()); Object ttn = ttypes.get(tt); if (ttn == null) ttn = "<"+tt+">"; return "["+ttn+",\""+t.getText()+"\"]"; } protected GroovyRecognizer parser; // little-used link; TODO: get rid of private void require(boolean z, String problem, String solution) throws SemanticException { // TODO: Direct to a common error handler, rather than through the parser. if (!z) parser.requireFailed(problem, solution); } public GroovyLexer(InputStream in) { this(new ByteBuffer(in)); } public GroovyLexer(Reader in) { this(new CharBuffer(in)); } public GroovyLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public GroovyLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); literals.put(new ANTLRHashString("byte", this), new Integer(102)); literals.put(new ANTLRHashString("public", this), new Integer(112)); literals.put(new ANTLRHashString("case", this), new Integer(145)); literals.put(new ANTLRHashString("short", this), new Integer(104)); literals.put(new ANTLRHashString("break", this), new Integer(139)); literals.put(new ANTLRHashString("while", this), new Integer(134)); literals.put(new ANTLRHashString("new", this), new Integer(154)); literals.put(new ANTLRHashString("instanceof", this), new Integer(153)); literals.put(new ANTLRHashString("implements", this), new Integer(127)); literals.put(new ANTLRHashString("synchronized", this), new Integer(117)); literals.put(new ANTLRHashString("const", this), new Integer(40)); literals.put(new ANTLRHashString("float", this), new Integer(106)); literals.put(new ANTLRHashString("package", this), new Integer(78)); literals.put(new ANTLRHashString("return", this), new Integer(138)); literals.put(new ANTLRHashString("throw", this), new Integer(141)); literals.put(new ANTLRHashString("null", this), new Integer(155)); literals.put(new ANTLRHashString("def", this), new Integer(81)); literals.put(new ANTLRHashString("threadsafe", this), new Integer(116)); literals.put(new ANTLRHashString("protected", this), new Integer(113)); literals.put(new ANTLRHashString("class", this), new Integer(89)); literals.put(new ANTLRHashString("throws", this), new Integer(126)); literals.put(new ANTLRHashString("do", this), new Integer(41)); literals.put(new ANTLRHashString("strictfp", this), new Integer(42)); literals.put(new ANTLRHashString("super", this), new Integer(95)); literals.put(new ANTLRHashString("transient", this), new Integer(114)); literals.put(new ANTLRHashString("native", this), new Integer(115)); literals.put(new ANTLRHashString("interface", this), new Integer(90)); literals.put(new ANTLRHashString("final", this), new Integer(37)); literals.put(new ANTLRHashString("if", this), new Integer(132)); literals.put(new ANTLRHashString("double", this), new Integer(108)); literals.put(new ANTLRHashString("volatile", this), new Integer(118)); literals.put(new ANTLRHashString("as", this), new Integer(110)); literals.put(new ANTLRHashString("assert", this), new Integer(142)); literals.put(new ANTLRHashString("catch", this), new Integer(148)); literals.put(new ANTLRHashString("try", this), new Integer(146)); literals.put(new ANTLRHashString("goto", this), new Integer(39)); literals.put(new ANTLRHashString("enum", this), new Integer(91)); literals.put(new ANTLRHashString("int", this), new Integer(105)); literals.put(new ANTLRHashString("for", this), new Integer(136)); literals.put(new ANTLRHashString("extends", this), new Integer(94)); literals.put(new ANTLRHashString("boolean", this), new Integer(101)); literals.put(new ANTLRHashString("char", this), new Integer(103)); literals.put(new ANTLRHashString("private", this), new Integer(111)); literals.put(new ANTLRHashString("default", this), new Integer(125)); literals.put(new ANTLRHashString("false", this), new Integer(152)); literals.put(new ANTLRHashString("this", this), new Integer(128)); literals.put(new ANTLRHashString("static", this), new Integer(80)); literals.put(new ANTLRHashString("abstract", this), new Integer(38)); literals.put(new ANTLRHashString("continue", this), new Integer(140)); literals.put(new ANTLRHashString("finally", this), new Integer(147)); literals.put(new ANTLRHashString("else", this), new Integer(133)); literals.put(new ANTLRHashString("import", this), new Integer(79)); literals.put(new ANTLRHashString("in", this), new Integer(137)); literals.put(new ANTLRHashString("void", this), new Integer(100)); literals.put(new ANTLRHashString("switch", this), new Integer(135)); literals.put(new ANTLRHashString("true", this), new Integer(156)); literals.put(new ANTLRHashString("long", this), new Integer(107)); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case '(': { mLPAREN(true); theRetToken=_returnToken; break; } case ')': { mRPAREN(true); theRetToken=_returnToken; break; } case '[': { mLBRACK(true); theRetToken=_returnToken; break; } case ']': { mRBRACK(true); theRetToken=_returnToken; break; } case '{': { mLCURLY(true); theRetToken=_returnToken; break; } case '}': { mRCURLY(true); theRetToken=_returnToken; break; } case ':': { mCOLON(true); theRetToken=_returnToken; break; } case ',': { mCOMMA(true); theRetToken=_returnToken; break; } case '~': { mBNOT(true); theRetToken=_returnToken; break; } case ';': { mSEMI(true); theRetToken=_returnToken; break; } case '\t': case '\u000c': case ' ': case '\\': { mWS(true); theRetToken=_returnToken; break; } case '\n': case '\r': { mNLS(true); theRetToken=_returnToken; break; } case '"': case '\'': { mSTRING_LITERAL(true); theRetToken=_returnToken; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mNUM_INT(true); theRetToken=_returnToken; break; } case '@': { mAT(true); theRetToken=_returnToken; break; } default: if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='>') && (LA(4)=='=')) { mBSR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='=') && (LA(3)=='>')) { mCOMPARE_TO(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (LA(2)=='=') && (LA(3)=='=')) { mIDENTICAL(true); theRetToken=_returnToken; } else if ((LA(1)=='!') && (LA(2)=='=') && (LA(3)=='=')) { mNOT_IDENTICAL(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='=')) { mSR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (LA(3)=='>') && (true)) { mBSR(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='<') && (LA(3)=='=')) { mSL_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (LA(2)=='.') && (LA(3)=='<')) { mRANGE_EXCLUSIVE(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (LA(2)=='.') && (LA(3)=='.')) { mTRIPLE_DOT(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (LA(2)=='=') && (LA(3)=='~')) { mREGEX_MATCH(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (LA(2)=='*') && (LA(3)=='=')) { mSTAR_STAR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (LA(2)=='=') && (true)) { mEQUAL(true); theRetToken=_returnToken; } else if ((LA(1)=='!') && (LA(2)=='=') && (true)) { mNOT_EQUAL(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (LA(2)=='=')) { mPLUS_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (LA(2)=='+')) { mINC(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (LA(2)=='=')) { mMINUS_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (LA(2)=='-')) { mDEC(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (LA(2)=='=')) { mSTAR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='%') && (LA(2)=='=')) { mMOD_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='>') && (true)) { mSR(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (LA(2)=='=')) { mGE(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='<') && (true)) { mSL(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (LA(2)=='=') && (true)) { mLE(true); theRetToken=_returnToken; } else if ((LA(1)=='^') && (LA(2)=='=')) { mBXOR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (LA(2)=='=')) { mBOR_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (LA(2)=='|')) { mLOR(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (LA(2)=='=')) { mBAND_ASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (LA(2)=='&')) { mLAND(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (LA(2)=='.') && (true)) { mRANGE_INCLUSIVE(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (LA(2)=='.')) { mSPREAD_DOT(true); theRetToken=_returnToken; } else if ((LA(1)=='?') && (LA(2)=='.')) { mOPTIONAL_DOT(true); theRetToken=_returnToken; } else if ((LA(1)=='?') && (LA(2)==':')) { mELVIS_OPERATOR(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (LA(2)=='&')) { mMEMBER_POINTER(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (LA(2)=='~')) { mREGEX_FIND(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (LA(2)=='*') && (true)) { mSTAR_STAR(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (LA(2)=='>')) { mCLOSABLE_BLOCK_OP(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='/')) { mSL_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='*')) { mML_COMMENT(true); theRetToken=_returnToken; } else if (((LA(1)=='$') && (LA(2)=='/'))&&(allowRegexpLiteral())) { mDOLLAR_REGEXP_LITERAL(true); theRetToken=_returnToken; } else if ((LA(1)=='?') && (true)) { mQUESTION(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (true)) { mDOT(true); theRetToken=_returnToken; } else if ((LA(1)=='=') && (true)) { mASSIGN(true); theRetToken=_returnToken; } else if ((LA(1)=='!') && (true)) { mLNOT(true); theRetToken=_returnToken; } else if ((LA(1)=='+') && (true)) { mPLUS(true); theRetToken=_returnToken; } else if ((LA(1)=='-') && (true)) { mMINUS(true); theRetToken=_returnToken; } else if ((LA(1)=='*') && (true)) { mSTAR(true); theRetToken=_returnToken; } else if ((LA(1)=='%') && (true)) { mMOD(true); theRetToken=_returnToken; } else if ((LA(1)=='>') && (true)) { mGT(true); theRetToken=_returnToken; } else if ((LA(1)=='<') && (true)) { mLT(true); theRetToken=_returnToken; } else if ((LA(1)=='^') && (true)) { mBXOR(true); theRetToken=_returnToken; } else if ((LA(1)=='|') && (true)) { mBOR(true); theRetToken=_returnToken; } else if ((LA(1)=='&') && (true)) { mBAND(true); theRetToken=_returnToken; } else if (((LA(1)=='#'))&&(getLine() == 1 && getColumn() == 1)) { mSH_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (true)) { mREGEXP_LITERAL(true); theRetToken=_returnToken; } else if ((_tokenSet_0.member(LA(1))) && (true)) { mIDENT(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mQUESTION(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = QUESTION; int _saveIndex; match('?'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LPAREN; int _saveIndex; match('('); if ( inputState.guessing==0 ) { ++parenLevel; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RPAREN; int _saveIndex; match(')'); if ( inputState.guessing==0 ) { --parenLevel; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LBRACK; int _saveIndex; match('['); if ( inputState.guessing==0 ) { ++parenLevel; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RBRACK; int _saveIndex; match(']'); if ( inputState.guessing==0 ) { --parenLevel; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLCURLY(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LCURLY; int _saveIndex; match('{'); if ( inputState.guessing==0 ) { pushParenLevel(); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRCURLY(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RCURLY; int _saveIndex; match('}'); if ( inputState.guessing==0 ) { popParenLevel(); if(stringCtorState!=0) restartStringCtor(true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOLON(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COLON; int _saveIndex; match(':'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMMA(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMA; int _saveIndex; match(','); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOT; int _saveIndex; match('.'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ASSIGN; int _saveIndex; match('='); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMPARE_TO(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMPARE_TO; int _saveIndex; match("<=>"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mEQUAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EQUAL; int _saveIndex; match("=="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mIDENTICAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = IDENTICAL; int _saveIndex; match("==="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLNOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LNOT; int _saveIndex; match('!'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBNOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BNOT; int _saveIndex; match('~'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNOT_EQUAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NOT_EQUAL; int _saveIndex; match("!="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNOT_IDENTICAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NOT_IDENTICAL; int _saveIndex; match("!=="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mDIV(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DIV; int _saveIndex; match('/'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mDIV_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DIV_ASSIGN; int _saveIndex; match("/="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS; int _saveIndex; match('+'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS_ASSIGN; int _saveIndex; match("+="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mINC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = INC; int _saveIndex; match("++"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMINUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MINUS; int _saveIndex; match('-'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMINUS_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MINUS_ASSIGN; int _saveIndex; match("-="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDEC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DEC; int _saveIndex; match("--"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR; int _saveIndex; match('*'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR_ASSIGN; int _saveIndex; match("*="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMOD(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MOD; int _saveIndex; match('%'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMOD_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MOD_ASSIGN; int _saveIndex; match("%="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SR; int _saveIndex; match(">>"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SR_ASSIGN; int _saveIndex; match(">>="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBSR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BSR; int _saveIndex; match(">>>"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBSR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BSR_ASSIGN; int _saveIndex; match(">>>="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mGE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = GE; int _saveIndex; match(">="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mGT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = GT; int _saveIndex; match(">"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL; int _saveIndex; match("<<"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_ASSIGN; int _saveIndex; match("<<="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LE; int _saveIndex; match("<="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LT; int _saveIndex; match('<'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBXOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BXOR; int _saveIndex; match('^'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBXOR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BXOR_ASSIGN; int _saveIndex; match("^="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BOR; int _saveIndex; match('|'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBOR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BOR_ASSIGN; int _saveIndex; match("|="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LOR; int _saveIndex; match("||"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBAND(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BAND; int _saveIndex; match('&'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBAND_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BAND_ASSIGN; int _saveIndex; match("&="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLAND(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LAND; int _saveIndex; match("&&"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSEMI(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SEMI; int _saveIndex; match(';'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mDOLLAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOLLAR; int _saveIndex; match('$'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRANGE_INCLUSIVE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RANGE_INCLUSIVE; int _saveIndex; match(".."); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRANGE_EXCLUSIVE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RANGE_EXCLUSIVE; int _saveIndex; match("..<"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mTRIPLE_DOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = TRIPLE_DOT; int _saveIndex; match("..."); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSPREAD_DOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SPREAD_DOT; int _saveIndex; match("*."); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mOPTIONAL_DOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = OPTIONAL_DOT; int _saveIndex; match("?."); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mELVIS_OPERATOR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ELVIS_OPERATOR; int _saveIndex; match("?:"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mMEMBER_POINTER(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = MEMBER_POINTER; int _saveIndex; match(".&"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mREGEX_FIND(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = REGEX_FIND; int _saveIndex; match("=~"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mREGEX_MATCH(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = REGEX_MATCH; int _saveIndex; match("==~"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR_STAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR_STAR; int _saveIndex; match("**"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR_STAR_ASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR_STAR_ASSIGN; int _saveIndex; match("**="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCLOSABLE_BLOCK_OP(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = CLOSABLE_BLOCK_OP; int _saveIndex; match("->"); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mWS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS; int _saveIndex; { int _cnt641=0; _loop641: do { if ((LA(1)=='\\') && (LA(2)=='\n'||LA(2)=='\r') && (true) && (true)) { match('\\'); mONE_NL(false,false); } else if ((LA(1)==' ') && (true) && (true) && (true)) { match(' '); } else if ((LA(1)=='\t') && (true) && (true) && (true)) { match('\t'); } else if ((LA(1)=='\u000c') && (true) && (true) && (true)) { match('\f'); } else { if ( _cnt641>=1 ) { break _loop641; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt641++; } while (true); } if ( inputState.guessing==0 ) { if (!whitespaceIncluded) _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mONE_NL(boolean _createToken, boolean check ) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ONE_NL; int _saveIndex; { if ((LA(1)=='\r') && (LA(2)=='\n') && (true) && (true)) { _saveIndex=text.length(); match("\r\n"); text.setLength(_saveIndex); } else if ((LA(1)=='\r') && (true) && (true) && (true)) { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); } else if ((LA(1)=='\n')) { _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { // update current line number for error reporting newlineCheck(check); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNLS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NLS; int _saveIndex; mONE_NL(false,true); { if (((LA(1)=='\t'||LA(1)=='\n'||LA(1)=='\u000c'||LA(1)=='\r'||LA(1)==' '||LA(1)=='/'||LA(1)=='\\'))&&(!whitespaceIncluded)) { { int _cnt647=0; _loop647: do { switch ( LA(1)) { case '\n': case '\r': { mONE_NL(false,true); break; } case '\t': case '\u000c': case ' ': case '\\': { mWS(false); break; } default: if ((LA(1)=='/') && (LA(2)=='/')) { mSL_COMMENT(false); } else if ((LA(1)=='/') && (LA(2)=='*')) { mML_COMMENT(false); } else { if ( _cnt647>=1 ) { break _loop647; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt647++; } while (true); } } else { } } if ( inputState.guessing==0 ) { if (whitespaceIncluded) { // keep the token as-is } else if (parenLevel != 0) { // when directly inside parens, all newlines are ignored here _ttype = Token.SKIP; } else { // inside {...}, newlines must be explicitly matched as 'nls!' text.setLength(_begin); text.append(""); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_COMMENT; int _saveIndex; match("//"); { _loop651: do { if ((_tokenSet_1.member(LA(1))) && (true) && (true) && (true)) { { match(_tokenSet_1); } } else { break _loop651; } } while (true); } if ( inputState.guessing==0 ) { if (!whitespaceIncluded) _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mML_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ML_COMMENT; int _saveIndex; match("/*"); { _loop661: do { boolean synPredMatched659 = false; if (((LA(1)=='*') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true))) { int _m659 = mark(); synPredMatched659 = true; inputState.guessing++; try { { match('*'); matchNot('/'); } } catch (RecognitionException pe) { synPredMatched659 = false; } rewind(_m659); inputState.guessing--; } if ( synPredMatched659 ) { match('*'); } else if ((LA(1)=='\n'||LA(1)=='\r')) { mONE_NL(false,true); } else if ((_tokenSet_2.member(LA(1)))) { { match(_tokenSet_2); } } else { break _loop661; } } while (true); } match("*/"); if ( inputState.guessing==0 ) { if (!whitespaceIncluded) _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSH_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SH_COMMENT; int _saveIndex; if (!(getLine() == 1 && getColumn() == 1)) throw new SemanticException("getLine() == 1 && getColumn() == 1"); match("#!"); { _loop655: do { if ((_tokenSet_1.member(LA(1)))) { { match(_tokenSet_1); } } else { break _loop655; } } while (true); } if ( inputState.guessing==0 ) { if (!whitespaceIncluded) _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTRING_LITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING_LITERAL; int _saveIndex; int tt=0; boolean synPredMatched664 = false; if (((LA(1)=='\'') && (LA(2)=='\'') && (LA(3)=='\'') && ((LA(4) >= '\u0000' && LA(4) <= '\ufffe')))) { int _m664 = mark(); synPredMatched664 = true; inputState.guessing++; try { { match("'''"); } } catch (RecognitionException pe) { synPredMatched664 = false; } rewind(_m664); inputState.guessing--; } if ( synPredMatched664 ) { _saveIndex=text.length(); match("'''"); text.setLength(_saveIndex); { _loop669: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '"': { match('"'); break; } case '$': { match('$'); break; } case '\n': case '\r': { mSTRING_NL(false,true); break; } default: boolean synPredMatched668 = false; if (((LA(1)=='\'') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0000' && LA(4) <= '\ufffe')))) { int _m668 = mark(); synPredMatched668 = true; inputState.guessing++; try { { match('\''); { if ((_tokenSet_3.member(LA(1)))) { matchNot('\''); } else if ((LA(1)=='\'')) { match('\''); matchNot('\''); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } catch (RecognitionException pe) { synPredMatched668 = false; } rewind(_m668); inputState.guessing--; } if ( synPredMatched668 ) { match('\''); } else if ((_tokenSet_4.member(LA(1)))) { mSTRING_CH(false); } else { break _loop669; } } } while (true); } _saveIndex=text.length(); match("'''"); text.setLength(_saveIndex); } else { boolean synPredMatched673 = false; if (((LA(1)=='"') && (LA(2)=='"') && (LA(3)=='"') && ((LA(4) >= '\u0000' && LA(4) <= '\ufffe')))) { int _m673 = mark(); synPredMatched673 = true; inputState.guessing++; try { { match("\"\"\""); } } catch (RecognitionException pe) { synPredMatched673 = false; } rewind(_m673); inputState.guessing--; } if ( synPredMatched673 ) { _saveIndex=text.length(); match("\"\"\""); text.setLength(_saveIndex); tt=mSTRING_CTOR_END(false,true, /*tripleQuote:*/ true); if ( inputState.guessing==0 ) { _ttype = tt; } } else if ((LA(1)=='\'') && (_tokenSet_1.member(LA(2))) && (true) && (true)) { _saveIndex=text.length(); match('\''); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { ++suppressNewline; } { _loop671: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '"': { match('"'); break; } case '$': { match('$'); break; } default: if ((_tokenSet_4.member(LA(1)))) { mSTRING_CH(false); } else { break _loop671; } } } while (true); } if ( inputState.guessing==0 ) { --suppressNewline; } _saveIndex=text.length(); match('\''); text.setLength(_saveIndex); } else if ((LA(1)=='"') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true)) { _saveIndex=text.length(); match('"'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { ++suppressNewline; } tt=mSTRING_CTOR_END(false,true, /*tripleQuote:*/ false); if ( inputState.guessing==0 ) { _ttype = tt; } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mSTRING_CH(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING_CH; int _saveIndex; { match(_tokenSet_4); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mESC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC; int _saveIndex; if ((LA(1)=='\\') && (LA(2)=='"'||LA(2)=='$'||LA(2)=='\''||LA(2)=='0'||LA(2)=='1'||LA(2)=='2'||LA(2)=='3'||LA(2)=='4'||LA(2)=='5'||LA(2)=='6'||LA(2)=='7'||LA(2)=='\\'||LA(2)=='b'||LA(2)=='f'||LA(2)=='n'||LA(2)=='r'||LA(2)=='t'||LA(2)=='u')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); { switch ( LA(1)) { case 'n': { match('n'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append("\n"); } break; } case 'r': { match('r'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append("\r"); } break; } case 't': { match('t'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append("\t"); } break; } case 'b': { match('b'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append("\b"); } break; } case 'f': { match('f'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append("\f"); } break; } case '"': { match('"'); break; } case '\'': { match('\''); break; } case '\\': { match('\\'); break; } case '$': { match('$'); break; } case 'u': { { int _cnt715=0; _loop715: do { if ((LA(1)=='u')) { match('u'); } else { if ( _cnt715>=1 ) { break _loop715; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt715++; } while (true); } if ( inputState.guessing==0 ) { text.setLength(_begin); text.append(""); } mHEX_DIGIT(false); mHEX_DIGIT(false); mHEX_DIGIT(false); mHEX_DIGIT(false); if ( inputState.guessing==0 ) { char ch = (char)Integer.parseInt(new String(text.getBuffer(),_begin,text.length()-_begin),16); text.setLength(_begin); text.append(ch); } break; } case '0': case '1': case '2': case '3': { matchRange('0','3'); { if (((LA(1) >= '0' && LA(1) <= '7')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true)) { matchRange('0','7'); { if (((LA(1) >= '0' && LA(1) <= '7')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true)) { matchRange('0','7'); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { char ch = (char)Integer.parseInt(new String(text.getBuffer(),_begin,text.length()-_begin),8); text.setLength(_begin); text.append(ch); } break; } case '4': case '5': case '6': case '7': { matchRange('4','7'); { if (((LA(1) >= '0' && LA(1) <= '7')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true)) { matchRange('0','7'); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { char ch = (char)Integer.parseInt(new String(text.getBuffer(),_begin,text.length()-_begin),8); text.setLength(_begin); text.append(ch); } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } else if ((LA(1)=='\\') && (LA(2)=='\n'||LA(2)=='\r')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); _saveIndex=text.length(); mONE_NL(false,false); text.setLength(_saveIndex); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mSTRING_NL(boolean _createToken, boolean allowNewline ) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING_NL; int _saveIndex; if ( inputState.guessing==0 ) { if (!allowNewline) throw new MismatchedCharException('\n', '\n', true, this); } mONE_NL(false,false); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append('\n'); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final int mSTRING_CTOR_END(boolean _createToken, boolean fromStart, boolean tripleQuote ) throws RecognitionException, CharStreamException, TokenStreamException { int tt=STRING_CTOR_END; int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING_CTOR_END; int _saveIndex; boolean dollarOK = false; { _loop679: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '\'': { match('\''); break; } case '\n': case '\r': { mSTRING_NL(false,tripleQuote); break; } default: boolean synPredMatched678 = false; if ((((LA(1)=='"') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true))&&(tripleQuote))) { int _m678 = mark(); synPredMatched678 = true; inputState.guessing++; try { { match('"'); { if ((_tokenSet_5.member(LA(1)))) { matchNot('"'); } else if ((LA(1)=='"')) { match('"'); matchNot('"'); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } catch (RecognitionException pe) { synPredMatched678 = false; } rewind(_m678); inputState.guessing--; } if ( synPredMatched678 ) { match('"'); } else if ((_tokenSet_4.member(LA(1)))) { mSTRING_CH(false); } else { break _loop679; } } } while (true); } { switch ( LA(1)) { case '"': { { if (((LA(1)=='"') && (LA(2)=='"'))&&( tripleQuote )) { _saveIndex=text.length(); match("\"\"\""); text.setLength(_saveIndex); } else if (((LA(1)=='"') && (true))&&( !tripleQuote )) { _saveIndex=text.length(); match("\""); text.setLength(_saveIndex); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { if (fromStart) tt = STRING_LITERAL; // plain string literal! if (!tripleQuote) {--suppressNewline;} // done with string constructor! //assert(stringCtorState == 0); } break; } case '$': { if ( inputState.guessing==0 ) { dollarOK = atValidDollarEscape(); } _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { require(dollarOK, "illegal string body character after dollar sign", "either escape a literal dollar sign \"\\$5\" or bracket the value expression \"${5}\""); // Yes, it's a string constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + (tripleQuote? SCS_TQ_TYPE: SCS_SQ_TYPE); } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = tt; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return tt; } public final void mREGEXP_LITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = REGEXP_LITERAL; int _saveIndex; int tt=0; if (((LA(1)=='/') && (_tokenSet_6.member(LA(2))) && (true) && (true))&&(allowRegexpLiteral())) { _saveIndex=text.length(); match('/'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { ++suppressNewline; } { if (((LA(1)=='$') && (_tokenSet_7.member(LA(2))))&&(!atValidDollarEscape())) { match('$'); tt=mREGEXP_CTOR_END(false,true); } else if ((_tokenSet_8.member(LA(1)))) { mREGEXP_SYMBOL(false); tt=mREGEXP_CTOR_END(false,true); } else if ((LA(1)=='$') && (true)) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { // Yes, it's a regexp constructor, and we've got a value part. tt = STRING_CTOR_START; stringCtorState = SCS_VAL + SCS_RE_TYPE; } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { _ttype = tt; } } else if ((LA(1)=='/') && (LA(2)=='=') && (true) && (true)) { mDIV_ASSIGN(false); if ( inputState.guessing==0 ) { _ttype = DIV_ASSIGN; } } else if ((LA(1)=='/') && (true)) { mDIV(false); if ( inputState.guessing==0 ) { _ttype = DIV; } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mREGEXP_SYMBOL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = REGEXP_SYMBOL; int _saveIndex; { if ((LA(1)=='\\') && (LA(2)=='/') && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true)) { match('\\'); match('/'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append('/'); } } else if ((LA(1)=='\\') && (LA(2)=='\n'||LA(2)=='\r') && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true)) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); _saveIndex=text.length(); mONE_NL(false,false); text.setLength(_saveIndex); } else if (((LA(1)=='\\') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true))&&( LA(2)!='/' && LA(2)!='\n' && LA(2)!='\r' )) { match('\\'); } else if ((_tokenSet_9.member(LA(1)))) { { match(_tokenSet_9); } } else if ((LA(1)=='\n'||LA(1)=='\r')) { mSTRING_NL(false,true); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop706: do { if ((LA(1)=='*')) { match('*'); } else { break _loop706; } } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final int mREGEXP_CTOR_END(boolean _createToken, boolean fromStart ) throws RecognitionException, CharStreamException, TokenStreamException { int tt=STRING_CTOR_END; int _ttype; Token _token=null; int _begin=text.length(); _ttype = REGEXP_CTOR_END; int _saveIndex; { _loop690: do { if (((LA(1)=='$') && (_tokenSet_7.member(LA(2))))&&(!atValidDollarEscape())) { match('$'); } else if ((_tokenSet_8.member(LA(1)))) { mREGEXP_SYMBOL(false); } else { break _loop690; } } while (true); } { switch ( LA(1)) { case '/': { _saveIndex=text.length(); match('/'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { if (fromStart) tt = STRING_LITERAL; // plain regexp literal! {--suppressNewline;} // done with regexp constructor! //assert(stringCtorState == 0); } break; } case '$': { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { // Yes, it's a regexp constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + SCS_RE_TYPE; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = tt; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return tt; } public final void mDOLLAR_REGEXP_LITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOLLAR_REGEXP_LITERAL; int _saveIndex; int tt=0; if (!(allowRegexpLiteral())) throw new SemanticException("allowRegexpLiteral()"); _saveIndex=text.length(); match("$/"); text.setLength(_saveIndex); { if (((LA(1)=='$') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')))&&(!atValidDollarEscape())) { match('$'); tt=mDOLLAR_REGEXP_CTOR_END(false,true); } else if ((_tokenSet_10.member(LA(1)))) { mDOLLAR_REGEXP_SYMBOL(false); tt=mDOLLAR_REGEXP_CTOR_END(false,true); } else if ((LA(1)=='$') && (true)) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { // Yes, it's a regexp constructor, and we've got a value part. tt = STRING_CTOR_START; stringCtorState = SCS_VAL + SCS_DRE_TYPE; } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { _ttype = tt; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mDOLLAR_REGEXP_SYMBOL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOLLAR_REGEXP_SYMBOL; int _saveIndex; { switch ( LA(1)) { case '/': { match('/'); break; } case '\n': case '\r': { mSTRING_NL(false,true); break; } default: if ((LA(1)=='\\') && (LA(2)=='\n'||LA(2)=='\r') && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true)) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); _saveIndex=text.length(); mONE_NL(false,false); text.setLength(_saveIndex); } else if (((LA(1)=='\\') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true))&&( LA(2)!='\n' && LA(2)!='\r' )) { match('\\'); } else if ((_tokenSet_11.member(LA(1)))) { { match(_tokenSet_11); } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final int mDOLLAR_REGEXP_CTOR_END(boolean _createToken, boolean fromStart ) throws RecognitionException, CharStreamException, TokenStreamException { int tt=STRING_CTOR_END; int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOLLAR_REGEXP_CTOR_END; int _saveIndex; { _loop698: do { boolean synPredMatched695 = false; if (((LA(1)=='$') && (LA(2)=='/') && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true))) { int _m695 = mark(); synPredMatched695 = true; inputState.guessing++; try { { match('$'); match('/'); } } catch (RecognitionException pe) { synPredMatched695 = false; } rewind(_m695); inputState.guessing--; } if ( synPredMatched695 ) { mESCAPED_SLASH(false); } else { boolean synPredMatched697 = false; if (((LA(1)=='$') && (LA(2)=='$') && ((LA(3) >= '\u0000' && LA(3) <= '\ufffe')) && (true))) { int _m697 = mark(); synPredMatched697 = true; inputState.guessing++; try { { match('$'); match('$'); } } catch (RecognitionException pe) { synPredMatched697 = false; } rewind(_m697); inputState.guessing--; } if ( synPredMatched697 ) { mESCAPED_DOLLAR(false); } else if (((_tokenSet_10.member(LA(1))) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true))&&( !(LA(1) == '/' && LA(2) == '$') )) { mDOLLAR_REGEXP_SYMBOL(false); } else if (((LA(1)=='$') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')) && (true) && (true))&&(!atValidDollarEscape() && !atDollarSlashEscape() && !atDollarDollarEscape())) { match('$'); } else { break _loop698; } } } while (true); } { switch ( LA(1)) { case '/': { _saveIndex=text.length(); match("/$"); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { if (fromStart) tt = STRING_LITERAL; // plain regexp literal! } break; } case '$': { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); if ( inputState.guessing==0 ) { // Yes, it's a regexp constructor, and we've got a value part. tt = (fromStart ? STRING_CTOR_START : STRING_CTOR_MIDDLE); stringCtorState = SCS_VAL + SCS_DRE_TYPE; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = tt; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return tt; } protected final void mESCAPED_SLASH(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESCAPED_SLASH; int _saveIndex; match('$'); match('/'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append('/'); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mESCAPED_DOLLAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESCAPED_DOLLAR; int _saveIndex; match('$'); match('$'); if ( inputState.guessing==0 ) { text.setLength(_begin); text.append('$'); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mHEX_DIGIT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = HEX_DIGIT; int _saveIndex; { switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': { matchRange('A','F'); break; } case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': { matchRange('a','f'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mVOCAB(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = VOCAB; int _saveIndex; matchRange('\3','\377'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mIDENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = IDENT; int _saveIndex; { if (((_tokenSet_0.member(LA(1))) && (true) && (true) && (true))&&(stringCtorState == 0)) { { if ((LA(1)=='$')) { mDOLLAR(false); } else if ((_tokenSet_12.member(LA(1)))) { mLETTER(false); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop727: do { switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mDIGIT(false); break; } case '$': { mDOLLAR(false); break; } default: if ((_tokenSet_12.member(LA(1)))) { mLETTER(false); } else { break _loop727; } } } while (true); } } else if ((_tokenSet_12.member(LA(1))) && (true) && (true) && (true)) { mLETTER(false); { _loop729: do { if ((_tokenSet_12.member(LA(1)))) { mLETTER(false); } else if (((LA(1) >= '0' && LA(1) <= '9'))) { mDIGIT(false); } else { break _loop729; } } while (true); } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { if (stringCtorState != 0) { if (LA(1) == '.' && LA(2) != '$' && Character.isJavaIdentifierStart(LA(2))) { // pick up another name component before going literal again: restartStringCtor(false); } else { // go back to the string restartStringCtor(true); } } int ttype = testLiteralsTable(IDENT); // Java doesn't have the keywords 'as', 'in' or 'def so we make some allowances // for them in package names for better integration with existing Java packages if ((ttype == LITERAL_as || ttype == LITERAL_def || ttype == LITERAL_in) && (LA(1) == '.' || lastSigTokenType == DOT || lastSigTokenType == LITERAL_package)) { ttype = IDENT; } if (ttype == LITERAL_static && LA(1) == '.') { ttype = IDENT; } /* The grammar allows a few keywords to follow dot. * TODO: Reinstate this logic if we change or remove keywordPropertyNames. if (ttype != IDENT && lastSigTokenType == DOT) { // A few keywords can follow a dot: switch (ttype) { case LITERAL_this: case LITERAL_super: case LITERAL_class: break; default: ttype = LITERAL_in; // the poster child for bad dotted names } } */ _ttype = ttype; // check if "assert" keyword is enabled if (assertEnabled && "assert".equals(new String(text.getBuffer(),_begin,text.length()-_begin))) { _ttype = LITERAL_assert; // set token type for the rule in the parser } // check if "enum" keyword is enabled if (enumEnabled && "enum".equals(new String(text.getBuffer(),_begin,text.length()-_begin))) { _ttype = LITERAL_enum; // set token type for the rule in the parser } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mLETTER(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LETTER; int _saveIndex; switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '\u00c0': case '\u00c1': case '\u00c2': case '\u00c3': case '\u00c4': case '\u00c5': case '\u00c6': case '\u00c7': case '\u00c8': case '\u00c9': case '\u00ca': case '\u00cb': case '\u00cc': case '\u00cd': case '\u00ce': case '\u00cf': case '\u00d0': case '\u00d1': case '\u00d2': case '\u00d3': case '\u00d4': case '\u00d5': case '\u00d6': { matchRange('\u00C0','\u00D6'); break; } case '\u00d8': case '\u00d9': case '\u00da': case '\u00db': case '\u00dc': case '\u00dd': case '\u00de': case '\u00df': case '\u00e0': case '\u00e1': case '\u00e2': case '\u00e3': case '\u00e4': case '\u00e5': case '\u00e6': case '\u00e7': case '\u00e8': case '\u00e9': case '\u00ea': case '\u00eb': case '\u00ec': case '\u00ed': case '\u00ee': case '\u00ef': case '\u00f0': case '\u00f1': case '\u00f2': case '\u00f3': case '\u00f4': case '\u00f5': case '\u00f6': { matchRange('\u00D8','\u00F6'); break; } case '\u00f8': case '\u00f9': case '\u00fa': case '\u00fb': case '\u00fc': case '\u00fd': case '\u00fe': case '\u00ff': { matchRange('\u00F8','\u00FF'); break; } case '_': { match('_'); break; } default: if (((LA(1) >= '\u0100' && LA(1) <= '\ufffe'))) { matchRange('\u0100','\uFFFE'); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mDIGIT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DIGIT; int _saveIndex; matchRange('0','9'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNUM_INT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NUM_INT; int _saveIndex; Token f2=null; Token g2=null; Token f3=null; Token g3=null; Token f4=null; boolean isDecimal=false; Token t=null; { switch ( LA(1)) { case '0': { match('0'); if ( inputState.guessing==0 ) { isDecimal = true; } { if ((LA(1)=='X'||LA(1)=='x')) { { switch ( LA(1)) { case 'x': { match('x'); break; } case 'X': { match('X'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { isDecimal = false; } { int _cnt737=0; _loop737: do { if ((_tokenSet_13.member(LA(1))) && (true) && (true) && (true)) { mHEX_DIGIT(false); } else { if ( _cnt737>=1 ) { break _loop737; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt737++; } while (true); } } else { boolean synPredMatched743 = false; if ((((LA(1) >= '0' && LA(1) <= '9')) && (true) && (true) && (true))) { int _m743 = mark(); synPredMatched743 = true; inputState.guessing++; try { { { int _cnt740=0; _loop740: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt740>=1 ) { break _loop740; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt740++; } while (true); } { switch ( LA(1)) { case '.': { match('.'); { matchRange('0','9'); } break; } case 'E': case 'e': { mEXPONENT(false); break; } case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(false); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } } catch (RecognitionException pe) { synPredMatched743 = false; } rewind(_m743); inputState.guessing--; } if ( synPredMatched743 ) { { int _cnt745=0; _loop745: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt745>=1 ) { break _loop745; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt745++; } while (true); } } else if (((LA(1) >= '0' && LA(1) <= '7')) && (true) && (true) && (true)) { { int _cnt747=0; _loop747: do { if (((LA(1) >= '0' && LA(1) <= '7'))) { matchRange('0','7'); } else { if ( _cnt747>=1 ) { break _loop747; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt747++; } while (true); } if ( inputState.guessing==0 ) { isDecimal = false; } } else { } } } break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { matchRange('1','9'); } { _loop750: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { break _loop750; } } while (true); } if ( inputState.guessing==0 ) { isDecimal=true; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { switch ( LA(1)) { case 'L': case 'l': { { switch ( LA(1)) { case 'l': { match('l'); break; } case 'L': { match('L'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = NUM_LONG; } break; } case 'I': case 'i': { { switch ( LA(1)) { case 'i': { match('i'); break; } case 'I': { match('I'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { _ttype = NUM_INT; } break; } case 'G': case 'g': { mBIG_SUFFIX(false); if ( inputState.guessing==0 ) { _ttype = NUM_BIG_INT; } break; } default: boolean synPredMatched756 = false; if ((((LA(1)=='.'||LA(1)=='D'||LA(1)=='E'||LA(1)=='F'||LA(1)=='d'||LA(1)=='e'||LA(1)=='f'))&&(isDecimal))) { int _m756 = mark(); synPredMatched756 = true; inputState.guessing++; try { { if ((_tokenSet_14.member(LA(1)))) { matchNot('.'); } else if ((LA(1)=='.')) { match('.'); { matchRange('0','9'); } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } catch (RecognitionException pe) { synPredMatched756 = false; } rewind(_m756); inputState.guessing--; } if ( synPredMatched756 ) { { switch ( LA(1)) { case '.': { match('.'); { int _cnt759=0; _loop759: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt759>=1 ) { break _loop759; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt759++; } while (true); } { if ((LA(1)=='E'||LA(1)=='e')) { mEXPONENT(false); } else { } } { switch ( LA(1)) { case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(true); f2=_returnToken; if ( inputState.guessing==0 ) { t=f2; } break; } case 'G': case 'g': { mBIG_SUFFIX(true); g2=_returnToken; if ( inputState.guessing==0 ) { t=g2; } break; } default: { } } } break; } case 'E': case 'e': { mEXPONENT(false); { switch ( LA(1)) { case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(true); f3=_returnToken; if ( inputState.guessing==0 ) { t=f3; } break; } case 'G': case 'g': { mBIG_SUFFIX(true); g3=_returnToken; if ( inputState.guessing==0 ) { t=g3; } break; } default: { } } } break; } case 'D': case 'F': case 'd': case 'f': { mFLOAT_SUFFIX(true); f4=_returnToken; if ( inputState.guessing==0 ) { t=f4; } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( inputState.guessing==0 ) { String txt = (t == null ? "" : t.getText().toUpperCase()); if (txt.indexOf('F') >= 0) { _ttype = NUM_FLOAT; } else if (txt.indexOf('G') >= 0) { _ttype = NUM_BIG_DECIMAL; } else { _ttype = NUM_DOUBLE; // assume double } } } else { } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mEXPONENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EXPONENT; int _saveIndex; { switch ( LA(1)) { case 'e': { match('e'); break; } case 'E': { match('E'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { switch ( LA(1)) { case '+': { match('+'); break; } case '-': { match('-'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { int _cnt768=0; _loop768: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt768>=1 ) { break _loop768; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt768++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mFLOAT_SUFFIX(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = FLOAT_SUFFIX; int _saveIndex; switch ( LA(1)) { case 'f': { match('f'); break; } case 'F': { match('F'); break; } case 'd': { match('d'); break; } case 'D': { match('D'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mBIG_SUFFIX(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BIG_SUFFIX; int _saveIndex; switch ( LA(1)) { case 'g': { match('g'); break; } case 'G': { match('G'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mAT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = AT; int _saveIndex; match('@'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2560]; data[0]=68719476736L; data[1]=576460745995190270L; data[3]=-36028797027352577L; for (int i = 4; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[2048]; data[0]=-9217L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[2048]; data[0]=-4398046520321L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[2048]; data[0]=-549755813889L; for (int i = 1; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = new long[2048]; data[0]=-635655169025L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = new long[2048]; data[0]=-17179869185L; for (int i = 1; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = new long[2048]; data[0]=-145135534866433L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = new long[2048]; data[0]=-4398046511105L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = new long[2048]; data[0]=-145204254343169L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = new long[2048]; data[0]=-145204254352385L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = new long[2048]; data[0]=-68719476737L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = new long[2048]; data[0]=-140806207841281L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = new long[2560]; data[1]=576460745995190270L; data[3]=-36028797027352577L; for (int i = 4; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); private static final long[] mk_tokenSet_13() { long[] data = new long[1025]; data[0]=287948901175001088L; data[1]=541165879422L; return data; } public static final BitSet _tokenSet_13 = new BitSet(mk_tokenSet_13()); private static final long[] mk_tokenSet_14() { long[] data = new long[2048]; data[0]=-70368744177665L; for (int i = 1; i<=1023; i++) { data[i]=-1L; } return data; } public static final BitSet _tokenSet_14 = new BitSet(mk_tokenSet_14()); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyLexer.smap0000644001501200150120000006134411715044502025605 0ustar miguelmiguelSMAP GroovyLexer.java G *S G *F + 0 groovy.g groovy.g *L 0:396 0:402 0:408 0:414 0:420 0:426 0:432 0:438 0:444 0:450 0:456 0:462 0:468 0:476 0:482 0:488 0:492 0:496 0:500 0:504 0:508 0:512 0:516 0:520 0:524 0:528 0:532 0:536 0:540 0:544 0:548 0:552 0:556 0:560 0:564 0:568 0:572 0:576 0:580 0:584 0:588 0:592 0:596 0:600 0:604 0:608 0:612 0:616 0:620 0:624 0:628 0:632 0:636 0:640 0:644 0:648 0:652 0:656 0:660 0:664 0:668 0:672 0:676 0:680 0:684 0:688 0:692 0:696 0:700 0:704 2:3 2:4 2:5 2:6 2:7 2:8 2:9 2:10 2:11 2:12 3334:41 3335:42 3336:43 3337:44 3338:45 3339:46 3341:48 3342:49 3343:50 3344:51 3345:52 3346:53 3347:54 3348:55 3350:57 3351:58 3352:59 3353:60 3355:62 3356:63 3357:64 3358:65 3360:67 3361:68 3362:69 3363:70 3364:71 3365:72 3366:73 3367:74 3368:75 3370:77 3372:79 3373:80 3374:81 3375:82 3376:83 3377:84 3378:85 3379:86 3381:88 3382:89 3383:90 3384:91 3385:92 3387:94 3388:95 3389:96 3390:97 3391:98 3392:99 3393:100 3395:102 3396:103 3397:104 3398:105 3399:106 3401:108 3402:109 3403:110 3405:112 3406:113 3407:114 3408:115 3409:116 3410:117 3411:118 3412:119 3413:120 3414:121 3415:122 3416:123 3417:124 3418:125 3419:126 3420:127 3421:128 3422:129 3423:130 3424:131 3425:132 3426:133 3427:134 3428:135 3429:136 3430:137 3431:138 3432:139 3433:140 3434:141 3435:142 3436:143 3437:144 3438:145 3439:146 3440:147 3441:148 3442:149 3443:150 3444:151 3445:152 3446:153 3447:154 3448:155 3449:156 3450:157 3451:158 3452:159 3453:160 3454:161 3455:162 3456:163 3457:164 3458:165 3459:166 3460:167 3461:168 3462:169 3463:170 3464:171 3465:172 3466:173 3467:174 3468:175 3469:176 3470:177 3471:178 3472:179 3473:180 3474:181 3475:182 3476:183 3477:184 3478:185 3479:186 3480:187 3481:188 3482:189 3483:190 3484:191 3486:193 3487:194 3488:195 3489:196 3490:197 3491:198 3492:199 3493:200 3494:201 3496:203 3497:204 3498:205 3499:206 3500:207 3501:208 3502:209 3503:210 3504:211 3506:213 3507:214 3508:215 3510:217 3511:218 3512:219 3514:221 3515:222 3516:223 3517:224 3518:225 3519:226 3520:227 3521:228 3522:229 3523:230 3524:231 3525:232 3526:233 3527:234 3528:235 3529:236 3530:237 3531:238 3532:239 3533:240 3534:241 3535:242 3536:243 3537:244 3538:245 3539:246 3540:247 3541:248 3542:249 3543:250 3544:251 3545:252 3546:253 3547:254 3548:255 3549:256 3550:257 3551:258 3552:259 3553:260 3554:261 3555:262 3556:263 3557:264 3558:265 3559:266 3560:267 3561:268 3562:269 3563:270 3564:271 3565:272 3566:273 3568:275 3569:276 3570:277 3571:278 3572:279 3573:280 3574:281 3575:282 3576:283 3577:284 3578:285 3579:286 3580:287 3581:288 3582:289 3583:290 3584:291 3585:292 3586:293 3587:294 3588:295 3589:296 3590:297 3591:298 3592:299 3593:300 3594:301 3595:302 3596:303 3597:304 3599:306 3600:307 3601:308 3602:309 3603:310 3609:732 3609:733 3609:734 3609:735 3609:737 3609:738 3609:739 3609:740 3609:741 3609:742 3609:743 3610:745 3610:746 3610:747 3610:748 3610:750 3610:751 3610:752 3610:754 3610:755 3610:756 3610:757 3610:758 3610:759 3611:761 3611:762 3611:763 3611:764 3611:766 3611:767 3611:768 3611:770 3611:771 3611:772 3611:773 3611:774 3611:775 3612:777 3612:778 3612:779 3612:780 3612:782 3612:783 3612:784 3612:786 3612:787 3612:788 3612:789 3612:790 3612:791 3613:793 3613:794 3613:795 3613:796 3613:798 3613:799 3613:800 3613:802 3613:803 3613:804 3613:805 3613:806 3613:807 3614:809 3614:810 3614:811 3614:812 3614:814 3614:815 3614:816 3614:818 3614:819 3614:820 3614:821 3614:822 3614:823 3615:825 3615:826 3615:827 3615:828 3615:830 3615:831 3615:832 3615:834 3615:835 3615:836 3615:837 3615:838 3615:839 3616:841 3616:842 3616:843 3616:844 3616:846 3616:847 3616:848 3616:849 3616:850 3616:851 3616:852 3617:854 3617:855 3617:856 3617:857 3617:859 3617:860 3617:861 3617:862 3617:863 3617:864 3617:865 3618:867 3618:868 3618:869 3618:870 3618:872 3618:873 3618:874 3618:875 3618:876 3618:877 3618:878 3619:880 3619:881 3619:882 3619:883 3619:885 3619:886 3619:887 3619:888 3619:889 3619:890 3619:891 3620:893 3620:894 3620:895 3620:896 3620:898 3620:899 3620:900 3620:901 3620:902 3620:903 3620:904 3621:906 3621:907 3621:908 3621:909 3621:911 3621:912 3621:913 3621:914 3621:915 3621:916 3621:917 3622:919 3622:920 3622:921 3622:922 3622:924 3622:925 3622:926 3622:927 3622:928 3622:929 3622:930 3623:932 3623:933 3623:934 3623:935 3623:937 3623:938 3623:939 3623:940 3623:941 3623:942 3623:943 3624:945 3624:946 3624:947 3624:948 3624:950 3624:951 3624:952 3624:953 3624:954 3624:955 3624:956 3625:958 3625:959 3625:960 3625:961 3625:963 3625:964 3625:965 3625:966 3625:967 3625:968 3625:969 3626:971 3626:972 3626:973 3626:974 3626:976 3626:977 3626:978 3626:979 3626:980 3626:981 3626:982 3628:984 3628:985 3628:986 3628:987 3628:989 3628:990 3628:991 3628:992 3628:993 3628:994 3628:995 3630:997 3630:998 3630:999 3630:1000 3630:1002 3630:1003 3630:1004 3630:1005 3630:1006 3630:1007 3630:1008 3631:1010 3631:1011 3631:1012 3631:1013 3631:1015 3631:1016 3631:1017 3631:1018 3631:1019 3631:1020 3631:1021 3632:1023 3632:1024 3632:1025 3632:1026 3632:1028 3632:1029 3632:1030 3632:1031 3632:1032 3632:1033 3632:1034 3633:1036 3633:1037 3633:1038 3633:1039 3633:1041 3633:1042 3633:1043 3633:1044 3633:1045 3633:1046 3633:1047 3634:1049 3634:1050 3634:1051 3634:1052 3634:1054 3634:1055 3634:1056 3634:1057 3634:1058 3634:1059 3634:1060 3635:1062 3635:1063 3635:1064 3635:1065 3635:1067 3635:1068 3635:1069 3635:1070 3635:1071 3635:1072 3635:1073 3636:1075 3636:1076 3636:1077 3636:1078 3636:1080 3636:1081 3636:1082 3636:1083 3636:1084 3636:1085 3636:1086 3637:1088 3637:1089 3637:1090 3637:1091 3637:1093 3637:1094 3637:1095 3637:1096 3637:1097 3637:1098 3637:1099 3638:1101 3638:1102 3638:1103 3638:1104 3638:1106 3638:1107 3638:1108 3638:1109 3638:1110 3638:1111 3638:1112 3639:1114 3639:1115 3639:1116 3639:1117 3639:1119 3639:1120 3639:1121 3639:1122 3639:1123 3639:1124 3639:1125 3640:1127 3640:1128 3640:1129 3640:1130 3640:1132 3640:1133 3640:1134 3640:1135 3640:1136 3640:1137 3640:1138 3641:1140 3641:1141 3641:1142 3641:1143 3641:1145 3641:1146 3641:1147 3641:1148 3641:1149 3641:1150 3641:1151 3642:1153 3642:1154 3642:1155 3642:1156 3642:1158 3642:1159 3642:1160 3642:1161 3642:1162 3642:1163 3642:1164 3643:1166 3643:1167 3643:1168 3643:1169 3643:1171 3643:1172 3643:1173 3643:1174 3643:1175 3643:1176 3643:1177 3644:1179 3644:1180 3644:1181 3644:1182 3644:1184 3644:1185 3644:1186 3644:1187 3644:1188 3644:1189 3644:1190 3645:1192 3645:1193 3645:1194 3645:1195 3645:1197 3645:1198 3645:1199 3645:1200 3645:1201 3645:1202 3645:1203 3646:1205 3646:1206 3646:1207 3646:1208 3646:1210 3646:1211 3646:1212 3646:1213 3646:1214 3646:1215 3646:1216 3647:1218 3647:1219 3647:1220 3647:1221 3647:1223 3647:1224 3647:1225 3647:1226 3647:1227 3647:1228 3647:1229 3648:1231 3648:1232 3648:1233 3648:1234 3648:1236 3648:1237 3648:1238 3648:1239 3648:1240 3648:1241 3648:1242 3649:1244 3649:1245 3649:1246 3649:1247 3649:1249 3649:1250 3649:1251 3649:1252 3649:1253 3649:1254 3649:1255 3650:1257 3650:1258 3650:1259 3650:1260 3650:1262 3650:1263 3650:1264 3650:1265 3650:1266 3650:1267 3650:1268 3651:1270 3651:1271 3651:1272 3651:1273 3651:1275 3651:1276 3651:1277 3651:1278 3651:1279 3651:1280 3651:1281 3652:1283 3652:1284 3652:1285 3652:1286 3652:1288 3652:1289 3652:1290 3652:1291 3652:1292 3652:1293 3652:1294 3653:1296 3653:1297 3653:1298 3653:1299 3653:1301 3653:1302 3653:1303 3653:1304 3653:1305 3653:1306 3653:1307 3654:1309 3654:1310 3654:1311 3654:1312 3654:1314 3654:1315 3654:1316 3654:1317 3654:1318 3654:1319 3654:1320 3655:1322 3655:1323 3655:1324 3655:1325 3655:1327 3655:1328 3655:1329 3655:1330 3655:1331 3655:1332 3655:1333 3656:1335 3656:1336 3656:1337 3656:1338 3656:1340 3656:1341 3656:1342 3656:1343 3656:1344 3656:1345 3656:1346 3657:1348 3657:1349 3657:1350 3657:1351 3657:1353 3657:1354 3657:1355 3657:1356 3657:1357 3657:1358 3657:1359 3658:1361 3658:1362 3658:1363 3658:1364 3658:1366 3658:1367 3658:1368 3658:1369 3658:1370 3658:1371 3658:1372 3659:1374 3659:1375 3659:1376 3659:1377 3659:1379 3659:1380 3659:1381 3659:1382 3659:1383 3659:1384 3659:1385 3661:1387 3661:1388 3661:1389 3661:1390 3661:1392 3661:1393 3661:1394 3661:1395 3661:1396 3661:1397 3661:1398 3662:1400 3662:1401 3662:1402 3662:1403 3662:1405 3662:1406 3662:1407 3662:1408 3662:1409 3662:1410 3662:1411 3663:1413 3663:1414 3663:1415 3663:1416 3663:1418 3663:1419 3663:1420 3663:1421 3663:1422 3663:1423 3663:1424 3664:1426 3664:1427 3664:1428 3664:1429 3664:1431 3664:1432 3664:1433 3664:1434 3664:1435 3664:1436 3664:1437 3665:1439 3665:1440 3665:1441 3665:1442 3665:1444 3665:1445 3665:1446 3665:1447 3665:1448 3665:1449 3665:1450 3666:1452 3666:1453 3666:1454 3666:1455 3666:1457 3666:1458 3666:1459 3666:1460 3666:1461 3666:1462 3666:1463 3667:1465 3667:1466 3667:1467 3667:1468 3667:1470 3667:1471 3667:1472 3667:1473 3667:1474 3667:1475 3667:1476 3668:1478 3668:1479 3668:1480 3668:1481 3668:1483 3668:1484 3668:1485 3668:1486 3668:1487 3668:1488 3668:1489 3669:1491 3669:1492 3669:1493 3669:1494 3669:1496 3669:1497 3669:1498 3669:1499 3669:1500 3669:1501 3669:1502 3670:1504 3670:1505 3670:1506 3670:1507 3670:1509 3670:1510 3670:1511 3670:1512 3670:1513 3670:1514 3670:1515 3671:1517 3671:1518 3671:1519 3671:1520 3671:1522 3671:1523 3671:1524 3671:1525 3671:1526 3671:1527 3671:1528 3672:1530 3672:1531 3672:1532 3672:1533 3672:1535 3672:1536 3672:1537 3672:1538 3672:1539 3672:1540 3672:1541 3673:1543 3673:1544 3673:1545 3673:1546 3673:1548 3673:1549 3673:1550 3673:1551 3673:1552 3673:1553 3673:1554 3676:1556 3676:1557 3676:1558 3676:1559 3676:1588 3676:1589 3676:1590 3676:1591 3676:1592 3676:1593 3681:1562 3681:1563 3681:1564 3681:1568 3681:1571 3681:1574 3681:1577 3681:1578 3681:1579 3681:1580 3681:1582 3681:1583 3681:1584 3683:1569 3683:1570 3684:1572 3684:1573 3685:1575 3685:1576 3686:1565 3686:1566 3686:1567 3688:1585 3688:1586 3692:1595 3692:1596 3692:1597 3692:1598 3692:1599 3692:1600 3692:1629 3692:1630 3692:1631 3692:1632 3692:1633 3692:1634 3697:1607 3697:1612 3697:1617 3697:1618 3697:1619 3697:1620 3698:1603 3698:1604 3698:1605 3698:1606 3699:1608 3699:1609 3699:1610 3699:1611 3700:1613 3700:1614 3700:1615 3700:1616 3702:1623 3703:1625 3704:1626 3711:1636 3711:1637 3711:1638 3711:1639 3711:1690 3711:1691 3711:1692 3711:1693 3711:1694 3711:1695 3715:1641 3716:1673 3716:1675 3717:1643 3717:1645 3717:1646 3717:1647 3717:1648 3717:1649 3717:1650 3717:1651 3717:1654 3717:1655 3717:1656 3717:1659 3717:1660 3717:1661 3717:1662 3717:1663 3717:1664 3717:1665 3717:1666 3717:1667 3717:1668 3717:1669 3717:1670 3717:1671 3717:1672 3721:1678 3721:1679 3722:1680 3723:1681 3724:1682 3725:1683 3726:1684 3727:1685 3728:1686 3729:1687 3734:1697 3734:1698 3734:1699 3734:1700 3734:1720 3734:1721 3734:1722 3734:1723 3734:1724 3734:1725 3738:1702 3739:1703 3739:1704 3739:1705 3739:1710 3739:1711 3739:1712 3739:1713 3739:1715 3739:1716 3743:1706 3743:1708 3745:1717 3745:1718 3751:1781 3751:1782 3751:1783 3751:1784 3751:1786 3751:1787 3751:1806 3751:1807 3751:1808 3751:1809 3751:1810 3751:1811 3755:1788 3756:1789 3756:1790 3756:1791 3756:1796 3756:1797 3756:1798 3756:1799 3756:1801 3756:1802 3760:1792 3760:1794 3762:1803 3762:1804 3767:1727 3767:1728 3767:1729 3767:1730 3767:1774 3767:1775 3767:1776 3767:1777 3767:1778 3767:1779 3771:1732 3772:1733 3772:1734 3772:1735 3772:1755 3772:1758 3772:1763 3772:1764 3772:1765 3772:1766 3772:1768 3772:1769 3783:1736 3783:1737 3783:1738 3783:1739 3783:1740 3783:1741 3783:1743 3783:1744 3783:1746 3783:1747 3783:1748 3783:1749 3783:1750 3783:1751 3783:1752 3783:1753 3783:1754 3784:1756 3784:1757 3785:1759 3785:1761 3787:1770 3788:1771 3788:1772 3793:1813 3793:1814 3793:1815 3793:1816 3793:1817 3793:1908 3793:1934 3793:1977 3793:1989 3793:1990 3793:1991 3793:1992 3793:1993 3793:1994 3793:1995 3793:1996 3793:1997 3793:1998 3793:1999 3798:1819 3798:1820 3798:1821 3798:1822 3798:1823 3798:1824 3798:1826 3798:1828 3798:1829 3798:1830 3798:1831 3798:1832 3798:1833 3798:1834 3798:1835 3799:1836 3799:1837 3799:1838 3800:1839 3800:1840 3800:1841 3800:1842 3800:1843 3800:1844 3800:1845 3800:1848 3800:1849 3800:1850 3800:1853 3800:1854 3800:1855 3800:1858 3800:1859 3800:1860 3800:1863 3800:1895 3800:1896 3800:1897 3800:1898 3800:1899 3800:1900 3800:1901 3800:1902 3800:1903 3800:1904 3801:1864 3801:1865 3801:1866 3801:1867 3801:1868 3801:1869 3801:1871 3801:1873 3801:1874 3801:1875 3801:1876 3801:1877 3801:1878 3801:1879 3801:1880 3801:1881 3801:1882 3801:1886 3801:1887 3801:1888 3801:1889 3801:1890 3801:1891 3801:1892 3801:1893 3801:1894 3803:1905 3803:1906 3803:1907 3804:1935 3804:1936 3804:1937 3804:1938 3805:1939 3805:1940 3806:1942 3806:1943 3806:1944 3806:1945 3806:1946 3806:1947 3806:1948 3806:1951 3806:1952 3806:1953 3806:1956 3806:1957 3806:1958 3806:1961 3806:1962 3806:1963 3806:1964 3806:1965 3806:1966 3806:1967 3806:1968 3806:1969 3806:1970 3807:1971 3807:1972 3808:1974 3808:1975 3808:1976 3809:1909 3809:1910 3809:1911 3809:1912 3809:1913 3809:1914 3809:1915 3809:1917 3809:1919 3809:1920 3809:1921 3809:1922 3809:1923 3809:1924 3809:1925 3809:1926 3810:1927 3810:1928 3810:1929 3811:1930 3812:1931 3812:1932 3813:1978 3813:1979 3813:1980 3813:1981 3814:1982 3814:1983 3815:1985 3816:1986 3816:1987 3820:2211 3820:2212 3820:2213 3820:2214 3820:2215 3820:2216 3820:2217 3820:2218 3820:2340 3820:2341 3820:2342 3820:2343 3820:2344 3820:2345 3820:2346 3827:2220 3827:2221 3827:2222 3827:2223 3827:2239 3827:2271 3827:2274 3827:2275 3827:2276 3827:2277 3827:2278 3827:2279 3827:2280 3829:2224 3829:2225 3829:2226 3829:2229 3829:2230 3829:2231 3829:2234 3829:2235 3829:2236 3829:2272 3829:2273 3830:2240 3830:2241 3830:2242 3830:2243 3830:2244 3830:2245 3830:2247 3830:2249 3830:2250 3830:2251 3830:2252 3830:2253 3830:2254 3830:2255 3830:2256 3830:2257 3830:2258 3830:2262 3830:2263 3830:2264 3830:2265 3830:2266 3830:2267 3830:2268 3830:2269 3830:2270 3832:2282 3832:2283 3832:2284 3832:2290 3832:2291 3832:2292 3832:2293 3832:2294 3832:2295 3832:2296 3832:2297 3832:2298 3832:2331 3832:2332 3832:2333 3832:2334 3832:2335 3833:2286 3833:2287 3833:2288 3833:2289 3835:2301 3836:2303 3837:2304 3838:2305 3839:2306 3841:2311 3841:2312 3841:2313 3841:2314 3842:2316 3842:2317 3842:2318 3843:2319 3844:2321 3845:2322 3846:2323 3847:2324 3848:2325 3849:2326 3852:2337 3852:2338 3856:2001 3856:2002 3856:2003 3856:2004 3856:2009 3856:2010 3856:2011 3856:2012 3856:2013 3856:2014 3860:2007 3863:2348 3863:2349 3863:2350 3863:2351 3863:2352 3863:2390 3863:2396 3863:2402 3863:2403 3863:2404 3863:2405 3863:2407 3863:2408 3863:2409 3863:2410 3863:2411 3863:2412 3869:2354 3869:2355 3869:2356 3869:2357 3870:2358 3870:2359 3874:2365 3874:2369 3874:2381 3874:2382 3874:2383 3874:2384 3875:2366 3875:2367 3876:2368 3877:2362 3877:2363 3878:2364 3879:2370 3879:2371 3879:2372 3879:2373 3880:2374 3881:2376 3882:2377 3883:2378 3886:2387 3886:2388 3888:2397 3888:2398 3888:2399 3888:2400 3889:2391 3889:2392 3889:2393 3889:2394 3892:2541 3892:2542 3892:2543 3892:2544 3892:2545 3892:2547 3892:2548 3892:2581 3892:2582 3892:2583 3892:2584 3892:2585 3892:2586 3897:2549 3897:2550 3897:2551 3900:2556 3900:2560 3900:2572 3900:2573 3900:2574 3900:2575 3901:2557 3901:2558 3902:2559 3903:2553 3903:2554 3904:2555 3905:2561 3905:2562 3905:2563 3905:2564 3906:2565 3907:2567 3908:2568 3909:2569 3912:2578 3912:2579 3916:2470 3916:2471 3916:2472 3916:2473 3916:2474 3916:2475 3916:2476 3916:2533 3916:2534 3916:2535 3916:2536 3916:2537 3916:2538 3916:2539 3922:2478 3922:2479 3922:2480 3922:2483 3922:2486 3922:2487 3922:2488 3922:2489 3922:2491 3922:2492 3924:2484 3924:2485 3926:2481 3926:2482 3928:2494 3928:2495 3928:2496 3928:2497 3928:2498 3928:2499 3928:2524 3928:2525 3928:2526 3928:2527 3928:2528 3929:2500 3930:2502 3931:2503 3932:2504 3933:2505 3935:2510 3935:2511 3935:2512 3935:2513 3935:2514 3936:2515 3937:2517 3938:2518 3939:2519 3942:2530 3942:2531 3946:2634 3946:2635 3946:2636 3946:2637 3946:2638 3946:2639 3946:2640 3946:2735 3946:2736 3946:2737 3946:2738 3946:2739 3946:2740 3946:2741 3952:2642 3952:2643 3952:2644 3952:2664 3952:2685 3952:2688 3952:2691 3952:2692 3952:2693 3952:2694 3952:2695 3952:2696 3952:2697 3954:2686 3954:2687 3956:2645 3956:2646 3956:2647 3956:2648 3956:2649 3956:2650 3956:2652 3956:2653 3956:2655 3956:2656 3956:2657 3956:2658 3956:2659 3956:2660 3956:2661 3956:2662 3956:2663 3958:2665 3958:2666 3958:2667 3958:2668 3958:2669 3958:2670 3958:2671 3958:2673 3958:2674 3958:2676 3958:2677 3958:2678 3958:2679 3958:2680 3958:2681 3958:2682 3958:2683 3958:2684 3960:2689 3960:2690 3962:2699 3962:2726 3962:2727 3962:2728 3962:2729 3962:2730 3963:2700 3963:2701 3963:2702 3963:2703 3963:2704 3964:2705 3965:2707 3967:2712 3967:2713 3967:2714 3967:2715 3967:2716 3968:2717 3969:2719 3970:2720 3971:2721 3974:2732 3974:2733 3977:2743 3977:2744 3977:2745 3977:2746 3977:2748 3977:2749 3977:2750 3977:2751 3977:2753 3977:2754 3977:2755 3977:2756 3977:2757 3977:2758 3979:2760 3979:2761 3979:2762 3979:2763 3979:2765 3979:2766 3979:2767 3979:2768 3979:2770 3979:2771 3979:2772 3979:2773 3979:2774 3979:2775 3982:2414 3982:2415 3982:2416 3982:2417 3982:2463 3982:2464 3982:2465 3982:2466 3982:2467 3982:2468 3987:2426 3987:2434 3987:2437 3987:2442 3987:2445 3987:2446 3987:2447 3987:2448 3988:2438 3988:2440 3989:2435 3989:2436 3990:2420 3990:2421 3990:2422 3990:2423 3990:2424 3991:2443 3991:2444 3992:2427 3992:2428 3992:2429 3992:2430 3992:2431 3992:2432 3992:2433 3994:2451 3994:2452 3994:2453 3994:2454 3994:2455 3994:2456 3994:2457 3994:2458 3994:2459 3994:2461 3994:2462 3998:2588 3998:2589 3998:2590 3998:2591 3998:2627 3998:2628 3998:2629 3998:2630 3998:2631 3998:2632 4003:2594 4003:2605 4003:2613 4003:2616 4003:2621 4003:2622 4003:2623 4003:2624 4003:2625 4004:2617 4004:2619 4005:2614 4005:2615 4006:2595 4006:2596 4006:2597 4007:2600 4007:2601 4007:2602 4008:2606 4008:2607 4008:2608 4008:2609 4008:2610 4008:2611 4008:2612 4021:2016 4021:2017 4021:2018 4021:2019 4021:2170 4021:2178 4021:2179 4021:2180 4021:2181 4021:2183 4021:2184 4021:2185 4021:2186 4021:2187 4021:2188 4025:2021 4025:2022 4025:2023 4025:2024 4026:2026 4026:2027 4026:2028 4026:2029 4026:2030 4026:2031 4026:2164 4026:2165 4026:2166 4026:2167 4026:2168 4027:2035 4027:2036 4027:2037 4027:2038 4027:2039 4028:2043 4028:2044 4028:2045 4028:2046 4028:2047 4029:2051 4029:2052 4029:2053 4029:2054 4029:2055 4030:2059 4030:2060 4030:2061 4030:2062 4030:2063 4031:2067 4031:2068 4031:2069 4032:2072 4032:2073 4032:2074 4033:2077 4033:2078 4033:2079 4034:2082 4034:2083 4034:2084 4035:2087 4035:2088 4035:2090 4035:2091 4035:2092 4035:2093 4035:2094 4035:2095 4035:2096 4035:2097 4035:2098 4035:2100 4035:2101 4035:2102 4035:2103 4035:2104 4036:2106 4036:2107 4036:2108 4036:2109 4037:2110 4037:2111 4038:2115 4038:2116 4038:2117 4039:2132 4039:2134 4039:2135 4039:2136 4039:2137 4043:2119 4043:2120 4044:2124 4044:2126 4044:2127 4044:2128 4044:2129 4048:2122 4048:2123 4051:2140 4051:2141 4052:2145 4052:2146 4052:2147 4053:2151 4053:2153 4053:2154 4053:2155 4053:2156 4057:2149 4057:2150 4059:2159 4059:2160 4061:2171 4061:2172 4061:2173 4061:2174 4061:2175 4061:2176 4061:2177 4065:2190 4065:2191 4065:2192 4065:2193 4065:2194 4065:2195 4065:2204 4065:2205 4065:2206 4065:2207 4065:2208 4065:2209 4069:2197 4069:2198 4070:2200 4070:2201 4070:2202 4076:2777 4076:2778 4076:2779 4076:2780 4076:2809 4076:2810 4076:2811 4076:2812 4076:2813 4076:2814 4080:2783 4080:2784 4080:2785 4080:2786 4080:2787 4080:2788 4080:2791 4080:2792 4080:2793 4080:2794 4080:2797 4080:2798 4080:2799 4080:2800 4080:2803 4080:2804 4080:2805 4080:2806 4080:2807 4087:2816 4087:2817 4087:2818 4087:2819 4087:2822 4087:2823 4087:2824 4087:2825 4087:2826 4087:2827 4091:2821 4098:2829 4098:2830 4098:2831 4098:2832 4098:2945 4098:2946 4098:2947 4098:2948 4098:2949 4098:2950 4103:2835 4103:2837 4103:2838 4103:2839 4103:2840 4103:2841 4103:2842 4103:2843 4103:2844 4103:2845 4103:2848 4103:2849 4103:2850 4103:2851 4103:2852 4103:2853 4103:2854 4103:2855 4103:2856 4103:2859 4103:2860 4103:2861 4103:2864 4103:2865 4103:2866 4103:2867 4103:2868 4103:2869 4103:2870 4103:2871 4103:2872 4103:2873 4103:2874 4103:2875 4103:2876 4103:2877 4103:2878 4103:2879 4103:2880 4103:2881 4103:2882 4103:2883 4103:2884 4103:2885 4103:2886 4103:2887 4103:2888 4103:2890 4103:2891 4103:2892 4103:2893 4103:2894 4103:2895 4104:2898 4105:2900 4106:2901 4107:2902 4108:2903 4109:2904 4110:2905 4111:2906 4112:2907 4113:2908 4114:2909 4115:2910 4116:2911 4117:2912 4118:2913 4119:2914 4120:2915 4121:2916 4122:2917 4123:2918 4124:2919 4126:2921 4127:2922 4128:2923 4129:2924 4130:2925 4131:2926 4132:2927 4133:2928 4134:2929 4135:2930 4136:2931 4137:2932 4138:2933 4140:2935 4141:2936 4142:2937 4143:2938 4144:2939 4145:2940 4146:2941 4147:2942 4152:2952 4152:2953 4152:2954 4152:2955 4152:2957 4152:3013 4152:3016 4152:3017 4152:3018 4152:3019 4152:3020 4152:3021 4152:3022 4152:3023 4152:3024 4152:3025 4152:3026 4156:2958 4156:2959 4156:2960 4156:2961 4156:2962 4156:2963 4156:2964 4156:2965 4156:2966 4156:2969 4156:2970 4156:2971 4156:2972 4156:2973 4156:2974 4156:2975 4156:2976 4156:2977 4156:2980 4156:2981 4156:2982 4156:2983 4156:2984 4156:2985 4156:2986 4156:2987 4156:2990 4156:2991 4156:2992 4156:2993 4156:2994 4156:2995 4156:2996 4156:2997 4156:2998 4156:2999 4156:3002 4156:3003 4156:3004 4156:3005 4156:3008 4156:3009 4156:3010 4156:3014 4156:3015 4161:3028 4161:3029 4161:3030 4161:3031 4161:3034 4161:3035 4161:3036 4161:3037 4161:3038 4161:3039 4165:3033 4170:3041 4170:3042 4170:3043 4170:3044 4170:3050 4170:3431 4170:3432 4170:3433 4170:3434 4170:3435 4170:3436 4195:3053 4195:3054 4195:3055 4195:3056 4195:3057 4195:3058 4195:3219 4195:3220 4195:3221 4195:3222 4195:3223 4196:3061 4196:3063 4196:3064 4196:3065 4196:3066 4196:3069 4196:3070 4196:3071 4196:3074 4196:3075 4196:3076 4196:3077 4196:3078 4196:3097 4196:3169 4196:3188 4196:3190 4196:3191 4197:3080 4197:3081 4198:3084 4198:3085 4198:3086 4198:3089 4198:3090 4198:3091 4198:3092 4198:3094 4198:3095 4198:3096 4207:3087 4207:3088 4211:3098 4211:3099 4211:3100 4211:3101 4211:3102 4211:3103 4211:3104 4211:3107 4211:3108 4211:3109 4211:3110 4211:3111 4211:3112 4211:3113 4211:3114 4211:3115 4211:3117 4211:3118 4211:3119 4211:3121 4211:3122 4211:3123 4211:3124 4211:3126 4211:3130 4211:3131 4211:3132 4211:3135 4211:3136 4211:3137 4211:3140 4211:3141 4211:3142 4211:3143 4211:3144 4211:3147 4211:3148 4211:3149 4211:3150 4211:3151 4211:3152 4211:3153 4211:3154 4211:3156 4211:3157 4211:3158 4211:3159 4211:3160 4211:3161 4211:3162 4211:3163 4211:3164 4211:3166 4211:3167 4211:3168 4213:3170 4213:3172 4213:3173 4213:3174 4213:3175 4213:3176 4213:3177 4213:3178 4213:3179 4213:3180 4213:3182 4213:3183 4213:3184 4214:3185 4214:3186 4216:3195 4216:3196 4216:3197 4216:3198 4216:3200 4216:3202 4216:3203 4216:3204 4216:3205 4216:3206 4216:3207 4216:3208 4216:3209 4216:3210 4216:3212 4216:3213 4216:3214 4216:3215 4218:3226 4218:3227 4218:3228 4218:3230 4218:3231 4218:3232 4218:3233 4218:3236 4218:3237 4218:3238 4218:3241 4218:3242 4218:3243 4218:3244 4218:3245 4218:3247 4218:3248 4218:3285 4218:3426 4218:3428 4218:3429 4219:3252 4219:3253 4219:3255 4219:3256 4219:3257 4219:3258 4219:3261 4219:3262 4219:3263 4219:3266 4219:3267 4219:3268 4219:3269 4219:3270 4219:3272 4219:3273 4220:3277 4220:3278 4220:3279 4220:3280 4220:3281 4224:3286 4224:3287 4224:3288 4224:3289 4224:3290 4224:3291 4224:3293 4224:3294 4224:3295 4224:3296 4224:3297 4224:3299 4224:3301 4224:3302 4224:3303 4224:3304 4224:3307 4224:3308 4224:3309 4224:3310 4224:3311 4224:3312 4224:3313 4224:3314 4226:3045 4226:3046 4226:3316 4226:3317 4226:3318 4226:3319 4226:3321 4226:3322 4226:3323 4226:3324 4226:3325 4226:3326 4226:3327 4226:3328 4226:3329 4226:3331 4226:3332 4226:3333 4226:3335 4226:3336 4226:3337 4226:3339 4226:3343 4226:3344 4226:3345 4226:3346 4226:3347 4226:3348 4226:3349 4226:3353 4226:3354 4226:3355 4226:3356 4226:3357 4226:3358 4226:3362 4226:3364 4226:3365 4226:3408 4226:3409 4226:3410 4226:3411 4226:3412 4227:3047 4227:3048 4227:3369 4227:3370 4227:3371 4227:3373 4227:3374 4227:3375 4227:3376 4227:3377 4227:3378 4227:3379 4227:3383 4227:3384 4227:3385 4227:3386 4227:3387 4227:3388 4227:3392 4227:3394 4227:3395 4228:3049 4228:3399 4228:3400 4228:3401 4228:3402 4228:3403 4228:3404 4230:3414 4231:3416 4232:3417 4233:3418 4234:3419 4235:3420 4236:3421 4237:3422 4238:3423 4245:3572 4245:3573 4245:3574 4245:3575 4245:3578 4245:3579 4245:3580 4245:3581 4245:3582 4245:3583 4249:3577 4254:3438 4254:3439 4254:3440 4254:3441 4254:3499 4254:3500 4254:3501 4254:3502 4254:3503 4254:3504 4258:3444 4258:3445 4258:3446 4258:3447 4258:3450 4258:3451 4258:3452 4258:3455 4258:3456 4258:3457 4258:3458 4258:3459 4258:3462 4258:3463 4258:3464 4258:3465 4258:3468 4258:3469 4258:3470 4258:3479 4258:3480 4258:3481 4258:3482 4258:3483 4258:3486 4258:3487 4258:3488 4258:3489 4258:3490 4258:3491 4258:3492 4258:3493 4258:3494 4258:3496 4258:3497 4258:3498 4263:3506 4263:3507 4263:3508 4263:3509 4263:3511 4263:3532 4263:3533 4263:3534 4263:3535 4263:3536 4263:3537 4263:3538 4263:3539 4263:3540 4263:3541 4263:3542 4267:3512 4267:3513 4267:3514 4267:3517 4267:3518 4267:3519 4267:3522 4267:3523 4267:3524 4267:3527 4267:3528 4267:3529 4271:3544 4271:3545 4271:3546 4271:3547 4271:3549 4271:3560 4271:3561 4271:3562 4271:3563 4271:3564 4271:3565 4271:3566 4271:3567 4271:3568 4271:3569 4271:3570 4275:3550 4275:3551 4275:3552 4275:3555 4275:3556 4275:3557 *E groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyTokenTypes.java0000644001501200150120000001300511715044502026603 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "groovy.g" -> "GroovyRecognizer.java"$ package org.codehaus.groovy.antlr.parser; import org.codehaus.groovy.antlr.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import antlr.CommonToken; import org.codehaus.groovy.GroovyBugError; import antlr.TokenStreamRecognitionException; public interface GroovyTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int BLOCK = 4; int MODIFIERS = 5; int OBJBLOCK = 6; int SLIST = 7; int METHOD_DEF = 8; int VARIABLE_DEF = 9; int INSTANCE_INIT = 10; int STATIC_INIT = 11; int TYPE = 12; int CLASS_DEF = 13; int INTERFACE_DEF = 14; int PACKAGE_DEF = 15; int ARRAY_DECLARATOR = 16; int EXTENDS_CLAUSE = 17; int IMPLEMENTS_CLAUSE = 18; int PARAMETERS = 19; int PARAMETER_DEF = 20; int LABELED_STAT = 21; int TYPECAST = 22; int INDEX_OP = 23; int POST_INC = 24; int POST_DEC = 25; int METHOD_CALL = 26; int EXPR = 27; int IMPORT = 28; int UNARY_MINUS = 29; int UNARY_PLUS = 30; int CASE_GROUP = 31; int ELIST = 32; int FOR_INIT = 33; int FOR_CONDITION = 34; int FOR_ITERATOR = 35; int EMPTY_STAT = 36; int FINAL = 37; int ABSTRACT = 38; int UNUSED_GOTO = 39; int UNUSED_CONST = 40; int UNUSED_DO = 41; int STRICTFP = 42; int SUPER_CTOR_CALL = 43; int CTOR_CALL = 44; int CTOR_IDENT = 45; int VARIABLE_PARAMETER_DEF = 46; int STRING_CONSTRUCTOR = 47; int STRING_CTOR_MIDDLE = 48; int CLOSABLE_BLOCK = 49; int IMPLICIT_PARAMETERS = 50; int SELECT_SLOT = 51; int DYNAMIC_MEMBER = 52; int LABELED_ARG = 53; int SPREAD_ARG = 54; int SPREAD_MAP_ARG = 55; int LIST_CONSTRUCTOR = 56; int MAP_CONSTRUCTOR = 57; int FOR_IN_ITERABLE = 58; int STATIC_IMPORT = 59; int ENUM_DEF = 60; int ENUM_CONSTANT_DEF = 61; int FOR_EACH_CLAUSE = 62; int ANNOTATION_DEF = 63; int ANNOTATIONS = 64; int ANNOTATION = 65; int ANNOTATION_MEMBER_VALUE_PAIR = 66; int ANNOTATION_FIELD_DEF = 67; int ANNOTATION_ARRAY_INIT = 68; int TYPE_ARGUMENTS = 69; int TYPE_ARGUMENT = 70; int TYPE_PARAMETERS = 71; int TYPE_PARAMETER = 72; int WILDCARD_TYPE = 73; int TYPE_UPPER_BOUNDS = 74; int TYPE_LOWER_BOUNDS = 75; int CLOSURE_LIST = 76; int SH_COMMENT = 77; int LITERAL_package = 78; int LITERAL_import = 79; int LITERAL_static = 80; int LITERAL_def = 81; int LBRACK = 82; int RBRACK = 83; int IDENT = 84; int STRING_LITERAL = 85; int LT = 86; int DOT = 87; int LPAREN = 88; int LITERAL_class = 89; int LITERAL_interface = 90; int LITERAL_enum = 91; int AT = 92; int QUESTION = 93; int LITERAL_extends = 94; int LITERAL_super = 95; int GT = 96; int COMMA = 97; int SR = 98; int BSR = 99; int LITERAL_void = 100; int LITERAL_boolean = 101; int LITERAL_byte = 102; int LITERAL_char = 103; int LITERAL_short = 104; int LITERAL_int = 105; int LITERAL_float = 106; int LITERAL_long = 107; int LITERAL_double = 108; int STAR = 109; int LITERAL_as = 110; int LITERAL_private = 111; int LITERAL_public = 112; int LITERAL_protected = 113; int LITERAL_transient = 114; int LITERAL_native = 115; int LITERAL_threadsafe = 116; int LITERAL_synchronized = 117; int LITERAL_volatile = 118; int RPAREN = 119; int ASSIGN = 120; int BAND = 121; int LCURLY = 122; int RCURLY = 123; int SEMI = 124; int LITERAL_default = 125; int LITERAL_throws = 126; int LITERAL_implements = 127; int LITERAL_this = 128; int TRIPLE_DOT = 129; int CLOSABLE_BLOCK_OP = 130; int COLON = 131; int LITERAL_if = 132; int LITERAL_else = 133; int LITERAL_while = 134; int LITERAL_switch = 135; int LITERAL_for = 136; int LITERAL_in = 137; int LITERAL_return = 138; int LITERAL_break = 139; int LITERAL_continue = 140; int LITERAL_throw = 141; int LITERAL_assert = 142; int PLUS = 143; int MINUS = 144; int LITERAL_case = 145; int LITERAL_try = 146; int LITERAL_finally = 147; int LITERAL_catch = 148; int SPREAD_DOT = 149; int OPTIONAL_DOT = 150; int MEMBER_POINTER = 151; int LITERAL_false = 152; int LITERAL_instanceof = 153; int LITERAL_new = 154; int LITERAL_null = 155; int LITERAL_true = 156; int PLUS_ASSIGN = 157; int MINUS_ASSIGN = 158; int STAR_ASSIGN = 159; int DIV_ASSIGN = 160; int MOD_ASSIGN = 161; int SR_ASSIGN = 162; int BSR_ASSIGN = 163; int SL_ASSIGN = 164; int BAND_ASSIGN = 165; int BXOR_ASSIGN = 166; int BOR_ASSIGN = 167; int STAR_STAR_ASSIGN = 168; int ELVIS_OPERATOR = 169; int LOR = 170; int LAND = 171; int BOR = 172; int BXOR = 173; int REGEX_FIND = 174; int REGEX_MATCH = 175; int NOT_EQUAL = 176; int EQUAL = 177; int IDENTICAL = 178; int NOT_IDENTICAL = 179; int COMPARE_TO = 180; int LE = 181; int GE = 182; int SL = 183; int RANGE_INCLUSIVE = 184; int RANGE_EXCLUSIVE = 185; int INC = 186; int DIV = 187; int MOD = 188; int DEC = 189; int STAR_STAR = 190; int BNOT = 191; int LNOT = 192; int STRING_CTOR_START = 193; int STRING_CTOR_END = 194; int NUM_INT = 195; int NUM_FLOAT = 196; int NUM_LONG = 197; int NUM_DOUBLE = 198; int NUM_BIG_INT = 199; int NUM_BIG_DECIMAL = 200; int NLS = 201; int DOLLAR = 202; int WS = 203; int ONE_NL = 204; int SL_COMMENT = 205; int ML_COMMENT = 206; int STRING_CH = 207; int REGEXP_LITERAL = 208; int DOLLAR_REGEXP_LITERAL = 209; int REGEXP_CTOR_END = 210; int DOLLAR_REGEXP_CTOR_END = 211; int ESCAPED_SLASH = 212; int ESCAPED_DOLLAR = 213; int REGEXP_SYMBOL = 214; int DOLLAR_REGEXP_SYMBOL = 215; int ESC = 216; int STRING_NL = 217; int HEX_DIGIT = 218; int VOCAB = 219; int LETTER = 220; int DIGIT = 221; int EXPONENT = 222; int FLOAT_SUFFIX = 223; int BIG_SUFFIX = 224; } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyTokenTypes.txt0000644001501200150120000001210711715044502026503 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): groovy.g -> GroovyTokenTypes.txt$ Groovy // output token vocab name BLOCK=4 MODIFIERS=5 OBJBLOCK=6 SLIST=7 METHOD_DEF=8 VARIABLE_DEF=9 INSTANCE_INIT=10 STATIC_INIT=11 TYPE=12 CLASS_DEF=13 INTERFACE_DEF=14 PACKAGE_DEF=15 ARRAY_DECLARATOR=16 EXTENDS_CLAUSE=17 IMPLEMENTS_CLAUSE=18 PARAMETERS=19 PARAMETER_DEF=20 LABELED_STAT=21 TYPECAST=22 INDEX_OP=23 POST_INC=24 POST_DEC=25 METHOD_CALL=26 EXPR=27 IMPORT=28 UNARY_MINUS=29 UNARY_PLUS=30 CASE_GROUP=31 ELIST=32 FOR_INIT=33 FOR_CONDITION=34 FOR_ITERATOR=35 EMPTY_STAT=36 FINAL="final"=37 ABSTRACT="abstract"=38 UNUSED_GOTO="goto"=39 UNUSED_CONST="const"=40 UNUSED_DO="do"=41 STRICTFP="strictfp"=42 SUPER_CTOR_CALL=43 CTOR_CALL=44 CTOR_IDENT=45 VARIABLE_PARAMETER_DEF=46 STRING_CONSTRUCTOR=47 STRING_CTOR_MIDDLE=48 CLOSABLE_BLOCK=49 IMPLICIT_PARAMETERS=50 SELECT_SLOT=51 DYNAMIC_MEMBER=52 LABELED_ARG=53 SPREAD_ARG=54 SPREAD_MAP_ARG=55 LIST_CONSTRUCTOR=56 MAP_CONSTRUCTOR=57 FOR_IN_ITERABLE=58 STATIC_IMPORT=59 ENUM_DEF=60 ENUM_CONSTANT_DEF=61 FOR_EACH_CLAUSE=62 ANNOTATION_DEF=63 ANNOTATIONS=64 ANNOTATION=65 ANNOTATION_MEMBER_VALUE_PAIR=66 ANNOTATION_FIELD_DEF=67 ANNOTATION_ARRAY_INIT=68 TYPE_ARGUMENTS=69 TYPE_ARGUMENT=70 TYPE_PARAMETERS=71 TYPE_PARAMETER=72 WILDCARD_TYPE=73 TYPE_UPPER_BOUNDS=74 TYPE_LOWER_BOUNDS=75 CLOSURE_LIST=76 SH_COMMENT("a script header")=77 LITERAL_package="package"=78 LITERAL_import="import"=79 LITERAL_static="static"=80 LITERAL_def="def"=81 LBRACK("'['")=82 RBRACK("']'")=83 IDENT("an identifier")=84 STRING_LITERAL("a string literal")=85 LT("'<'")=86 DOT("'.'")=87 LPAREN("'('")=88 LITERAL_class="class"=89 LITERAL_interface="interface"=90 LITERAL_enum="enum"=91 AT("'@'")=92 QUESTION("'?'")=93 LITERAL_extends="extends"=94 LITERAL_super="super"=95 GT("'>'")=96 COMMA("','")=97 SR("'>>'")=98 BSR("'>>>'")=99 LITERAL_void="void"=100 LITERAL_boolean="boolean"=101 LITERAL_byte="byte"=102 LITERAL_char="char"=103 LITERAL_short="short"=104 LITERAL_int="int"=105 LITERAL_float="float"=106 LITERAL_long="long"=107 LITERAL_double="double"=108 STAR("'*'")=109 LITERAL_as="as"=110 LITERAL_private="private"=111 LITERAL_public="public"=112 LITERAL_protected="protected"=113 LITERAL_transient="transient"=114 LITERAL_native="native"=115 LITERAL_threadsafe="threadsafe"=116 LITERAL_synchronized="synchronized"=117 LITERAL_volatile="volatile"=118 RPAREN("')'")=119 ASSIGN("'='")=120 BAND("'&'")=121 LCURLY("'{'")=122 RCURLY("'}'")=123 SEMI("';'")=124 LITERAL_default="default"=125 LITERAL_throws="throws"=126 LITERAL_implements="implements"=127 LITERAL_this="this"=128 TRIPLE_DOT("'...'")=129 CLOSABLE_BLOCK_OP("'->'")=130 COLON("':'")=131 LITERAL_if="if"=132 LITERAL_else="else"=133 LITERAL_while="while"=134 LITERAL_switch="switch"=135 LITERAL_for="for"=136 LITERAL_in="in"=137 LITERAL_return="return"=138 LITERAL_break="break"=139 LITERAL_continue="continue"=140 LITERAL_throw="throw"=141 LITERAL_assert="assert"=142 PLUS("'+'")=143 MINUS("'-'")=144 LITERAL_case="case"=145 LITERAL_try="try"=146 LITERAL_finally="finally"=147 LITERAL_catch="catch"=148 SPREAD_DOT("'*.'")=149 OPTIONAL_DOT("'?.'")=150 MEMBER_POINTER("'.&'")=151 LITERAL_false="false"=152 LITERAL_instanceof="instanceof"=153 LITERAL_new="new"=154 LITERAL_null="null"=155 LITERAL_true="true"=156 PLUS_ASSIGN("'+='")=157 MINUS_ASSIGN("'-='")=158 STAR_ASSIGN("'*='")=159 DIV_ASSIGN("'/='")=160 MOD_ASSIGN("'%='")=161 SR_ASSIGN("'>>='")=162 BSR_ASSIGN("'>>>='")=163 SL_ASSIGN("'<<='")=164 BAND_ASSIGN("'&='")=165 BXOR_ASSIGN("'^='")=166 BOR_ASSIGN("'|='")=167 STAR_STAR_ASSIGN("'**='")=168 ELVIS_OPERATOR("'?:'")=169 LOR("'||'")=170 LAND("'&&'")=171 BOR("'|'")=172 BXOR("'^'")=173 REGEX_FIND("'=~'")=174 REGEX_MATCH("'==~'")=175 NOT_EQUAL("'!='")=176 EQUAL("'=='")=177 IDENTICAL("'==='")=178 NOT_IDENTICAL("'!=='")=179 COMPARE_TO("'<=>'")=180 LE("'<='")=181 GE("'>='")=182 SL("'<<'")=183 RANGE_INCLUSIVE("'..'")=184 RANGE_EXCLUSIVE("'..<'")=185 INC("'++'")=186 DIV("'/'")=187 MOD("'%'")=188 DEC("'--'")=189 STAR_STAR("'**'")=190 BNOT("'~'")=191 LNOT("'!'")=192 STRING_CTOR_START=193 STRING_CTOR_END("a string literal end")=194 NUM_INT("a numeric literal")=195 NUM_FLOAT=196 NUM_LONG=197 NUM_DOUBLE=198 NUM_BIG_INT=199 NUM_BIG_DECIMAL=200 NLS("some newlines, whitespace or comments")=201 DOLLAR("'$'")=202 WS("whitespace")=203 ONE_NL("a newline")=204 SL_COMMENT("a single line comment")=205 ML_COMMENT("a comment")=206 STRING_CH("a string character")=207 REGEXP_LITERAL("a multiline regular expression literal")=208 DOLLAR_REGEXP_LITERAL("a multiline dollar escaping regular expression literal")=209 REGEXP_CTOR_END("a multiline regular expression literal end")=210 DOLLAR_REGEXP_CTOR_END("a multiline dollar escaping regular expression literal end")=211 ESCAPED_SLASH=212 ESCAPED_DOLLAR=213 REGEXP_SYMBOL("a multiline regular expression character")=214 DOLLAR_REGEXP_SYMBOL("a multiline dollar escaping regular expression character")=215 ESC("an escape sequence")=216 STRING_NL("a newline inside a string")=217 HEX_DIGIT("a hexadecimal digit")=218 VOCAB("a character")=219 LETTER("a letter")=220 DIGIT("a digit")=221 EXPONENT("an exponent")=222 FLOAT_SUFFIX("a float or double suffix")=223 BIG_SUFFIX("a big decimal suffix")=224 groovy-1.8.6/src/main/org/codehaus/groovy/antlr/parser/GroovyRecognizer.java0000644001501200150120000136701511715044502026623 0ustar miguelmiguel// $ANTLR 2.7.7 (20060906): "groovy.g" -> "GroovyRecognizer.java"$ package org.codehaus.groovy.antlr.parser; import org.codehaus.groovy.antlr.*; import java.util.*; import java.io.InputStream; import java.io.Reader; import antlr.InputBuffer; import antlr.LexerSharedInputState; import antlr.CommonToken; import org.codehaus.groovy.GroovyBugError; import antlr.TokenStreamRecognitionException; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; import antlr.collections.AST; import java.util.Hashtable; import antlr.ASTFactory; import antlr.ASTPair; import antlr.collections.impl.ASTArray; /** JSR-241 Groovy Recognizer. * * Run 'java Main [-showtree] directory-full-of-groovy-files' * * [The -showtree option pops up a Swing frame that shows * the AST constructed from the parser.] * * Contributing authors: * John Mitchell johnm@non.net * Terence Parr parrt@magelang.com * John Lilley jlilley@empathy.com * Scott Stanchfield thetick@magelang.com * Markus Mohnen mohnen@informatik.rwth-aachen.de * Peter Williams pete.williams@sun.com * Allan Jacobs Allan.Jacobs@eng.sun.com * Steve Messick messick@redhills.com * James Strachan jstrachan@protique.com * John Pybus john@pybus.org * John Rose rose00@mac.com * Jeremy Rayner groovy@ross-rayner.com * Alex Popescu the.mindstorm@gmail.com * Martin Kempf mkempf@hsr.ch * Reto Kleeb rkleeb@hsr.ch * * Version 1.00 December 9, 1997 -- initial release * Version 1.01 December 10, 1997 * fixed bug in octal def (0..7 not 0..8) * Version 1.10 August 1998 (parrt) * added tree construction * fixed definition of WS,comments for mac,pc,unix newlines * added unary plus * Version 1.11 (Nov 20, 1998) * Added "shutup" option to turn off last ambig warning. * Fixed inner class def to allow named class defs as statements * synchronized requires compound not simple statement * add [] after builtInType DOT class in primaryExpression * "const" is reserved but not valid..removed from modifiers * Version 1.12 (Feb 2, 1999) * Changed LITERAL_xxx to xxx in tree grammar. * Updated java.g to use tokens {...} now for 2.6.0 (new feature). * * Version 1.13 (Apr 23, 1999) * Didn't have (stat)? for else clause in tree parser. * Didn't gen ASTs for interface extends. Updated tree parser too. * Updated to 2.6.0. * Version 1.14 (Jun 20, 1999) * Allowed final/abstract on local classes. * Removed local interfaces from methods * Put instanceof precedence where it belongs...in relationalExpr * It also had expr not type as arg; fixed it. * Missing ! on SEMI in classBlock * fixed: (expr) + "string" was parsed incorrectly (+ as unary plus). * fixed: didn't like Object[].class in parser or tree parser * Version 1.15 (Jun 26, 1999) * Screwed up rule with instanceof in it. :( Fixed. * Tree parser didn't like (expr).something; fixed. * Allowed multiple inheritance in tree grammar. oops. * Version 1.16 (August 22, 1999) * Extending an interface built a wacky tree: had extra EXTENDS. * Tree grammar didn't allow multiple superinterfaces. * Tree grammar didn't allow empty var initializer: {} * Version 1.17 (October 12, 1999) * ESC lexer rule allowed 399 max not 377 max. * java.tree.g didn't handle the expression of synchronized * statements. * Version 1.18 (August 12, 2001) * Terence updated to Java 2 Version 1.3 by * observing/combining work of Allan Jacobs and Steve * Messick. Handles 1.3 src. Summary: * o primary didn't include boolean.class kind of thing * o constructor calls parsed explicitly now: * see explicitConstructorInvocation * o add strictfp modifier * o missing objBlock after new expression in tree grammar * o merged local class definition alternatives, moved after declaration * o fixed problem with ClassName.super.field * o reordered some alternatives to make things more efficient * o long and double constants were not differentiated from int/float * o whitespace rule was inefficient: matched only one char * o add an examples directory with some nasty 1.3 cases * o made Main.java use buffered IO and a Reader for Unicode support * o supports UNICODE? * Using Unicode charVocabulary makes code file big, but only * in the bitsets at the end. I need to make ANTLR generate * unicode bitsets more efficiently. * Version 1.19 (April 25, 2002) * Terence added in nice fixes by John Pybus concerning floating * constants and problems with super() calls. John did a nice * reorg of the primary/postfix expression stuff to read better * and makes f.g.super() parse properly (it was METHOD_CALL not * a SUPER_CTOR_CALL). Also: * * o "finally" clause was a root...made it a child of "try" * o Added stuff for asserts too for Java 1.4, but *commented out* * as it is not backward compatible. * * Version 1.20 (October 27, 2002) * * Terence ended up reorging John Pybus' stuff to * remove some nondeterminisms and some syntactic predicates. * Note that the grammar is stricter now; e.g., this(...) must * be the first statement. * * Trinary ?: operator wasn't working as array name: * (isBig ? bigDigits : digits)[i]; * * Checked parser/tree parser on source for * Resin-2.0.5, jive-2.1.1, jdk 1.3.1, Lucene, antlr 2.7.2a4, * and the 110k-line jGuru server source. * * Version 1.21 (October 17, 2003) * Fixed lots of problems including: * Ray Waldin: add typeDefinition to interfaceBlock in java.tree.g * He found a problem/fix with floating point that start with 0 * Ray also fixed problem that (int.class) was not recognized. * Thorsten van Ellen noticed that \n are allowed incorrectly in strings. * TJP fixed CHAR_LITERAL analogously. * * Version 1.21.2 (March, 2003) * Changes by Matt Quail to support generics (as per JDK1.5/JSR14) * Notes: * o We only allow the "extends" keyword and not the "implements" * keyword, since that's what JSR14 seems to imply. * o Thanks to Monty Zukowski for his help on the antlr-interest * mail list. * o Thanks to Alan Eliasen for testing the grammar over his * Fink source base * * Version 1.22 (July, 2004) * Changes by Michael Studman to support Java 1.5 language extensions * Notes: * o Added support for annotations types * o Finished off Matt Quail's generics enhancements to support bound type arguments * o Added support for new for statement syntax * o Added support for static import syntax * o Added support for enum types * o Tested against JDK 1.5 source base and source base of jdigraph project * o Thanks to Matt Quail for doing the hard part by doing most of the generics work * * Version 1.22.1 (July 28, 2004) * Bug/omission fixes for Java 1.5 language support * o Fixed tree structure bug with classOrInterface - thanks to Pieter Vangorpto for * spotting this * o Fixed bug where incorrect handling of SR and BSR tokens would cause type * parameters to be recognised as type arguments. * o Enabled type parameters on constructors, annotations on enum constants * and package definitions * o Fixed problems when parsing if ((char.class.equals(c))) {} - solution by Matt Quail at Cenqua * * Version 1.22.2 (July 28, 2004) * Slight refactoring of Java 1.5 language support * o Refactored for/"foreach" productions so that original literal "for" literal * is still used but the for sub-clauses vary by token type * o Fixed bug where type parameter was not included in generic constructor's branch of AST * * Version 1.22.3 (August 26, 2004) * Bug fixes as identified by Michael Stahl; clean up of tabs/spaces * and other refactorings * o Fixed typeParameters omission in identPrimary and newStatement * o Replaced GT reconcilliation code with simple semantic predicate * o Adapted enum/assert keyword checking support from Michael Stahl's java15 grammar * o Refactored typeDefinition production and field productions to reduce duplication * * Version 1.22.4 (October 21, 2004) * Small bux fixes * o Added typeArguments to explicitConstructorInvocation, e.g. new MyParameterised() * o Added typeArguments to postfixExpression productions for anonymous inner class super * constructor invocation, e.g. new Outer().super() * o Fixed bug in array declarations identified by Geoff Roy * * Version 1.22.4.g.1 * o I have taken java.g for Java1.5 from Michael Studman (1.22.4) * and have applied the groovy.diff from java.g (1.22) by John Rose * back onto the new root (1.22.4) - Jeremy Rayner (Jan 2005) * o for a map of the task see... * http://groovy.javanicus.com/java-g.png * * Version 1.22.4.g.2 * o mkempf, rkleeb, Dec 2007 * o fixed various rules so that they call the correct Create Method * to make sure that the line information are correct * * This grammar is in the PUBLIC DOMAIN */ public class GroovyRecognizer extends antlr.LLkParser implements GroovyTokenTypes { /** This factory is the correct way to wire together a Groovy parser and lexer. */ public static GroovyRecognizer make(GroovyLexer lexer) { GroovyRecognizer parser = new GroovyRecognizer(lexer.plumb()); // TODO: set up a common error-handling control block, to avoid excessive tangle between these guys parser.lexer = lexer; lexer.parser = parser; parser.getASTFactory().setASTNodeClass(GroovySourceAST.class); parser.warningList = new ArrayList(); return parser; } // Create a scanner that reads from the input stream passed to us... public static GroovyRecognizer make(InputStream in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(Reader in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(InputBuffer in) { return make(new GroovyLexer(in)); } public static GroovyRecognizer make(LexerSharedInputState in) { return make(new GroovyLexer(in)); } private static GroovySourceAST dummyVariableToforceClassLoaderToFindASTClass = new GroovySourceAST(); List warningList; public List getWarningList() { return warningList; } GroovyLexer lexer; public GroovyLexer getLexer() { return lexer; } public void setFilename(String f) { super.setFilename(f); lexer.setFilename(f); } private SourceBuffer sourceBuffer; public void setSourceBuffer(SourceBuffer sourceBuffer) { this.sourceBuffer = sourceBuffer; } /** Create an AST node with the token type and text passed in, but * with the same background information as another supplied Token (e.g. line numbers). * To be used in place of antlr tree construction syntax, * i.e. #[TOKEN,"text"] becomes create(TOKEN,"text",anotherToken) * * todo - change antlr.ASTFactory to do this instead... */ public AST create(int type, String txt, AST first) { AST t = astFactory.create(type,txt); if ( t != null && first != null) { // first copy details from first token t.initialize(first); // then ensure that type and txt are specific to this new node t.initialize(type,txt); } return t; } private AST attachLast(AST t, Object last) { if ((t instanceof GroovySourceAST) && (last instanceof SourceInfo)) { SourceInfo lastInfo = (SourceInfo) last; GroovySourceAST node = (GroovySourceAST)t; node.setColumnLast(lastInfo.getColumn()); node.setLineLast(lastInfo.getLine()); // This is a good point to call node.setSnippet(), // but it bulks up the AST too much for production code. } return t; } public AST create(int type, String txt, Token first, Token last) { return attachLast(create(type, txt, astFactory.create(first)), last); } public AST create(int type, String txt, AST first, Token last) { return attachLast(create(type, txt, first), last); } public AST create(int type, String txt, AST first, AST last) { return attachLast(create(type, txt, first), last); } /** * Clones the token */ public Token cloneToken(Token t) { CommonToken clone = new CommonToken(t.getType(),t.getText()); clone.setLine(t.getLine()); clone.setColumn(t.getColumn()); return clone; } // stuff to adjust ANTLR's tracing machinery public static boolean tracing = false; // only effective if antlr.Tool is run with -traceParser public void traceIn(String rname) throws TokenStreamException { if (!GroovyRecognizer.tracing) return; super.traceIn(rname); } public void traceOut(String rname) throws TokenStreamException { if (!GroovyRecognizer.tracing) return; if (returnAST != null) rname += returnAST.toStringList(); super.traceOut(rname); } // Error handling. This is a funnel through which parser errors go, when the parser can suggest a solution. public void requireFailed(String problem, String solution) throws SemanticException { // TODO: Needs more work. Token lt = null; int lineNum = Token.badToken.getLine(), colNum = Token.badToken.getColumn(); try { lt = LT(1); if(lt != null) { lineNum = lt.getLine(); colNum = lt.getColumn(); } } catch (TokenStreamException ee) { if(ee instanceof TokenStreamRecognitionException) { lineNum = ((TokenStreamRecognitionException) ee).recog.getLine(); colNum = ((TokenStreamRecognitionException) ee).recog.getColumn(); } } throw new SemanticException(problem + ";\n solution: " + solution, getFilename(), lineNum, colNum); } public void addWarning(String warning, String solution) { Token lt = null; try { lt = LT(1); } catch (TokenStreamException ee) { } if (lt == null) lt = Token.badToken; Map row = new HashMap(); row.put("warning", warning); row.put("solution", solution); row.put("filename", getFilename()); row.put("line", Integer.valueOf(lt.getLine())); row.put("column", Integer.valueOf(lt.getColumn())); // System.out.println(row); warningList.add(row); } // Convenience method for checking of expected error syndromes. private void require(boolean z, String problem, String solution) throws SemanticException { if (!z) requireFailed(problem, solution); } private boolean matchGenericTypeBrackets(boolean z, String problem, String solution) throws SemanticException { if (!z) matchGenericTypeBracketsFailed(problem, solution); return z; } public void matchGenericTypeBracketsFailed(String problem, String solution) throws SemanticException { Token lt = null; int lineNum = Token.badToken.getLine(), colNum = Token.badToken.getColumn(); try { lt = LT(1); if(lt != null) { lineNum = lt.getLine(); colNum = lt.getColumn(); } } catch (TokenStreamException ee) { if(ee instanceof TokenStreamRecognitionException) { lineNum = ((TokenStreamRecognitionException) ee).recog.getLine(); colNum = ((TokenStreamRecognitionException) ee).recog.getColumn(); } } throw new SemanticException(problem + ";\n solution: " + solution, getFilename(), lineNum, colNum); } // Query a name token to see if it begins with a capital letter. // This is used to tell the difference (w/o symbol table access) between {String x} and {println x}. private boolean isUpperCase(Token x) { if (x == null || x.getType() != IDENT) return false; // cannot happen? String xtext = x.getText(); return (xtext.length() > 0 && Character.isUpperCase(xtext.charAt(0))); } private AST currentClass = null; // current enclosing class (for constructor recognition) // Query a name token to see if it is identical with the current class name. // This is used to distinguish constructors from other methods. private boolean isConstructorIdent(Token x) { if (currentClass == null) return false; if (currentClass.getType() != IDENT) return false; // cannot happen? String cname = currentClass.getText(); if (x == null || x.getType() != IDENT) return false; // cannot happen? return cname.equals(x.getText()); } private void dumpTree(AST ast, String offset) { dump(ast, offset); for (AST node = ast.getFirstChild(); node != null; node = node.getNextSibling()) { dumpTree(node, offset+"\t"); } } private void dump(AST node, String offset) { System.out.println(offset+"Type: " + getTokenName(node) + " text: " + node.getText()); } private String getTokenName(AST node) { if (node == null) return "null"; return getTokenName(node.getType()); } // Scratch variable for last 'sep' token. // Written by the 'sep' rule, read only by immediate callers of 'sep'. // (Not entirely clean, but better than a million xx=sep occurrences.) private int sepToken = EOF; // Scratch variable for last argument list; tells whether there was a label. // Written by 'argList' rule, read only by immediate callers of 'argList'. private boolean argListHasLabels = false; // Scratch variable, holds most recently completed pathExpression. // Read only by immediate callers of 'pathExpression' and 'expression'. private AST lastPathExpression = null; // Inherited attribute pushed into most expression rules. // If not zero, it means that the left context of the expression // being parsed is a statement boundary or an initializer sign '='. // Only such expressions are allowed to reach across newlines // to pull in an LCURLY and appended block. private final int LC_STMT = 1, LC_INIT = 2; /** * Counts the number of LT seen in the typeArguments production. * It is used in semantic predicates to ensure we have seen * enough closing '>' characters; which actually may have been * either GT, SR or BSR tokens. */ private int ltCounter = 0; /* This symbol is used to work around a known ANTLR limitation. * In a loop with syntactic predicate, ANTLR needs help knowing * that the loop exit is a second alternative. * Example usage: ( (LCURLY)=> block | {ANTLR_LOOP_EXIT}? )* * Probably should be an ANTLR RFE. */ ////// Original comment in Java grammar: // Unfortunately a syntactic predicate can only select one of // multiple alternatives on the same level, not break out of // an enclosing loop, which is why this ugly hack (a fake // empty alternative with always-false semantic predicate) // is necessary. private static final boolean ANTLR_LOOP_EXIT = false; protected GroovyRecognizer(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public GroovyRecognizer(TokenBuffer tokenBuf) { this(tokenBuf,2); } protected GroovyRecognizer(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public GroovyRecognizer(TokenStream lexer) { this(lexer,2); } public GroovyRecognizer(ParserSharedInputState state) { super(state,2); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public final void compilationUnit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST compilationUnit_AST = null; { switch ( LA(1)) { case SH_COMMENT: { match(SH_COMMENT); break; } case EOF: case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case SEMI: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); { boolean synPredMatched5 = false; if (((LA(1)==LITERAL_package||LA(1)==AT) && (LA(2)==IDENT||LA(2)==LITERAL_interface))) { int _m5 = mark(); synPredMatched5 = true; inputState.guessing++; try { { annotationsOpt(); match(LITERAL_package); } } catch (RecognitionException pe) { synPredMatched5 = false; } rewind(_m5); inputState.guessing--; } if ( synPredMatched5 ) { packageDefinition(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_0.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { statement(EOF); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { throw new NoViableAltException(LT(1), getFilename()); } } { _loop9: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { statement(sepToken); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop9; } } while (true); } match(Token.EOF_TYPE); compilationUnit_AST = (AST)currentAST.root; returnAST = compilationUnit_AST; } /** Zero or more insignificant newlines, all gobbled up and thrown away. */ public final void nls() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST nls_AST = null; { if ((LA(1)==NLS) && (_tokenSet_2.member(LA(2)))) { match(NLS); } else if ((_tokenSet_2.member(LA(1))) && (_tokenSet_3.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = nls_AST; } public final void annotationsOpt() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationsOpt_AST = null; Token first = LT(1); { if ((_tokenSet_4.member(LA(1))) && (_tokenSet_5.member(LA(2)))) { annotationsInternal(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_6.member(LA(1))) && (_tokenSet_7.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { annotationsOpt_AST = (AST)currentAST.root; annotationsOpt_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(ANNOTATIONS,"ANNOTATIONS",first,LT(1))).add(annotationsOpt_AST)); currentAST.root = annotationsOpt_AST; currentAST.child = annotationsOpt_AST!=null &&annotationsOpt_AST.getFirstChild()!=null ? annotationsOpt_AST.getFirstChild() : annotationsOpt_AST; currentAST.advanceChildToEnd(); } annotationsOpt_AST = (AST)currentAST.root; returnAST = annotationsOpt_AST; } public final void packageDefinition() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST packageDefinition_AST = null; AST an_AST = null; AST id_AST = null; Token first = LT(1); annotationsOpt(); an_AST = (AST)returnAST; match(LITERAL_package); identifier(); id_AST = (AST)returnAST; if ( inputState.guessing==0 ) { packageDefinition_AST = (AST)currentAST.root; packageDefinition_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(PACKAGE_DEF,"package",first,LT(1))).add(an_AST).add(id_AST)); currentAST.root = packageDefinition_AST; currentAST.child = packageDefinition_AST!=null &&packageDefinition_AST.getFirstChild()!=null ? packageDefinition_AST.getFirstChild() : packageDefinition_AST; currentAST.advanceChildToEnd(); } packageDefinition_AST = (AST)currentAST.root; returnAST = packageDefinition_AST; } /** A statement is an element of a block. * Typical statements are declarations (which are scoped to the block) * and expressions. */ public final void statement( int prevToken ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST statement_AST = null; AST pfx_AST = null; AST es_AST = null; AST ale_AST = null; AST ifCbs_AST = null; AST elseCbs_AST = null; AST while_sce_AST = null; Token s = null; AST s_AST = null; AST while_cbs_AST = null; AST m_AST = null; AST switchSce_AST = null; AST cg_AST = null; AST synch_sce_AST = null; AST synch_cs_AST = null; boolean sce=false; Token first = LT(1); AST casesGroup_AST = null; switch ( LA(1)) { case LITERAL_if: { match(LITERAL_if); match(LPAREN); assignmentLessExpression(); ale_AST = (AST)returnAST; match(RPAREN); nlsWarn(); compatibleBodyStatement(); ifCbs_AST = (AST)returnAST; { boolean synPredMatched294 = false; if (((_tokenSet_8.member(LA(1))) && (_tokenSet_9.member(LA(2))))) { int _m294 = mark(); synPredMatched294 = true; inputState.guessing++; try { { { switch ( LA(1)) { case SEMI: case NLS: { sep(); break; } case LITERAL_else: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(LITERAL_else); } } catch (RecognitionException pe) { synPredMatched294 = false; } rewind(_m294); inputState.guessing--; } if ( synPredMatched294 ) { { switch ( LA(1)) { case SEMI: case NLS: { sep(); break; } case LITERAL_else: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(LITERAL_else); nlsWarn(); compatibleBodyStatement(); elseCbs_AST = (AST)returnAST; } else if ((_tokenSet_10.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { statement_AST = (AST)currentAST.root; statement_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(LITERAL_if,"if",first,LT(1))).add(ale_AST).add(ifCbs_AST).add(elseCbs_AST)); currentAST.root = statement_AST; currentAST.child = statement_AST!=null &&statement_AST.getFirstChild()!=null ? statement_AST.getFirstChild() : statement_AST; currentAST.advanceChildToEnd(); } statement_AST = (AST)currentAST.root; break; } case LITERAL_for: { forStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_while: { match(LITERAL_while); match(LPAREN); sce=strictContextExpression(false); while_sce_AST = (AST)returnAST; match(RPAREN); nlsWarn(); { switch ( LA(1)) { case SEMI: { s = LT(1); s_AST = astFactory.create(s); match(SEMI); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { compatibleBodyStatement(); while_cbs_AST = (AST)returnAST; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { statement_AST = (AST)currentAST.root; if (s_AST != null) statement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_while,"Literal_while",first,LT(1))).add(while_sce_AST).add(s_AST)); else statement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_while,"Literal_while",first,LT(1))).add(while_sce_AST).add(while_cbs_AST)); currentAST.root = statement_AST; currentAST.child = statement_AST!=null &&statement_AST.getFirstChild()!=null ? statement_AST.getFirstChild() : statement_AST; currentAST.advanceChildToEnd(); } statement_AST = (AST)currentAST.root; break; } case LITERAL_switch: { match(LITERAL_switch); match(LPAREN); sce=strictContextExpression(false); switchSce_AST = (AST)returnAST; match(RPAREN); nlsWarn(); match(LCURLY); nls(); { _loop300: do { if ((LA(1)==LITERAL_default||LA(1)==LITERAL_case)) { casesGroup(); cg_AST = (AST)returnAST; if ( inputState.guessing==0 ) { casesGroup_AST = (AST)astFactory.make( (new ASTArray(3)).add(null).add(casesGroup_AST).add(cg_AST)); } } else { break _loop300; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { statement_AST = (AST)currentAST.root; statement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_switch,"switch",first,LT(1))).add(switchSce_AST).add(casesGroup_AST)); currentAST.root = statement_AST; currentAST.child = statement_AST!=null &&statement_AST.getFirstChild()!=null ? statement_AST.getFirstChild() : statement_AST; currentAST.advanceChildToEnd(); } statement_AST = (AST)currentAST.root; break; } case LITERAL_try: { tryBlock(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: { branchStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; break; } default: boolean synPredMatched281 = false; if (((_tokenSet_12.member(LA(1))) && (_tokenSet_13.member(LA(2))))) { int _m281 = mark(); synPredMatched281 = true; inputState.guessing++; try { { genericMethodStart(); } } catch (RecognitionException pe) { synPredMatched281 = false; } rewind(_m281); inputState.guessing--; } if ( synPredMatched281 ) { genericMethod(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else { boolean synPredMatched283 = false; if (((_tokenSet_12.member(LA(1))) && (_tokenSet_14.member(LA(2))))) { int _m283 = mark(); synPredMatched283 = true; inputState.guessing++; try { { multipleAssignmentDeclarationStart(); } } catch (RecognitionException pe) { synPredMatched283 = false; } rewind(_m283); inputState.guessing--; } if ( synPredMatched283 ) { multipleAssignmentDeclaration(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else { boolean synPredMatched285 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_16.member(LA(2))))) { int _m285 = mark(); synPredMatched285 = true; inputState.guessing++; try { { declarationStart(); } } catch (RecognitionException pe) { synPredMatched285 = false; } rewind(_m285); inputState.guessing--; } if ( synPredMatched285 ) { declaration(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else { boolean synPredMatched287 = false; if (((LA(1)==IDENT) && (LA(2)==COLON))) { int _m287 = mark(); synPredMatched287 = true; inputState.guessing++; try { { match(IDENT); match(COLON); } } catch (RecognitionException pe) { synPredMatched287 = false; } rewind(_m287); inputState.guessing--; } if ( synPredMatched287 ) { statementLabelPrefix(); pfx_AST = (AST)returnAST; if ( inputState.guessing==0 ) { statement_AST = (AST)currentAST.root; statement_AST = pfx_AST; currentAST.root = statement_AST; currentAST.child = statement_AST!=null &&statement_AST.getFirstChild()!=null ? statement_AST.getFirstChild() : statement_AST; currentAST.advanceChildToEnd(); } { boolean synPredMatched290 = false; if (((LA(1)==LCURLY) && (_tokenSet_17.member(LA(2))))) { int _m290 = mark(); synPredMatched290 = true; inputState.guessing++; try { { match(LCURLY); } } catch (RecognitionException pe) { synPredMatched290 = false; } rewind(_m290); inputState.guessing--; } if ( synPredMatched290 ) { openOrClosableBlock(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_18.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { statement(COLON); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } statement_AST = (AST)currentAST.root; } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { expressionStatement(prevToken); es_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else { boolean synPredMatched298 = false; if (((LA(1)==LITERAL_import||LA(1)==AT) && (_tokenSet_20.member(LA(2))))) { int _m298 = mark(); synPredMatched298 = true; inputState.guessing++; try { { annotationsOpt(); match(LITERAL_import); } } catch (RecognitionException pe) { synPredMatched298 = false; } rewind(_m298); inputState.guessing--; } if ( synPredMatched298 ) { importStatement(); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else if ((_tokenSet_21.member(LA(1))) && (_tokenSet_22.member(LA(2)))) { modifiersOpt(); m_AST = (AST)returnAST; typeDefinitionInternal(m_AST); astFactory.addASTChild(currentAST, returnAST); statement_AST = (AST)currentAST.root; } else if ((LA(1)==LITERAL_synchronized) && (LA(2)==LPAREN)) { match(LITERAL_synchronized); match(LPAREN); sce=strictContextExpression(false); synch_sce_AST = (AST)returnAST; match(RPAREN); nlsWarn(); compoundStatement(); synch_cs_AST = (AST)returnAST; if ( inputState.guessing==0 ) { statement_AST = (AST)currentAST.root; statement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_synchronized,"synchronized",first,LT(1))).add(synch_sce_AST).add(synch_cs_AST)); currentAST.root = statement_AST; currentAST.child = statement_AST!=null &&statement_AST.getFirstChild()!=null ? statement_AST.getFirstChild() : statement_AST; currentAST.advanceChildToEnd(); } statement_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } }}}}} returnAST = statement_AST; } /** A statement separator is either a semicolon or a significant newline. * Any number of additional (insignificant) newlines may accompany it. */ public final void sep() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST sep_AST = null; switch ( LA(1)) { case SEMI: { match(SEMI); { _loop566: do { if ((LA(1)==NLS) && (_tokenSet_23.member(LA(2)))) { match(NLS); } else { break _loop566; } } while (true); } if ( inputState.guessing==0 ) { sepToken = SEMI; } break; } case NLS: { match(NLS); if ( inputState.guessing==0 ) { sepToken = NLS; } { _loop570: do { if ((LA(1)==SEMI) && (_tokenSet_23.member(LA(2)))) { match(SEMI); { _loop569: do { if ((LA(1)==NLS) && (_tokenSet_23.member(LA(2)))) { match(NLS); } else { break _loop569; } } while (true); } if ( inputState.guessing==0 ) { sepToken = SEMI; } } else { break _loop570; } } while (true); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = sep_AST; } /** A Groovy script or simple expression. Can be anything legal inside {...}. */ public final void snippetUnit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST snippetUnit_AST = null; nls(); blockBody(EOF); astFactory.addASTChild(currentAST, returnAST); snippetUnit_AST = (AST)currentAST.root; returnAST = snippetUnit_AST; } /** A block body is a parade of zero or more statements or expressions. */ public final void blockBody( int prevToken ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST blockBody_AST = null; { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { statement(prevToken); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop275: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { statement(sepToken); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop275; } } while (true); } blockBody_AST = (AST)currentAST.root; returnAST = blockBody_AST; } public final void identifier() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST identifier_AST = null; Token i1 = null; AST i1_AST = null; Token d = null; AST d_AST = null; Token i2 = null; AST i2_AST = null; Token first = LT(1); i1 = LT(1); i1_AST = astFactory.create(i1); match(IDENT); { _loop72: do { if ((LA(1)==DOT)) { d = LT(1); d_AST = astFactory.create(d); match(DOT); nls(); i2 = LT(1); i2_AST = astFactory.create(i2); match(IDENT); if ( inputState.guessing==0 ) { i1_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(DOT,".",first,LT(1))).add(i1_AST).add(i2_AST)); } } else { break _loop72; } } while (true); } if ( inputState.guessing==0 ) { identifier_AST = (AST)currentAST.root; identifier_AST = i1_AST; currentAST.root = identifier_AST; currentAST.child = identifier_AST!=null &&identifier_AST.getFirstChild()!=null ? identifier_AST.getFirstChild() : identifier_AST; currentAST.advanceChildToEnd(); } identifier_AST = (AST)currentAST.root; returnAST = identifier_AST; } public final void importStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST importStatement_AST = null; AST an_AST = null; AST is_AST = null; Token first = LT(1); boolean isStatic = false; annotationsOpt(); an_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); match(LITERAL_import); { switch ( LA(1)) { case LITERAL_static: { match(LITERAL_static); if ( inputState.guessing==0 ) { isStatic=true; } break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } identifierStar(); is_AST = (AST)returnAST; if ( inputState.guessing==0 ) { importStatement_AST = (AST)currentAST.root; if (isStatic) importStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(STATIC_IMPORT,"static_import",first,LT(1))).add(an_AST).add(is_AST)); else importStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(IMPORT,"import",first,LT(1))).add(an_AST).add(is_AST)); currentAST.root = importStatement_AST; currentAST.child = importStatement_AST!=null &&importStatement_AST.getFirstChild()!=null ? importStatement_AST.getFirstChild() : importStatement_AST; currentAST.advanceChildToEnd(); } importStatement_AST = (AST)currentAST.root; returnAST = importStatement_AST; } public final void identifierStar() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST identifierStar_AST = null; Token i1 = null; AST i1_AST = null; Token d1 = null; AST d1_AST = null; Token i2 = null; AST i2_AST = null; Token d2 = null; AST d2_AST = null; Token s = null; AST s_AST = null; Token alias = null; AST alias_AST = null; Token first = LT(1); i1 = LT(1); i1_AST = astFactory.create(i1); match(IDENT); { _loop75: do { if ((LA(1)==DOT) && (LA(2)==IDENT||LA(2)==NLS)) { d1 = LT(1); d1_AST = astFactory.create(d1); match(DOT); nls(); i2 = LT(1); i2_AST = astFactory.create(i2); match(IDENT); if ( inputState.guessing==0 ) { i1_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(DOT,".",first,LT(1))).add(i1_AST).add(i2_AST)); } } else { break _loop75; } } while (true); } { switch ( LA(1)) { case DOT: { d2 = LT(1); d2_AST = astFactory.create(d2); match(DOT); nls(); s = LT(1); s_AST = astFactory.create(s); match(STAR); if ( inputState.guessing==0 ) { i1_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(DOT,".",first,LT(1))).add(i1_AST).add(s_AST)); } break; } case LITERAL_as: { match(LITERAL_as); nls(); alias = LT(1); alias_AST = astFactory.create(alias); match(IDENT); if ( inputState.guessing==0 ) { i1_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_as,"as",first,LT(1))).add(i1_AST).add(alias_AST)); } break; } case EOF: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_else: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { identifierStar_AST = (AST)currentAST.root; identifierStar_AST = i1_AST; currentAST.root = identifierStar_AST; currentAST.child = identifierStar_AST!=null &&identifierStar_AST.getFirstChild()!=null ? identifierStar_AST.getFirstChild() : identifierStar_AST; currentAST.advanceChildToEnd(); } identifierStar_AST = (AST)currentAST.root; returnAST = identifierStar_AST; } protected final void typeDefinitionInternal( AST mods ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeDefinitionInternal_AST = null; AST cd_AST = null; AST id_AST = null; AST ed_AST = null; AST ad_AST = null; switch ( LA(1)) { case LITERAL_class: { classDefinition(mods); cd_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { typeDefinitionInternal_AST = (AST)currentAST.root; typeDefinitionInternal_AST = cd_AST; currentAST.root = typeDefinitionInternal_AST; currentAST.child = typeDefinitionInternal_AST!=null &&typeDefinitionInternal_AST.getFirstChild()!=null ? typeDefinitionInternal_AST.getFirstChild() : typeDefinitionInternal_AST; currentAST.advanceChildToEnd(); } typeDefinitionInternal_AST = (AST)currentAST.root; break; } case LITERAL_interface: { interfaceDefinition(mods); id_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { typeDefinitionInternal_AST = (AST)currentAST.root; typeDefinitionInternal_AST = id_AST; currentAST.root = typeDefinitionInternal_AST; currentAST.child = typeDefinitionInternal_AST!=null &&typeDefinitionInternal_AST.getFirstChild()!=null ? typeDefinitionInternal_AST.getFirstChild() : typeDefinitionInternal_AST; currentAST.advanceChildToEnd(); } typeDefinitionInternal_AST = (AST)currentAST.root; break; } case LITERAL_enum: { enumDefinition(mods); ed_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { typeDefinitionInternal_AST = (AST)currentAST.root; typeDefinitionInternal_AST = ed_AST; currentAST.root = typeDefinitionInternal_AST; currentAST.child = typeDefinitionInternal_AST!=null &&typeDefinitionInternal_AST.getFirstChild()!=null ? typeDefinitionInternal_AST.getFirstChild() : typeDefinitionInternal_AST; currentAST.advanceChildToEnd(); } typeDefinitionInternal_AST = (AST)currentAST.root; break; } case AT: { annotationDefinition(mods); ad_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { typeDefinitionInternal_AST = (AST)currentAST.root; typeDefinitionInternal_AST = ad_AST; currentAST.root = typeDefinitionInternal_AST; currentAST.child = typeDefinitionInternal_AST!=null &&typeDefinitionInternal_AST.getFirstChild()!=null ? typeDefinitionInternal_AST.getFirstChild() : typeDefinitionInternal_AST; currentAST.advanceChildToEnd(); } typeDefinitionInternal_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeDefinitionInternal_AST; } public final void classDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classDefinition_AST = null; AST tp_AST = null; AST sc_AST = null; AST ic_AST = null; AST cb_AST = null; Token first = cloneToken(LT(1));AST prevCurrentClass = currentClass; if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); } match(LITERAL_class); AST tmp29_AST = null; tmp29_AST = astFactory.create(LT(1)); match(IDENT); nls(); if ( inputState.guessing==0 ) { currentClass = tmp29_AST; } { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; nls(); break; } case LITERAL_extends: case LCURLY: case LITERAL_implements: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } superClassClause(); sc_AST = (AST)returnAST; implementsClause(); ic_AST = (AST)returnAST; classBlock(); cb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classDefinition_AST = (AST)currentAST.root; classDefinition_AST = (AST)astFactory.make( (new ASTArray(7)).add(create(CLASS_DEF,"CLASS_DEF",first,LT(1))).add(modifiers).add(tmp29_AST).add(tp_AST).add(sc_AST).add(ic_AST).add(cb_AST)); currentAST.root = classDefinition_AST; currentAST.child = classDefinition_AST!=null &&classDefinition_AST.getFirstChild()!=null ? classDefinition_AST.getFirstChild() : classDefinition_AST; currentAST.advanceChildToEnd(); } if ( inputState.guessing==0 ) { currentClass = prevCurrentClass; } returnAST = classDefinition_AST; } public final void interfaceDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceDefinition_AST = null; AST tp_AST = null; AST ie_AST = null; AST ib_AST = null; Token first = cloneToken(LT(1)); if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); } match(LITERAL_interface); AST tmp31_AST = null; tmp31_AST = astFactory.create(LT(1)); match(IDENT); nls(); { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; nls(); break; } case LITERAL_extends: case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } interfaceExtends(); ie_AST = (AST)returnAST; interfaceBlock(); ib_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceDefinition_AST = (AST)currentAST.root; interfaceDefinition_AST = (AST)astFactory.make( (new ASTArray(6)).add(create(INTERFACE_DEF,"INTERFACE_DEF",first,LT(1))).add(modifiers).add(tmp31_AST).add(tp_AST).add(ie_AST).add(ib_AST)); currentAST.root = interfaceDefinition_AST; currentAST.child = interfaceDefinition_AST!=null &&interfaceDefinition_AST.getFirstChild()!=null ? interfaceDefinition_AST.getFirstChild() : interfaceDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = interfaceDefinition_AST; } public final void enumDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumDefinition_AST = null; AST ic_AST = null; AST eb_AST = null; Token first = cloneToken(LT(1)); AST prevCurrentClass = currentClass; if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); } match(LITERAL_enum); AST tmp33_AST = null; tmp33_AST = astFactory.create(LT(1)); match(IDENT); if ( inputState.guessing==0 ) { currentClass = tmp33_AST; } nls(); implementsClause(); ic_AST = (AST)returnAST; nls(); enumBlock(); eb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumDefinition_AST = (AST)currentAST.root; enumDefinition_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(ENUM_DEF,"ENUM_DEF",first,LT(1))).add(modifiers).add(tmp33_AST).add(ic_AST).add(eb_AST)); currentAST.root = enumDefinition_AST; currentAST.child = enumDefinition_AST!=null &&enumDefinition_AST.getFirstChild()!=null ? enumDefinition_AST.getFirstChild() : enumDefinition_AST; currentAST.advanceChildToEnd(); } if ( inputState.guessing==0 ) { currentClass = prevCurrentClass; } returnAST = enumDefinition_AST; } public final void annotationDefinition( AST modifiers ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationDefinition_AST = null; AST ab_AST = null; Token first = cloneToken(LT(1)); if (modifiers != null) { first.setLine(modifiers.getLine()); first.setColumn(modifiers.getColumn()); } AST tmp34_AST = null; tmp34_AST = astFactory.create(LT(1)); match(AT); match(LITERAL_interface); AST tmp36_AST = null; tmp36_AST = astFactory.create(LT(1)); match(IDENT); annotationBlock(); ab_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationDefinition_AST = (AST)currentAST.root; annotationDefinition_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(ANNOTATION_DEF,"ANNOTATION_DEF",first,LT(1))).add(modifiers).add(tmp36_AST).add(ab_AST)); currentAST.root = annotationDefinition_AST; currentAST.child = annotationDefinition_AST!=null &&annotationDefinition_AST.getFirstChild()!=null ? annotationDefinition_AST.getFirstChild() : annotationDefinition_AST; currentAST.advanceChildToEnd(); } returnAST = annotationDefinition_AST; } /** A declaration is the creation of a reference or primitive-type variable, * or (if arguments are present) of a method. * Generically, this is called a 'variable' definition, even in the case of a class field or method. * It may start with the modifiers and/or a declaration keyword "def". * It may also start with the modifiers and a capitalized type name. *

      * AST effect: Create a separate Type/Var tree for each var in the var list. * Must be guarded, as in (declarationStart) => declaration. */ public final void declaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST declaration_AST = null; AST m_AST = null; AST t_AST = null; AST v_AST = null; AST t2_AST = null; AST v2_AST = null; switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case AT: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifiers(); m_AST = (AST)returnAST; { if ((_tokenSet_24.member(LA(1))) && (_tokenSet_25.member(LA(2)))) { typeSpec(false); t_AST = (AST)returnAST; } else if ((LA(1)==IDENT||LA(1)==STRING_LITERAL) && (_tokenSet_26.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } variableDefinitions(m_AST, t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { declaration_AST = (AST)currentAST.root; declaration_AST = v_AST; currentAST.root = declaration_AST; currentAST.child = declaration_AST!=null &&declaration_AST.getFirstChild()!=null ? declaration_AST.getFirstChild() : declaration_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeSpec(false); t2_AST = (AST)returnAST; variableDefinitions(null,t2_AST); v2_AST = (AST)returnAST; if ( inputState.guessing==0 ) { declaration_AST = (AST)currentAST.root; declaration_AST = v2_AST; currentAST.root = declaration_AST; currentAST.child = declaration_AST!=null &&declaration_AST.getFirstChild()!=null ? declaration_AST.getFirstChild() : declaration_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = declaration_AST; } /** A list of one or more modifier, annotation, or "def". */ public final void modifiers() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifiers_AST = null; Token first = LT(1); modifiersInternal(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { modifiers_AST = (AST)currentAST.root; modifiers_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))).add(modifiers_AST)); currentAST.root = modifiers_AST; currentAST.child = modifiers_AST!=null &&modifiers_AST.getFirstChild()!=null ? modifiers_AST.getFirstChild() : modifiers_AST; currentAST.advanceChildToEnd(); } modifiers_AST = (AST)currentAST.root; returnAST = modifiers_AST; } public final void typeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeSpec_AST = null; switch ( LA(1)) { case IDENT: { classTypeSpec(addImagNode); astFactory.addASTChild(currentAST, returnAST); typeSpec_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInTypeSpec(addImagNode); astFactory.addASTChild(currentAST, returnAST); typeSpec_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeSpec_AST; } /** The tail of a declaration. * Either v1, v2, ... (with possible initializers) or else m(args){body}. * The two arguments are the modifier list (if any) and the declaration head (if any). * The declaration head is the variable type, or (for a method) the return type. * If it is missing, then the variable type is taken from its initializer (if there is one). * Otherwise, the variable type defaults to 'any'. * DECIDE: Method return types default to the type of the method body, as an expression. */ public final void variableDefinitions( AST mods, AST t ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableDefinitions_AST = null; Token id = null; AST id_AST = null; Token qid = null; AST qid_AST = null; AST param_AST = null; AST tc_AST = null; AST mb_AST = null; Token first = cloneToken(LT(1)); if (mods != null) { first.setLine(mods.getLine()); first.setColumn(mods.getColumn()); } else if (t != null) { first.setLine(t.getLine()); first.setColumn(t.getColumn()); } if ((LA(1)==IDENT) && (_tokenSet_27.member(LA(2)))) { listOfVariables(mods,t,first); astFactory.addASTChild(currentAST, returnAST); variableDefinitions_AST = (AST)currentAST.root; } else if ((LA(1)==IDENT||LA(1)==STRING_LITERAL) && (LA(2)==LPAREN)) { { switch ( LA(1)) { case IDENT: { id = LT(1); id_AST = astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(IDENT); break; } case STRING_LITERAL: { qid = LT(1); qid_AST = astFactory.create(qid); astFactory.addASTChild(currentAST, qid_AST); match(STRING_LITERAL); if ( inputState.guessing==0 ) { qid_AST.setType(IDENT); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); { boolean synPredMatched233 = false; if (((LA(1)==LITERAL_throws||LA(1)==NLS) && (_tokenSet_28.member(LA(2))))) { int _m233 = mark(); synPredMatched233 = true; inputState.guessing++; try { { nls(); match(LITERAL_throws); } } catch (RecognitionException pe) { synPredMatched233 = false; } rewind(_m233); inputState.guessing--; } if ( synPredMatched233 ) { throwsClause(); tc_AST = (AST)returnAST; } else if ((_tokenSet_29.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { boolean synPredMatched236 = false; if (((LA(1)==LCURLY||LA(1)==NLS) && (_tokenSet_30.member(LA(2))))) { int _m236 = mark(); synPredMatched236 = true; inputState.guessing++; try { { nls(); match(LCURLY); } } catch (RecognitionException pe) { synPredMatched236 = false; } rewind(_m236); inputState.guessing--; } if ( synPredMatched236 ) { { nlsWarn(); openBlock(); mb_AST = (AST)returnAST; } } else if ((_tokenSet_10.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { variableDefinitions_AST = (AST)currentAST.root; if (qid_AST != null) id_AST = qid_AST; variableDefinitions_AST = (AST)astFactory.make( (new ASTArray(7)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t))).add(id_AST).add(param_AST).add(tc_AST).add(mb_AST)); currentAST.root = variableDefinitions_AST; currentAST.child = variableDefinitions_AST!=null &&variableDefinitions_AST.getFirstChild()!=null ? variableDefinitions_AST.getFirstChild() : variableDefinitions_AST; currentAST.advanceChildToEnd(); } variableDefinitions_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = variableDefinitions_AST; } public final void genericMethod() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST genericMethod_AST = null; AST m_AST = null; AST p_AST = null; AST t_AST = null; AST v_AST = null; modifiers(); m_AST = (AST)returnAST; typeParameters(); p_AST = (AST)returnAST; typeSpec(false); t_AST = (AST)returnAST; variableDefinitions(m_AST, t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { genericMethod_AST = (AST)currentAST.root; genericMethod_AST = v_AST; AST old = v_AST.getFirstChild(); genericMethod_AST.setFirstChild(p_AST); p_AST.setNextSibling(old); currentAST.root = genericMethod_AST; currentAST.child = genericMethod_AST!=null &&genericMethod_AST.getFirstChild()!=null ? genericMethod_AST.getFirstChild() : genericMethod_AST; currentAST.advanceChildToEnd(); } returnAST = genericMethod_AST; } public final void typeParameters() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameters_AST = null; Token first = LT(1);int currentLtLevel = 0; if ( inputState.guessing==0 ) { currentLtLevel = ltCounter; } match(LT); if ( inputState.guessing==0 ) { ltCounter++; } nls(); typeParameter(); astFactory.addASTChild(currentAST, returnAST); { _loop110: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); typeParameter(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop110; } } while (true); } nls(); { switch ( LA(1)) { case GT: case SR: case BSR: { typeArgumentsOrParametersEnd(); astFactory.addASTChild(currentAST, returnAST); break; } case IDENT: case LITERAL_extends: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_implements: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if (!(matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel), "Missing closing bracket '>' for generics types", "Please specify the missing bracket!"))) throw new SemanticException("matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel),\n \"Missing closing bracket '>' for generics types\", \"Please specify the missing bracket!\")"); if ( inputState.guessing==0 ) { typeParameters_AST = (AST)currentAST.root; typeParameters_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_PARAMETERS,"TYPE_PARAMETERS",first,LT(1))).add(typeParameters_AST)); currentAST.root = typeParameters_AST; currentAST.child = typeParameters_AST!=null &&typeParameters_AST.getFirstChild()!=null ? typeParameters_AST.getFirstChild() : typeParameters_AST; currentAST.advanceChildToEnd(); } typeParameters_AST = (AST)currentAST.root; returnAST = typeParameters_AST; } /** A declaration with one declarator and no initialization, like a parameterDeclaration. * Used to parse loops like for (int x in y) (up to the in keyword). */ public final void singleDeclarationNoInit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST singleDeclarationNoInit_AST = null; AST m_AST = null; AST t_AST = null; AST v_AST = null; AST t2_AST = null; AST v2_AST = null; switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case AT: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifiers(); m_AST = (AST)returnAST; { if ((_tokenSet_24.member(LA(1))) && (_tokenSet_31.member(LA(2)))) { typeSpec(false); t_AST = (AST)returnAST; } else if ((LA(1)==IDENT) && (_tokenSet_32.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } singleVariable(m_AST, t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { singleDeclarationNoInit_AST = (AST)currentAST.root; singleDeclarationNoInit_AST = v_AST; currentAST.root = singleDeclarationNoInit_AST; currentAST.child = singleDeclarationNoInit_AST!=null &&singleDeclarationNoInit_AST.getFirstChild()!=null ? singleDeclarationNoInit_AST.getFirstChild() : singleDeclarationNoInit_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeSpec(false); t2_AST = (AST)returnAST; singleVariable(null,t2_AST); v2_AST = (AST)returnAST; if ( inputState.guessing==0 ) { singleDeclarationNoInit_AST = (AST)currentAST.root; singleDeclarationNoInit_AST = v2_AST; currentAST.root = singleDeclarationNoInit_AST; currentAST.child = singleDeclarationNoInit_AST!=null &&singleDeclarationNoInit_AST.getFirstChild()!=null ? singleDeclarationNoInit_AST.getFirstChild() : singleDeclarationNoInit_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = singleDeclarationNoInit_AST; } /** Used in cases where a declaration cannot have commas, or ends with the "in" operator instead of '='. */ public final void singleVariable( AST mods, AST t ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST singleVariable_AST = null; AST id_AST = null; Token first = LT(1); variableName(); id_AST = (AST)returnAST; if ( inputState.guessing==0 ) { singleVariable_AST = (AST)currentAST.root; singleVariable_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1))).add(mods).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t))).add(id_AST)); currentAST.root = singleVariable_AST; currentAST.child = singleVariable_AST!=null &&singleVariable_AST.getFirstChild()!=null ? singleVariable_AST.getFirstChild() : singleVariable_AST; currentAST.advanceChildToEnd(); } returnAST = singleVariable_AST; } /** A declaration with one declarator and optional initialization, like a parameterDeclaration. * Used to parse declarations used for both binding and effect, in places like argument * lists and while statements. */ public final void singleDeclaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST singleDeclaration_AST = null; AST sd_AST = null; singleDeclarationNoInit(); sd_AST = (AST)returnAST; if ( inputState.guessing==0 ) { singleDeclaration_AST = (AST)currentAST.root; singleDeclaration_AST = sd_AST; currentAST.root = singleDeclaration_AST; currentAST.child = singleDeclaration_AST!=null &&singleDeclaration_AST.getFirstChild()!=null ? singleDeclaration_AST.getFirstChild() : singleDeclaration_AST; currentAST.advanceChildToEnd(); } { switch ( LA(1)) { case ASSIGN: { varInitializer(); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case RBRACK: case COMMA: case RPAREN: case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } singleDeclaration_AST = (AST)currentAST.root; returnAST = singleDeclaration_AST; } /** An assignment operator '=' followed by an expression. (Never empty.) */ public final void varInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST varInitializer_AST = null; AST tmp41_AST = null; tmp41_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp41_AST); match(ASSIGN); nls(); expressionStatementNoCheck(); astFactory.addASTChild(currentAST, returnAST); varInitializer_AST = (AST)currentAST.root; returnAST = varInitializer_AST; } /** Used only as a lookahead predicate, before diving in and parsing a declaration. * A declaration can be unambiguously introduced with "def", an annotation or a modifier token like "final". * It may also be introduced by a simple identifier whose first character is an uppercase letter, * as in {String x}. A declaration can also be introduced with a built in type like 'int' or 'void'. * Brackets (array and generic) are allowed, as in {List[] x} or {int[][] y}. * Anything else is parsed as a statement of some sort (expression or command). *

      * (In the absence of explicit method-call parens, we assume a capitalized name is a type name. * Yes, this is a little hacky. Alternatives are to complicate the declaration or command * syntaxes, or to have the parser query the symbol table. Parse-time queries are evil. * And we want both {String x} and {println x}. So we need a syntactic razor-edge to slip * between 'println' and 'String'.) * * *TODO* The declarationStart production needs to be strengthened to recognize * things like {List foo}. * Right now it only knows how to skip square brackets after the type, not * angle brackets. * This probably turns out to be tricky because of >> vs. > >. If so, * just put a TODO comment in. */ public final void declarationStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST declarationStart_AST = null; { int _cnt29=0; _loop29: do { switch ( LA(1)) { case LITERAL_def: { { match(LITERAL_def); nls(); } break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifier(); nls(); break; } case AT: { annotation(); nls(); break; } default: if ((_tokenSet_24.member(LA(1))) && (_tokenSet_33.member(LA(2)))) { { if ((LA(1)==IDENT) && (_tokenSet_34.member(LA(2)))) { upperCaseIdent(); } else if (((LA(1) >= LITERAL_void && LA(1) <= LITERAL_double))) { builtInType(); } else if ((LA(1)==IDENT) && (LA(2)==DOT)) { qualifiedTypeName(); } else { throw new NoViableAltException(LT(1), getFilename()); } } { switch ( LA(1)) { case LT: { typeArguments(); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop28: do { if ((LA(1)==LBRACK)) { AST tmp43_AST = null; tmp43_AST = astFactory.create(LT(1)); match(LBRACK); balancedTokens(); AST tmp44_AST = null; tmp44_AST = astFactory.create(LT(1)); match(RBRACK); } else { break _loop28; } } while (true); } } else { if ( _cnt29>=1 ) { break _loop29; } else {throw new NoViableAltException(LT(1), getFilename());} } } _cnt29++; } while (true); } { switch ( LA(1)) { case IDENT: { AST tmp45_AST = null; tmp45_AST = astFactory.create(LT(1)); match(IDENT); break; } case STRING_LITERAL: { AST tmp46_AST = null; tmp46_AST = astFactory.create(LT(1)); match(STRING_LITERAL); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } returnAST = declarationStart_AST; } public final void modifier() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifier_AST = null; switch ( LA(1)) { case LITERAL_private: { AST tmp47_AST = null; tmp47_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp47_AST); match(LITERAL_private); modifier_AST = (AST)currentAST.root; break; } case LITERAL_public: { AST tmp48_AST = null; tmp48_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp48_AST); match(LITERAL_public); modifier_AST = (AST)currentAST.root; break; } case LITERAL_protected: { AST tmp49_AST = null; tmp49_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp49_AST); match(LITERAL_protected); modifier_AST = (AST)currentAST.root; break; } case LITERAL_static: { AST tmp50_AST = null; tmp50_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp50_AST); match(LITERAL_static); modifier_AST = (AST)currentAST.root; break; } case LITERAL_transient: { AST tmp51_AST = null; tmp51_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp51_AST); match(LITERAL_transient); modifier_AST = (AST)currentAST.root; break; } case FINAL: { AST tmp52_AST = null; tmp52_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp52_AST); match(FINAL); modifier_AST = (AST)currentAST.root; break; } case ABSTRACT: { AST tmp53_AST = null; tmp53_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp53_AST); match(ABSTRACT); modifier_AST = (AST)currentAST.root; break; } case LITERAL_native: { AST tmp54_AST = null; tmp54_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp54_AST); match(LITERAL_native); modifier_AST = (AST)currentAST.root; break; } case LITERAL_threadsafe: { AST tmp55_AST = null; tmp55_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp55_AST); match(LITERAL_threadsafe); modifier_AST = (AST)currentAST.root; break; } case LITERAL_synchronized: { AST tmp56_AST = null; tmp56_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp56_AST); match(LITERAL_synchronized); modifier_AST = (AST)currentAST.root; break; } case LITERAL_volatile: { AST tmp57_AST = null; tmp57_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp57_AST); match(LITERAL_volatile); modifier_AST = (AST)currentAST.root; break; } case STRICTFP: { AST tmp58_AST = null; tmp58_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp58_AST); match(STRICTFP); modifier_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = modifier_AST; } public final void annotation() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotation_AST = null; AST i_AST = null; AST args_AST = null; Token first = LT(1); match(AT); identifier(); i_AST = (AST)returnAST; nls(); { if ((LA(1)==LPAREN) && (_tokenSet_35.member(LA(2)))) { match(LPAREN); { switch ( LA(1)) { case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { annotationArguments(); args_AST = (AST)returnAST; break; } case RPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RPAREN); } else if ((_tokenSet_36.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { annotation_AST = (AST)currentAST.root; annotation_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(ANNOTATION,"ANNOTATION",first,LT(1))).add(i_AST).add(args_AST)); currentAST.root = annotation_AST; currentAST.child = annotation_AST!=null &&annotation_AST.getFirstChild()!=null ? annotation_AST.getFirstChild() : annotation_AST; currentAST.advanceChildToEnd(); } returnAST = annotation_AST; } /** An IDENT token whose spelling is required to start with an uppercase letter. * In the case of a simple statement {UpperID name} the identifier is taken to be a type name, not a command name. */ public final void upperCaseIdent() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST upperCaseIdent_AST = null; if (!(isUpperCase(LT(1)))) throw new SemanticException("isUpperCase(LT(1))"); AST tmp62_AST = null; tmp62_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp62_AST); match(IDENT); upperCaseIdent_AST = (AST)currentAST.root; returnAST = upperCaseIdent_AST; } public final void builtInType() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInType_AST = null; switch ( LA(1)) { case LITERAL_void: { AST tmp63_AST = null; tmp63_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp63_AST); match(LITERAL_void); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_boolean: { AST tmp64_AST = null; tmp64_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp64_AST); match(LITERAL_boolean); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_byte: { AST tmp65_AST = null; tmp65_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp65_AST); match(LITERAL_byte); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_char: { AST tmp66_AST = null; tmp66_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp66_AST); match(LITERAL_char); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_short: { AST tmp67_AST = null; tmp67_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp67_AST); match(LITERAL_short); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_int: { AST tmp68_AST = null; tmp68_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp68_AST); match(LITERAL_int); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_float: { AST tmp69_AST = null; tmp69_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp69_AST); match(LITERAL_float); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_long: { AST tmp70_AST = null; tmp70_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp70_AST); match(LITERAL_long); builtInType_AST = (AST)currentAST.root; break; } case LITERAL_double: { AST tmp71_AST = null; tmp71_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp71_AST); match(LITERAL_double); builtInType_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = builtInType_AST; } public final void qualifiedTypeName() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST qualifiedTypeName_AST = null; AST tmp72_AST = null; tmp72_AST = astFactory.create(LT(1)); match(IDENT); AST tmp73_AST = null; tmp73_AST = astFactory.create(LT(1)); match(DOT); { _loop36: do { if ((LA(1)==IDENT) && (LA(2)==DOT)) { AST tmp74_AST = null; tmp74_AST = astFactory.create(LT(1)); match(IDENT); AST tmp75_AST = null; tmp75_AST = astFactory.create(LT(1)); match(DOT); } else { break _loop36; } } while (true); } upperCaseIdent(); returnAST = qualifiedTypeName_AST; } public final void typeArguments() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArguments_AST = null; Token first = LT(1); int currentLtLevel = 0; if ( inputState.guessing==0 ) { currentLtLevel = ltCounter; } match(LT); if ( inputState.guessing==0 ) { ltCounter++; } nls(); typeArgument(); astFactory.addASTChild(currentAST, returnAST); { _loop58: do { if (((LA(1)==COMMA) && (_tokenSet_38.member(LA(2))))&&(inputState.guessing !=0 || ltCounter == currentLtLevel + 1)) { match(COMMA); nls(); typeArgument(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop58; } } while (true); } nls(); { if ((_tokenSet_39.member(LA(1))) && (_tokenSet_40.member(LA(2)))) { typeArgumentsOrParametersEnd(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_40.member(LA(1))) && (_tokenSet_3.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if (!(matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel), "Missing closing bracket '>' for generics types", "Please specify the missing bracket!"))) throw new SemanticException("matchGenericTypeBrackets(((currentLtLevel != 0) || ltCounter == currentLtLevel),\n \"Missing closing bracket '>' for generics types\", \"Please specify the missing bracket!\")"); if ( inputState.guessing==0 ) { typeArguments_AST = (AST)currentAST.root; typeArguments_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_ARGUMENTS,"TYPE_ARGUMENTS",first,LT(1))).add(typeArguments_AST)); currentAST.root = typeArguments_AST; currentAST.child = typeArguments_AST!=null &&typeArguments_AST.getFirstChild()!=null ? typeArguments_AST.getFirstChild() : typeArguments_AST; currentAST.advanceChildToEnd(); } typeArguments_AST = (AST)currentAST.root; returnAST = typeArguments_AST; } public final void balancedTokens() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST balancedTokens_AST = null; { _loop563: do { if ((_tokenSet_41.member(LA(1)))) { balancedBrackets(); } else if ((_tokenSet_42.member(LA(1)))) { { match(_tokenSet_42); } } else { break _loop563; } } while (true); } returnAST = balancedTokens_AST; } /** * lookahead predicate for usage of generics in methods * as parameter for the method. Example: * static T foo(){} * must be first after the modifier. * This rule allows more and does no exact match, but it * is only a lookahead, not the real rule. */ public final void genericMethodStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST genericMethodStart_AST = null; { int _cnt33=0; _loop33: do { switch ( LA(1)) { case LITERAL_def: { match(LITERAL_def); nls(); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifier(); nls(); break; } case AT: { annotation(); nls(); break; } default: { if ( _cnt33>=1 ) { break _loop33; } else {throw new NoViableAltException(LT(1), getFilename());} } } _cnt33++; } while (true); } AST tmp80_AST = null; tmp80_AST = astFactory.create(LT(1)); match(LT); returnAST = genericMethodStart_AST; } /** Used to look ahead for a constructor */ public final void constructorStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constructorStart_AST = null; Token id = null; AST id_AST = null; modifiersOpt(); id = LT(1); id_AST = astFactory.create(id); match(IDENT); if (!(isConstructorIdent(id))) throw new SemanticException("isConstructorIdent(id)"); nls(); match(LPAREN); returnAST = constructorStart_AST; } /** A list of zero or more modifiers, annotations, or "def". */ public final void modifiersOpt() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifiersOpt_AST = null; Token first = LT(1); { if ((_tokenSet_12.member(LA(1))) && (_tokenSet_43.member(LA(2)))) { modifiersInternal(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_44.member(LA(1))) && (_tokenSet_45.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { modifiersOpt_AST = (AST)currentAST.root; modifiersOpt_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))).add(modifiersOpt_AST)); currentAST.root = modifiersOpt_AST; currentAST.child = modifiersOpt_AST!=null &&modifiersOpt_AST.getFirstChild()!=null ? modifiersOpt_AST.getFirstChild() : modifiersOpt_AST; currentAST.advanceChildToEnd(); } modifiersOpt_AST = (AST)currentAST.root; returnAST = modifiersOpt_AST; } /** Used only as a lookahead predicate for nested type declarations. */ public final void typeDeclarationStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeDeclarationStart_AST = null; modifiersOpt(); { switch ( LA(1)) { case LITERAL_class: { match(LITERAL_class); break; } case LITERAL_interface: { match(LITERAL_interface); break; } case LITERAL_enum: { match(LITERAL_enum); break; } case AT: { AST tmp85_AST = null; tmp85_AST = astFactory.create(LT(1)); match(AT); match(LITERAL_interface); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } returnAST = typeDeclarationStart_AST; } public final void classTypeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classTypeSpec_AST = null; AST ct_AST = null; Token first = LT(1); classOrInterfaceType(false); ct_AST = (AST)returnAST; declaratorBrackets(ct_AST); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { classTypeSpec_AST = (AST)currentAST.root; if ( addImagNode ) { classTypeSpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(classTypeSpec_AST)); } currentAST.root = classTypeSpec_AST; currentAST.child = classTypeSpec_AST!=null &&classTypeSpec_AST.getFirstChild()!=null ? classTypeSpec_AST.getFirstChild() : classTypeSpec_AST; currentAST.advanceChildToEnd(); } classTypeSpec_AST = (AST)currentAST.root; returnAST = classTypeSpec_AST; } public final void builtInTypeSpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInTypeSpec_AST = null; AST bt_AST = null; Token first = LT(1); builtInType(); bt_AST = (AST)returnAST; declaratorBrackets(bt_AST); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { builtInTypeSpec_AST = (AST)currentAST.root; if ( addImagNode ) { builtInTypeSpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(builtInTypeSpec_AST)); } currentAST.root = builtInTypeSpec_AST; currentAST.child = builtInTypeSpec_AST!=null &&builtInTypeSpec_AST.getFirstChild()!=null ? builtInTypeSpec_AST.getFirstChild() : builtInTypeSpec_AST; currentAST.advanceChildToEnd(); } builtInTypeSpec_AST = (AST)currentAST.root; returnAST = builtInTypeSpec_AST; } public final void classOrInterfaceType( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classOrInterfaceType_AST = null; Token i1 = null; AST i1_AST = null; Token d = null; AST d_AST = null; Token i2 = null; AST i2_AST = null; AST ta_AST = null; Token first = LT(1); i1 = LT(1); i1_AST = astFactory.create(i1); astFactory.makeASTRoot(currentAST, i1_AST); match(IDENT); { if ((LA(1)==LT) && (_tokenSet_38.member(LA(2)))) { typeArguments(); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==LT) && (LA(2)==GT)) { typeArgumentsDiamond(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_40.member(LA(1)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { _loop47: do { if ((LA(1)==DOT) && (LA(2)==IDENT)) { d = LT(1); d_AST = astFactory.create(d); match(DOT); i2 = LT(1); i2_AST = astFactory.create(i2); match(IDENT); { switch ( LA(1)) { case LT: { typeArguments(); ta_AST = (AST)returnAST; break; } case EOF: case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case RBRACK: case IDENT: case STRING_LITERAL: case DOT: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case QUESTION: case LITERAL_extends: case LITERAL_super: case GT: case COMMA: case SR: case BSR: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case RPAREN: case ASSIGN: case BAND: case LCURLY: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case TRIPLE_DOT: case CLOSABLE_BLOCK_OP: case COLON: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case STAR_STAR_ASSIGN: case ELVIS_OPERATOR: case LOR: case LAND: case BOR: case BXOR: case REGEX_FIND: case REGEX_MATCH: case NOT_EQUAL: case EQUAL: case IDENTICAL: case NOT_IDENTICAL: case COMPARE_TO: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { i1_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(DOT,".",first,LT(1))).add(i1_AST).add(i2_AST).add(ta_AST)); } } else { break _loop47; } } while (true); } if ( inputState.guessing==0 ) { classOrInterfaceType_AST = (AST)currentAST.root; classOrInterfaceType_AST = i1_AST; if ( addImagNode ) { classOrInterfaceType_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(classOrInterfaceType_AST)); } currentAST.root = classOrInterfaceType_AST; currentAST.child = classOrInterfaceType_AST!=null &&classOrInterfaceType_AST.getFirstChild()!=null ? classOrInterfaceType_AST.getFirstChild() : classOrInterfaceType_AST; currentAST.advanceChildToEnd(); } classOrInterfaceType_AST = (AST)currentAST.root; returnAST = classOrInterfaceType_AST; } /** After some type names, where zero or more empty bracket pairs are allowed. * We use ARRAY_DECLARATOR to represent this. * TODO: Is there some more Groovy way to view this in terms of the indexed property syntax? */ public final void declaratorBrackets( AST typ ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST declaratorBrackets_AST = null; if ( inputState.guessing==0 ) { declaratorBrackets_AST = (AST)currentAST.root; declaratorBrackets_AST=typ; currentAST.root = declaratorBrackets_AST; currentAST.child = declaratorBrackets_AST!=null &&declaratorBrackets_AST.getFirstChild()!=null ? declaratorBrackets_AST.getFirstChild() : declaratorBrackets_AST; currentAST.advanceChildToEnd(); } { _loop248: do { if ((LA(1)==LBRACK) && (LA(2)==RBRACK)) { match(LBRACK); match(RBRACK); if ( inputState.guessing==0 ) { declaratorBrackets_AST = (AST)currentAST.root; declaratorBrackets_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(ARRAY_DECLARATOR,"[",typ,LT(1))).add(declaratorBrackets_AST)); currentAST.root = declaratorBrackets_AST; currentAST.child = declaratorBrackets_AST!=null &&declaratorBrackets_AST.getFirstChild()!=null ? declaratorBrackets_AST.getFirstChild() : declaratorBrackets_AST; currentAST.advanceChildToEnd(); } } else { break _loop248; } } while (true); } declaratorBrackets_AST = (AST)currentAST.root; returnAST = declaratorBrackets_AST; } public final void typeArgumentsDiamond() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentsDiamond_AST = null; Token first = LT(1); match(LT); match(GT); nls(); typeArgumentsDiamond_AST = (AST)currentAST.root; returnAST = typeArgumentsDiamond_AST; } public final void typeArgumentSpec() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentSpec_AST = null; switch ( LA(1)) { case IDENT: { classTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); typeArgumentSpec_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInTypeArraySpec(true); astFactory.addASTChild(currentAST, returnAST); typeArgumentSpec_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeArgumentSpec_AST; } public final void builtInTypeArraySpec( boolean addImagNode ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST builtInTypeArraySpec_AST = null; AST bt_AST = null; Token first = LT(1); builtInType(); bt_AST = (AST)returnAST; { boolean synPredMatched66 = false; if (((_tokenSet_40.member(LA(1))) && (_tokenSet_3.member(LA(2))))) { int _m66 = mark(); synPredMatched66 = true; inputState.guessing++; try { { match(LBRACK); } } catch (RecognitionException pe) { synPredMatched66 = false; } rewind(_m66); inputState.guessing--; } if ( synPredMatched66 ) { declaratorBrackets(bt_AST); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_40.member(LA(1))) && (_tokenSet_3.member(LA(2)))) { if ( inputState.guessing==0 ) { require(false, "primitive type parameters not allowed here", "use the corresponding wrapper type, such as Integer for int" ); } } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { builtInTypeArraySpec_AST = (AST)currentAST.root; if ( addImagNode ) { builtInTypeArraySpec_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(builtInTypeArraySpec_AST)); } currentAST.root = builtInTypeArraySpec_AST; currentAST.child = builtInTypeArraySpec_AST!=null &&builtInTypeArraySpec_AST.getFirstChild()!=null ? builtInTypeArraySpec_AST.getFirstChild() : builtInTypeArraySpec_AST; currentAST.advanceChildToEnd(); } builtInTypeArraySpec_AST = (AST)currentAST.root; returnAST = builtInTypeArraySpec_AST; } public final void typeArgument() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgument_AST = null; Token first = LT(1); { switch ( LA(1)) { case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeArgumentSpec(); astFactory.addASTChild(currentAST, returnAST); break; } case QUESTION: { wildcardType(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { typeArgument_AST = (AST)currentAST.root; typeArgument_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_ARGUMENT,"TYPE_ARGUMENT",first,LT(1))).add(typeArgument_AST)); currentAST.root = typeArgument_AST; currentAST.child = typeArgument_AST!=null &&typeArgument_AST.getFirstChild()!=null ? typeArgument_AST.getFirstChild() : typeArgument_AST; currentAST.advanceChildToEnd(); } typeArgument_AST = (AST)currentAST.root; returnAST = typeArgument_AST; } public final void wildcardType() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST wildcardType_AST = null; AST tmp91_AST = null; tmp91_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp91_AST); match(QUESTION); { boolean synPredMatched54 = false; if (((LA(1)==LITERAL_extends||LA(1)==LITERAL_super) && (LA(2)==IDENT||LA(2)==NLS))) { int _m54 = mark(); synPredMatched54 = true; inputState.guessing++; try { { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); break; } case LITERAL_super: { match(LITERAL_super); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException pe) { synPredMatched54 = false; } rewind(_m54); inputState.guessing--; } if ( synPredMatched54 ) { typeArgumentBounds(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_40.member(LA(1))) && (_tokenSet_3.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { wildcardType_AST = (AST)currentAST.root; wildcardType_AST.setType(WILDCARD_TYPE); } wildcardType_AST = (AST)currentAST.root; returnAST = wildcardType_AST; } public final void typeArgumentBounds() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentBounds_AST = null; Token first = LT(1);boolean isUpperBounds = false; { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); if ( inputState.guessing==0 ) { isUpperBounds=true; } break; } case LITERAL_super: { match(LITERAL_super); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); nls(); if ( inputState.guessing==0 ) { typeArgumentBounds_AST = (AST)currentAST.root; if (isUpperBounds) { typeArgumentBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1))).add(typeArgumentBounds_AST)); } else { typeArgumentBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_LOWER_BOUNDS,"TYPE_LOWER_BOUNDS",first,LT(1))).add(typeArgumentBounds_AST)); } currentAST.root = typeArgumentBounds_AST; currentAST.child = typeArgumentBounds_AST!=null &&typeArgumentBounds_AST.getFirstChild()!=null ? typeArgumentBounds_AST.getFirstChild() : typeArgumentBounds_AST; currentAST.advanceChildToEnd(); } typeArgumentBounds_AST = (AST)currentAST.root; returnAST = typeArgumentBounds_AST; } protected final void typeArgumentsOrParametersEnd() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeArgumentsOrParametersEnd_AST = null; switch ( LA(1)) { case GT: { match(GT); if ( inputState.guessing==0 ) { ltCounter-=1; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } case SR: { match(SR); if ( inputState.guessing==0 ) { ltCounter-=2; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } case BSR: { match(BSR); if ( inputState.guessing==0 ) { ltCounter-=3; } typeArgumentsOrParametersEnd_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = typeArgumentsOrParametersEnd_AST; } public final void type() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST type_AST = null; switch ( LA(1)) { case IDENT: { classOrInterfaceType(false); astFactory.addASTChild(currentAST, returnAST); type_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInType(); astFactory.addASTChild(currentAST, returnAST); type_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = type_AST; } public final void modifiersInternal() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST modifiersInternal_AST = null; int seenDef = 0; { int _cnt79=0; _loop79: do { if (((LA(1)==LITERAL_def))&&(seenDef++ == 0)) { match(LITERAL_def); nls(); } else if ((_tokenSet_46.member(LA(1)))) { modifier(); astFactory.addASTChild(currentAST, returnAST); nls(); } else if ((LA(1)==AT) && (LA(2)==LITERAL_interface)) { if ( inputState.guessing==0 ) { break; /* go out of the ()+ loop*/ } AST tmp98_AST = null; tmp98_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp98_AST); match(AT); AST tmp99_AST = null; tmp99_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp99_AST); match(LITERAL_interface); } else if ((LA(1)==AT) && (LA(2)==IDENT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); nls(); } else { if ( _cnt79>=1 ) { break _loop79; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt79++; } while (true); } modifiersInternal_AST = (AST)currentAST.root; returnAST = modifiersInternal_AST; } public final void annotationArguments() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationArguments_AST = null; AST v_AST = null; if ((_tokenSet_47.member(LA(1))) && (_tokenSet_48.member(LA(2)))) { annotationMemberValueInitializer(); v_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { annotationArguments_AST = (AST)currentAST.root; Token itkn = new Token(IDENT, "value"); AST i; i = (AST)astFactory.make( (new ASTArray(1)).add(create(IDENT,"value",itkn,itkn))); annotationArguments_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",LT(1),LT(1))).add(i).add(v_AST)); currentAST.root = annotationArguments_AST; currentAST.child = annotationArguments_AST!=null &&annotationArguments_AST.getFirstChild()!=null ? annotationArguments_AST.getFirstChild() : annotationArguments_AST; currentAST.advanceChildToEnd(); } annotationArguments_AST = (AST)currentAST.root; } else if ((_tokenSet_49.member(LA(1))) && (LA(2)==ASSIGN)) { annotationMemberValuePairs(); astFactory.addASTChild(currentAST, returnAST); annotationArguments_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = annotationArguments_AST; } public final void annotationsInternal() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationsInternal_AST = null; { _loop89: do { if ((LA(1)==AT) && (LA(2)==LITERAL_interface)) { if ( inputState.guessing==0 ) { break; /* go out of the ()* loop*/ } AST tmp100_AST = null; tmp100_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp100_AST); match(AT); AST tmp101_AST = null; tmp101_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp101_AST); match(LITERAL_interface); } else if ((LA(1)==AT) && (LA(2)==IDENT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); nls(); } else { break _loop89; } } while (true); } annotationsInternal_AST = (AST)currentAST.root; returnAST = annotationsInternal_AST; } public final void annotationMemberValueInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberValueInitializer_AST = null; switch ( LA(1)) { case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { conditionalExpression(0); astFactory.addASTChild(currentAST, returnAST); annotationMemberValueInitializer_AST = (AST)currentAST.root; break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); annotationMemberValueInitializer_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = annotationMemberValueInitializer_AST; } public final void annotationMemberValuePairs() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberValuePairs_AST = null; annotationMemberValuePair(); astFactory.addASTChild(currentAST, returnAST); { _loop95: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); annotationMemberValuePair(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop95; } } while (true); } annotationMemberValuePairs_AST = (AST)currentAST.root; returnAST = annotationMemberValuePairs_AST; } public final void annotationMemberValuePair() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberValuePair_AST = null; AST i_AST = null; AST v_AST = null; Token first = LT(1); annotationIdent(); i_AST = (AST)returnAST; match(ASSIGN); nls(); annotationMemberValueInitializer(); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationMemberValuePair_AST = (AST)currentAST.root; annotationMemberValuePair_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR",first,LT(1))).add(i_AST).add(v_AST)); currentAST.root = annotationMemberValuePair_AST; currentAST.child = annotationMemberValuePair_AST!=null &&annotationMemberValuePair_AST.getFirstChild()!=null ? annotationMemberValuePair_AST.getFirstChild() : annotationMemberValuePair_AST; currentAST.advanceChildToEnd(); } returnAST = annotationMemberValuePair_AST; } public final void annotationIdent() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationIdent_AST = null; switch ( LA(1)) { case IDENT: { AST tmp104_AST = null; tmp104_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp104_AST); match(IDENT); annotationIdent_AST = (AST)currentAST.root; break; } case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: { keywordPropertyNames(); astFactory.addASTChild(currentAST, returnAST); annotationIdent_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = annotationIdent_AST; } public final void keywordPropertyNames() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST keywordPropertyNames_AST = null; { switch ( LA(1)) { case LITERAL_as: { AST tmp105_AST = null; tmp105_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp105_AST); match(LITERAL_as); break; } case LITERAL_assert: { AST tmp106_AST = null; tmp106_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp106_AST); match(LITERAL_assert); break; } case LITERAL_break: { AST tmp107_AST = null; tmp107_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp107_AST); match(LITERAL_break); break; } case LITERAL_case: { AST tmp108_AST = null; tmp108_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp108_AST); match(LITERAL_case); break; } case LITERAL_catch: { AST tmp109_AST = null; tmp109_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp109_AST); match(LITERAL_catch); break; } case LITERAL_class: { AST tmp110_AST = null; tmp110_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp110_AST); match(LITERAL_class); break; } case UNUSED_CONST: { AST tmp111_AST = null; tmp111_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp111_AST); match(UNUSED_CONST); break; } case LITERAL_continue: { AST tmp112_AST = null; tmp112_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp112_AST); match(LITERAL_continue); break; } case LITERAL_def: { AST tmp113_AST = null; tmp113_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp113_AST); match(LITERAL_def); break; } case LITERAL_default: { AST tmp114_AST = null; tmp114_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp114_AST); match(LITERAL_default); break; } case UNUSED_DO: { AST tmp115_AST = null; tmp115_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp115_AST); match(UNUSED_DO); break; } case LITERAL_else: { AST tmp116_AST = null; tmp116_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp116_AST); match(LITERAL_else); break; } case LITERAL_enum: { AST tmp117_AST = null; tmp117_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp117_AST); match(LITERAL_enum); break; } case LITERAL_extends: { AST tmp118_AST = null; tmp118_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp118_AST); match(LITERAL_extends); break; } case LITERAL_false: { AST tmp119_AST = null; tmp119_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp119_AST); match(LITERAL_false); break; } case LITERAL_finally: { AST tmp120_AST = null; tmp120_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp120_AST); match(LITERAL_finally); break; } case LITERAL_for: { AST tmp121_AST = null; tmp121_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp121_AST); match(LITERAL_for); break; } case UNUSED_GOTO: { AST tmp122_AST = null; tmp122_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp122_AST); match(UNUSED_GOTO); break; } case LITERAL_if: { AST tmp123_AST = null; tmp123_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp123_AST); match(LITERAL_if); break; } case LITERAL_implements: { AST tmp124_AST = null; tmp124_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp124_AST); match(LITERAL_implements); break; } case LITERAL_import: { AST tmp125_AST = null; tmp125_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp125_AST); match(LITERAL_import); break; } case LITERAL_in: { AST tmp126_AST = null; tmp126_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp126_AST); match(LITERAL_in); break; } case LITERAL_instanceof: { AST tmp127_AST = null; tmp127_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp127_AST); match(LITERAL_instanceof); break; } case LITERAL_interface: { AST tmp128_AST = null; tmp128_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp128_AST); match(LITERAL_interface); break; } case LITERAL_new: { AST tmp129_AST = null; tmp129_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp129_AST); match(LITERAL_new); break; } case LITERAL_null: { AST tmp130_AST = null; tmp130_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp130_AST); match(LITERAL_null); break; } case LITERAL_package: { AST tmp131_AST = null; tmp131_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp131_AST); match(LITERAL_package); break; } case LITERAL_return: { AST tmp132_AST = null; tmp132_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp132_AST); match(LITERAL_return); break; } case LITERAL_super: { AST tmp133_AST = null; tmp133_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp133_AST); match(LITERAL_super); break; } case LITERAL_switch: { AST tmp134_AST = null; tmp134_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp134_AST); match(LITERAL_switch); break; } case LITERAL_this: { AST tmp135_AST = null; tmp135_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp135_AST); match(LITERAL_this); break; } case LITERAL_throw: { AST tmp136_AST = null; tmp136_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp136_AST); match(LITERAL_throw); break; } case LITERAL_throws: { AST tmp137_AST = null; tmp137_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp137_AST); match(LITERAL_throws); break; } case LITERAL_true: { AST tmp138_AST = null; tmp138_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp138_AST); match(LITERAL_true); break; } case LITERAL_try: { AST tmp139_AST = null; tmp139_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp139_AST); match(LITERAL_try); break; } case LITERAL_while: { AST tmp140_AST = null; tmp140_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp140_AST); match(LITERAL_while); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifier(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInType(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { keywordPropertyNames_AST = (AST)currentAST.root; keywordPropertyNames_AST.setType(IDENT); } keywordPropertyNames_AST = (AST)currentAST.root; returnAST = keywordPropertyNames_AST; } public final void conditionalExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST conditionalExpression_AST = null; logicalOrExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case ELVIS_OPERATOR: { AST tmp141_AST = null; tmp141_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp141_AST); match(ELVIS_OPERATOR); nls(); conditionalExpression(0); astFactory.addASTChild(currentAST, returnAST); break; } case QUESTION: { AST tmp142_AST = null; tmp142_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp142_AST); match(QUESTION); nls(); assignmentExpression(0); astFactory.addASTChild(currentAST, returnAST); nls(); match(COLON); nls(); conditionalExpression(0); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case RBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case COMMA: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case RPAREN: case ASSIGN: case LCURLY: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case CLOSABLE_BLOCK_OP: case COLON: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case STAR_STAR_ASSIGN: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } conditionalExpression_AST = (AST)currentAST.root; returnAST = conditionalExpression_AST; } public final void annotationMemberArrayValueInitializer() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationMemberArrayValueInitializer_AST = null; switch ( LA(1)) { case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { conditionalExpression(0); astFactory.addASTChild(currentAST, returnAST); annotationMemberArrayValueInitializer_AST = (AST)currentAST.root; break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); nls(); annotationMemberArrayValueInitializer_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = annotationMemberArrayValueInitializer_AST; } public final void superClassClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST superClassClause_AST = null; AST c_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_extends: { match(LITERAL_extends); nls(); classOrInterfaceType(false); c_AST = (AST)returnAST; nls(); break; } case LCURLY: case LITERAL_implements: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { superClassClause_AST = (AST)currentAST.root; superClassClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1))).add(c_AST)); currentAST.root = superClassClause_AST; currentAST.child = superClassClause_AST!=null &&superClassClause_AST.getFirstChild()!=null ? superClassClause_AST.getFirstChild() : superClassClause_AST; currentAST.advanceChildToEnd(); } returnAST = superClassClause_AST; } public final void implementsClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST implementsClause_AST = null; Token i = null; AST i_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_implements: { i = LT(1); i_AST = astFactory.create(i); match(LITERAL_implements); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); { _loop187: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); } else { break _loop187; } } while (true); } nls(); break; } case LCURLY: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { implementsClause_AST = (AST)currentAST.root; implementsClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE",first,LT(1))).add(implementsClause_AST)); currentAST.root = implementsClause_AST; currentAST.child = implementsClause_AST!=null &&implementsClause_AST.getFirstChild()!=null ? implementsClause_AST.getFirstChild() : implementsClause_AST; currentAST.advanceChildToEnd(); } implementsClause_AST = (AST)currentAST.root; returnAST = implementsClause_AST; } public final void classBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classBlock_AST = null; Token first = LT(1); match(LCURLY); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop122: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop122; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { classBlock_AST = (AST)currentAST.root; classBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(OBJBLOCK,"OBJBLOCK",first,LT(1))).add(classBlock_AST)); currentAST.root = classBlock_AST; currentAST.child = classBlock_AST!=null &&classBlock_AST.getFirstChild()!=null ? classBlock_AST.getFirstChild() : classBlock_AST; currentAST.advanceChildToEnd(); } classBlock_AST = (AST)currentAST.root; returnAST = classBlock_AST; } public final void interfaceExtends() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceExtends_AST = null; Token e = null; AST e_AST = null; Token first = LT(1); { switch ( LA(1)) { case LITERAL_extends: { e = LT(1); e_AST = astFactory.create(e); match(LITERAL_extends); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); { _loop183: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); } else { break _loop183; } } while (true); } nls(); break; } case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { interfaceExtends_AST = (AST)currentAST.root; interfaceExtends_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE",first,LT(1))).add(interfaceExtends_AST)); currentAST.root = interfaceExtends_AST; currentAST.child = interfaceExtends_AST!=null &&interfaceExtends_AST.getFirstChild()!=null ? interfaceExtends_AST.getFirstChild() : interfaceExtends_AST; currentAST.advanceChildToEnd(); } interfaceExtends_AST = (AST)currentAST.root; returnAST = interfaceExtends_AST; } public final void interfaceBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceBlock_AST = null; Token first = LT(1); match(LCURLY); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { interfaceField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop127: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { interfaceField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop127; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { interfaceBlock_AST = (AST)currentAST.root; interfaceBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(OBJBLOCK,"OBJBLOCK",first,LT(1))).add(interfaceBlock_AST)); currentAST.root = interfaceBlock_AST; currentAST.child = interfaceBlock_AST!=null &&interfaceBlock_AST.getFirstChild()!=null ? interfaceBlock_AST.getFirstChild() : interfaceBlock_AST; currentAST.advanceChildToEnd(); } interfaceBlock_AST = (AST)currentAST.root; returnAST = interfaceBlock_AST; } public final void enumBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumBlock_AST = null; Token first = LT(1); match(LCURLY); nls(); { boolean synPredMatched136 = false; if (((LA(1)==IDENT||LA(1)==AT) && (_tokenSet_50.member(LA(2))))) { int _m136 = mark(); synPredMatched136 = true; inputState.guessing++; try { { enumConstantsStart(); } } catch (RecognitionException pe) { synPredMatched136 = false; } rewind(_m136); inputState.guessing--; } if ( synPredMatched136 ) { enumConstants(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_51.member(LA(1))) && (_tokenSet_52.member(LA(2)))) { { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { throw new NoViableAltException(LT(1), getFilename()); } } { _loop140: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop140; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { enumBlock_AST = (AST)currentAST.root; enumBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(OBJBLOCK,"OBJBLOCK",first,LT(1))).add(enumBlock_AST)); currentAST.root = enumBlock_AST; currentAST.child = enumBlock_AST!=null &&enumBlock_AST.getFirstChild()!=null ? enumBlock_AST.getFirstChild() : enumBlock_AST; currentAST.advanceChildToEnd(); } enumBlock_AST = (AST)currentAST.root; returnAST = enumBlock_AST; } public final void annotationBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationBlock_AST = null; Token first = LT(1); match(LCURLY); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { annotationField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop132: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { annotationField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop132; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { annotationBlock_AST = (AST)currentAST.root; annotationBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(OBJBLOCK,"OBJBLOCK",first,LT(1))).add(annotationBlock_AST)); currentAST.root = annotationBlock_AST; currentAST.child = annotationBlock_AST!=null &&annotationBlock_AST.getFirstChild()!=null ? annotationBlock_AST.getFirstChild() : annotationBlock_AST; currentAST.advanceChildToEnd(); } annotationBlock_AST = (AST)currentAST.root; returnAST = annotationBlock_AST; } public final void typeParameter() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameter_AST = null; Token id = null; AST id_AST = null; Token first = LT(1); { id = LT(1); id_AST = astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(IDENT); } { if ((LA(1)==LITERAL_extends) && (LA(2)==IDENT||LA(2)==NLS)) { typeParameterBounds(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_53.member(LA(1))) && (_tokenSet_54.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { typeParameter_AST = (AST)currentAST.root; typeParameter_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_PARAMETER,"TYPE_PARAMETER",first,LT(1))).add(typeParameter_AST)); currentAST.root = typeParameter_AST; currentAST.child = typeParameter_AST!=null &&typeParameter_AST.getFirstChild()!=null ? typeParameter_AST.getFirstChild() : typeParameter_AST; currentAST.advanceChildToEnd(); } typeParameter_AST = (AST)currentAST.root; returnAST = typeParameter_AST; } public final void typeParameterBounds() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeParameterBounds_AST = null; Token first = LT(1); match(LITERAL_extends); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); { _loop117: do { if ((LA(1)==BAND)) { match(BAND); nls(); classOrInterfaceType(true); astFactory.addASTChild(currentAST, returnAST); } else { break _loop117; } } while (true); } if ( inputState.guessing==0 ) { typeParameterBounds_AST = (AST)currentAST.root; typeParameterBounds_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(TYPE_UPPER_BOUNDS,"TYPE_UPPER_BOUNDS",first,LT(1))).add(typeParameterBounds_AST)); currentAST.root = typeParameterBounds_AST; currentAST.child = typeParameterBounds_AST!=null &&typeParameterBounds_AST.getFirstChild()!=null ? typeParameterBounds_AST.getFirstChild() : typeParameterBounds_AST; currentAST.advanceChildToEnd(); } typeParameterBounds_AST = (AST)currentAST.root; returnAST = typeParameterBounds_AST; } public final void classField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST classField_AST = null; AST mc_AST = null; AST ctor_AST = null; AST dg_AST = null; AST mad_AST = null; AST dd_AST = null; AST mods_AST = null; AST td_AST = null; AST s3_AST = null; AST s4_AST = null; Token first = LT(1); boolean synPredMatched190 = false; if (((_tokenSet_55.member(LA(1))) && (_tokenSet_56.member(LA(2))))) { int _m190 = mark(); synPredMatched190 = true; inputState.guessing++; try { { constructorStart(); } } catch (RecognitionException pe) { synPredMatched190 = false; } rewind(_m190); inputState.guessing--; } if ( synPredMatched190 ) { modifiersOpt(); mc_AST = (AST)returnAST; constructorDefinition(mc_AST); ctor_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = ctor_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched192 = false; if (((_tokenSet_12.member(LA(1))) && (_tokenSet_13.member(LA(2))))) { int _m192 = mark(); synPredMatched192 = true; inputState.guessing++; try { { genericMethodStart(); } } catch (RecognitionException pe) { synPredMatched192 = false; } rewind(_m192); inputState.guessing--; } if ( synPredMatched192 ) { genericMethod(); dg_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = dg_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched194 = false; if (((_tokenSet_12.member(LA(1))) && (_tokenSet_14.member(LA(2))))) { int _m194 = mark(); synPredMatched194 = true; inputState.guessing++; try { { multipleAssignmentDeclarationStart(); } } catch (RecognitionException pe) { synPredMatched194 = false; } rewind(_m194); inputState.guessing--; } if ( synPredMatched194 ) { multipleAssignmentDeclaration(); mad_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = mad_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched196 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_16.member(LA(2))))) { int _m196 = mark(); synPredMatched196 = true; inputState.guessing++; try { { declarationStart(); } } catch (RecognitionException pe) { synPredMatched196 = false; } rewind(_m196); inputState.guessing--; } if ( synPredMatched196 ) { declaration(); dd_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = dd_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched198 = false; if (((_tokenSet_21.member(LA(1))) && (_tokenSet_22.member(LA(2))))) { int _m198 = mark(); synPredMatched198 = true; inputState.guessing++; try { { typeDeclarationStart(); } } catch (RecognitionException pe) { synPredMatched198 = false; } rewind(_m198); inputState.guessing--; } if ( synPredMatched198 ) { modifiersOpt(); mods_AST = (AST)returnAST; { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = td_AST; currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } } else if ((LA(1)==LITERAL_static) && (LA(2)==LCURLY||LA(2)==NLS)) { match(LITERAL_static); nls(); compoundStatement(); s3_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(STATIC_INIT,"STATIC_INIT",first,LT(1))).add(s3_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==LCURLY)) { compoundStatement(); s4_AST = (AST)returnAST; if ( inputState.guessing==0 ) { classField_AST = (AST)currentAST.root; classField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1))).add(s4_AST)); currentAST.root = classField_AST; currentAST.child = classField_AST!=null &&classField_AST.getFirstChild()!=null ? classField_AST.getFirstChild() : classField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } }}}} returnAST = classField_AST; } public final void interfaceField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST interfaceField_AST = null; AST d_AST = null; AST dg_AST = null; AST mods_AST = null; AST td_AST = null; boolean synPredMatched202 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_16.member(LA(2))))) { int _m202 = mark(); synPredMatched202 = true; inputState.guessing++; try { { declarationStart(); } } catch (RecognitionException pe) { synPredMatched202 = false; } rewind(_m202); inputState.guessing--; } if ( synPredMatched202 ) { declaration(); d_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = d_AST; currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched204 = false; if (((_tokenSet_12.member(LA(1))) && (_tokenSet_13.member(LA(2))))) { int _m204 = mark(); synPredMatched204 = true; inputState.guessing++; try { { genericMethodStart(); } } catch (RecognitionException pe) { synPredMatched204 = false; } rewind(_m204); inputState.guessing--; } if ( synPredMatched204 ) { genericMethod(); dg_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = dg_AST; currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched206 = false; if (((_tokenSet_21.member(LA(1))) && (_tokenSet_22.member(LA(2))))) { int _m206 = mark(); synPredMatched206 = true; inputState.guessing++; try { { typeDeclarationStart(); } } catch (RecognitionException pe) { synPredMatched206 = false; } rewind(_m206); inputState.guessing--; } if ( synPredMatched206 ) { modifiersOpt(); mods_AST = (AST)returnAST; { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { interfaceField_AST = (AST)currentAST.root; interfaceField_AST = td_AST; currentAST.root = interfaceField_AST; currentAST.child = interfaceField_AST!=null &&interfaceField_AST.getFirstChild()!=null ? interfaceField_AST.getFirstChild() : interfaceField_AST; currentAST.advanceChildToEnd(); } } } else { throw new NoViableAltException(LT(1), getFilename()); } }} returnAST = interfaceField_AST; } public final void annotationField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST annotationField_AST = null; AST mods_AST = null; AST td_AST = null; AST t_AST = null; Token i = null; AST i_AST = null; AST amvi_AST = null; AST v_AST = null; Token first = LT(1); modifiersOpt(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = td_AST; currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeSpec(false); t_AST = (AST)returnAST; { boolean synPredMatched160 = false; if (((LA(1)==IDENT) && (LA(2)==LPAREN))) { int _m160 = mark(); synPredMatched160 = true; inputState.guessing++; try { { match(IDENT); match(LPAREN); } } catch (RecognitionException pe) { synPredMatched160 = false; } rewind(_m160); inputState.guessing--; } if ( synPredMatched160 ) { i = LT(1); i_AST = astFactory.create(i); match(IDENT); match(LPAREN); match(RPAREN); { switch ( LA(1)) { case LITERAL_default: { match(LITERAL_default); nls(); annotationMemberValueInitializer(); amvi_AST = (AST)returnAST; break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(ANNOTATION_FIELD_DEF,"ANNOTATION_FIELD_DEF",first,LT(1))).add(mods_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t_AST))).add(i_AST).add(amvi_AST)); currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT||LA(1)==STRING_LITERAL) && (_tokenSet_57.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { annotationField_AST = (AST)currentAST.root; annotationField_AST = v_AST; currentAST.root = annotationField_AST; currentAST.child = annotationField_AST!=null &&annotationField_AST.getFirstChild()!=null ? annotationField_AST.getFirstChild() : annotationField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } returnAST = annotationField_AST; } /** Guard for enumConstants. */ public final void enumConstantsStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstantsStart_AST = null; annotationsOpt(); astFactory.addASTChild(currentAST, returnAST); AST tmp161_AST = null; tmp161_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp161_AST); match(IDENT); { switch ( LA(1)) { case LCURLY: { AST tmp162_AST = null; tmp162_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp162_AST); match(LCURLY); break; } case LPAREN: { AST tmp163_AST = null; tmp163_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp163_AST); match(LPAREN); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case AT: case COMMA: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case RCURLY: case SEMI: case NLS: { nls(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case SEMI: { AST tmp164_AST = null; tmp164_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp164_AST); match(SEMI); break; } case COMMA: { AST tmp165_AST = null; tmp165_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp165_AST); match(COMMA); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { declarationStart(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: { AST tmp166_AST = null; tmp166_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp166_AST); match(RCURLY); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } enumConstantsStart_AST = (AST)currentAST.root; returnAST = enumConstantsStart_AST; } /** Comma-separated list of one or more enum constant definitions. */ public final void enumConstants() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstants_AST = null; enumConstant(); astFactory.addASTChild(currentAST, returnAST); { _loop155: do { boolean synPredMatched148 = false; if (((_tokenSet_58.member(LA(1))) && (_tokenSet_59.member(LA(2))))) { int _m148 = mark(); synPredMatched148 = true; inputState.guessing++; try { { nls(); { switch ( LA(1)) { case RCURLY: { match(RCURLY); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } } catch (RecognitionException pe) { synPredMatched148 = false; } rewind(_m148); inputState.guessing--; } if ( synPredMatched148 ) { if ( inputState.guessing==0 ) { break; /* leave ()* loop */ } } else if ((LA(1)==COMMA||LA(1)==NLS) && (_tokenSet_60.member(LA(2)))) { nls(); match(COMMA); { boolean synPredMatched152 = false; if (((_tokenSet_58.member(LA(1))) && (_tokenSet_59.member(LA(2))))) { int _m152 = mark(); synPredMatched152 = true; inputState.guessing++; try { { nls(); { switch ( LA(1)) { case RCURLY: { match(RCURLY); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { classField(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } } catch (RecognitionException pe) { synPredMatched152 = false; } rewind(_m152); inputState.guessing--; } if ( synPredMatched152 ) { if ( inputState.guessing==0 ) { break; /* leave ()* loop */ } } else { boolean synPredMatched154 = false; if (((_tokenSet_61.member(LA(1))) && (_tokenSet_62.member(LA(2))))) { int _m154 = mark(); synPredMatched154 = true; inputState.guessing++; try { { nls(); annotationsOpt(); match(IDENT); } } catch (RecognitionException pe) { synPredMatched154 = false; } rewind(_m154); inputState.guessing--; } if ( synPredMatched154 ) { nls(); enumConstant(); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop155; } } while (true); } enumConstants_AST = (AST)currentAST.root; returnAST = enumConstants_AST; } public final void enumConstant() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstant_AST = null; AST an_AST = null; Token i = null; AST i_AST = null; AST a_AST = null; AST b_AST = null; Token first = LT(1); annotationsOpt(); an_AST = (AST)returnAST; i = LT(1); i_AST = astFactory.create(i); match(IDENT); { switch ( LA(1)) { case LPAREN: { match(LPAREN); argList(); a_AST = (AST)returnAST; match(RPAREN); break; } case COMMA: case LCURLY: case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LCURLY: { enumConstantBlock(); b_AST = (AST)returnAST; break; } case COMMA: case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { enumConstant_AST = (AST)currentAST.root; enumConstant_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(ENUM_CONSTANT_DEF,"ENUM_CONSTANT_DEF",first,LT(1))).add(an_AST).add(i_AST).add(a_AST).add(b_AST)); currentAST.root = enumConstant_AST; currentAST.child = enumConstant_AST!=null &&enumConstant_AST.getFirstChild()!=null ? enumConstant_AST.getFirstChild() : enumConstant_AST; currentAST.advanceChildToEnd(); } returnAST = enumConstant_AST; } public final void argList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST argList_AST = null; Token first = LT(1); Token lastComma = null; int hls=0, hls2=0; boolean hasClosureList=false; boolean trailingComma=false; boolean sce=false; { switch ( LA(1)) { case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case STAR: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { hls=argument(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case SEMI: { { { int _cnt531=0; _loop531: do { if ((LA(1)==SEMI)) { match(SEMI); if ( inputState.guessing==0 ) { hasClosureList=true; } { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { sce=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); break; } case RBRACK: case RPAREN: case SEMI: { if ( inputState.guessing==0 ) { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { if ( _cnt531>=1 ) { break _loop531; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt531++; } while (true); } if ( inputState.guessing==0 ) { argList_AST = (AST)currentAST.root; argList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1))).add(argList_AST)); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } } break; } case RBRACK: case COMMA: case RPAREN: { { { _loop537: do { if ((LA(1)==COMMA)) { if ( inputState.guessing==0 ) { lastComma = LT(1); } match(COMMA); { switch ( LA(1)) { case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case STAR: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { { hls2=argument(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { hls |= hls2; } } break; } case RBRACK: case COMMA: case RPAREN: { { if ( inputState.guessing==0 ) { if (trailingComma) throw new NoViableAltException(lastComma, getFilename()); trailingComma=true; } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop537; } } while (true); } if ( inputState.guessing==0 ) { argList_AST = (AST)currentAST.root; argList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(ELIST,"ELIST",first,LT(1))).add(argList_AST)); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case RBRACK: case RPAREN: { { if ( inputState.guessing==0 ) { argList_AST = (AST)currentAST.root; argList_AST = create(ELIST,"ELIST",first,LT(1)); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { argListHasLabels = (hls&1)!=0; } argList_AST = (AST)currentAST.root; returnAST = argList_AST; } public final void enumConstantBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstantBlock_AST = null; Token first = LT(1); match(LCURLY); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { enumConstantField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { _loop169: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: { enumConstantField(); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop169; } } while (true); } match(RCURLY); if ( inputState.guessing==0 ) { enumConstantBlock_AST = (AST)currentAST.root; enumConstantBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(OBJBLOCK,"OBJBLOCK",first,LT(1))).add(enumConstantBlock_AST)); currentAST.root = enumConstantBlock_AST; currentAST.child = enumConstantBlock_AST!=null &&enumConstantBlock_AST.getFirstChild()!=null ? enumConstantBlock_AST.getFirstChild() : enumConstantBlock_AST; currentAST.advanceChildToEnd(); } enumConstantBlock_AST = (AST)currentAST.root; returnAST = enumConstantBlock_AST; } public final void enumConstantField() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST enumConstantField_AST = null; AST mods_AST = null; AST td_AST = null; AST tp_AST = null; AST t_AST = null; AST param_AST = null; AST tc_AST = null; AST s2_AST = null; AST v_AST = null; AST s4_AST = null; Token first = LT(1); switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case IDENT: case LT: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifiersOpt(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: { typeDefinitionInternal(mods_AST); td_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = td_AST; currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } break; } case IDENT: case LT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { { switch ( LA(1)) { case LT: { typeParameters(); tp_AST = (AST)returnAST; break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } typeSpec(false); t_AST = (AST)returnAST; { boolean synPredMatched175 = false; if (((LA(1)==IDENT) && (LA(2)==LPAREN))) { int _m175 = mark(); synPredMatched175 = true; inputState.guessing++; try { { match(IDENT); match(LPAREN); } } catch (RecognitionException pe) { synPredMatched175 = false; } rewind(_m175); inputState.guessing--; } if ( synPredMatched175 ) { AST tmp174_AST = null; tmp174_AST = astFactory.create(LT(1)); match(IDENT); match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); { boolean synPredMatched178 = false; if (((LA(1)==LITERAL_throws||LA(1)==NLS) && (_tokenSet_28.member(LA(2))))) { int _m178 = mark(); synPredMatched178 = true; inputState.guessing++; try { { nls(); match(LITERAL_throws); } } catch (RecognitionException pe) { synPredMatched178 = false; } rewind(_m178); inputState.guessing--; } if ( synPredMatched178 ) { throwsClause(); tc_AST = (AST)returnAST; } else if ((_tokenSet_63.member(LA(1))) && (_tokenSet_64.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { switch ( LA(1)) { case LCURLY: { compoundStatement(); s2_AST = (AST)returnAST; break; } case RCURLY: case SEMI: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = (AST)astFactory.make( (new ASTArray(8)).add(create(METHOD_DEF,"METHOD_DEF",first,LT(1))).add(mods_AST).add(tp_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t_AST))).add(tmp174_AST).add(param_AST).add(tc_AST).add(s2_AST)); currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } } else if ((LA(1)==IDENT||LA(1)==STRING_LITERAL) && (_tokenSet_57.member(LA(2)))) { variableDefinitions(mods_AST,t_AST); v_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = v_AST; currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } } else { throw new NoViableAltException(LT(1), getFilename()); } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LCURLY: { compoundStatement(); s4_AST = (AST)returnAST; if ( inputState.guessing==0 ) { enumConstantField_AST = (AST)currentAST.root; enumConstantField_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(INSTANCE_INIT,"INSTANCE_INIT",first,LT(1))).add(s4_AST)); currentAST.root = enumConstantField_AST; currentAST.child = enumConstantField_AST!=null &&enumConstantField_AST.getFirstChild()!=null ? enumConstantField_AST.getFirstChild() : enumConstantField_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = enumConstantField_AST; } /** A list of zero or more formal parameters. * If a parameter is variable length (e.g. String... myArg) it should be * to the right of any other parameters of the same kind. * General form: (req, ..., opt, ..., [rest], key, ..., [restKeys], [block] * This must be sorted out after parsing, since the various declaration forms * are impossible to tell apart without backtracking. */ public final void parameterDeclarationList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterDeclarationList_AST = null; Token first = LT(1); { switch ( LA(1)) { case FINAL: case LITERAL_def: case IDENT: case AT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case TRIPLE_DOT: { parameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); { _loop256: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); parameterDeclaration(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop256; } } while (true); } break; } case RPAREN: case CLOSABLE_BLOCK_OP: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { parameterDeclarationList_AST = (AST)currentAST.root; parameterDeclarationList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(PARAMETERS,"PARAMETERS",first,LT(1))).add(parameterDeclarationList_AST)); currentAST.root = parameterDeclarationList_AST; currentAST.child = parameterDeclarationList_AST!=null &¶meterDeclarationList_AST.getFirstChild()!=null ? parameterDeclarationList_AST.getFirstChild() : parameterDeclarationList_AST; currentAST.advanceChildToEnd(); } parameterDeclarationList_AST = (AST)currentAST.root; returnAST = parameterDeclarationList_AST; } public final void throwsClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST throwsClause_AST = null; nls(); AST tmp178_AST = null; tmp178_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp178_AST); match(LITERAL_throws); nls(); identifier(); astFactory.addASTChild(currentAST, returnAST); { _loop252: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); identifier(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop252; } } while (true); } throwsClause_AST = (AST)currentAST.root; returnAST = throwsClause_AST; } public final void compoundStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST compoundStatement_AST = null; openBlock(); astFactory.addASTChild(currentAST, returnAST); compoundStatement_AST = (AST)currentAST.root; returnAST = compoundStatement_AST; } /** I've split out constructors separately; we could maybe integrate back into variableDefinitions * later on if we maybe simplified 'def' to be a type declaration? */ public final void constructorDefinition( AST mods ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constructorDefinition_AST = null; Token id = null; AST id_AST = null; AST param_AST = null; AST tc_AST = null; AST cb_AST = null; Token first = cloneToken(LT(1)); if (mods != null) { first.setLine(mods.getLine()); first.setColumn(mods.getColumn()); } id = LT(1); id_AST = astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(IDENT); match(LPAREN); parameterDeclarationList(); param_AST = (AST)returnAST; match(RPAREN); { boolean synPredMatched241 = false; if (((LA(1)==LITERAL_throws||LA(1)==NLS) && (_tokenSet_28.member(LA(2))))) { int _m241 = mark(); synPredMatched241 = true; inputState.guessing++; try { { nls(); match(LITERAL_throws); } } catch (RecognitionException pe) { synPredMatched241 = false; } rewind(_m241); inputState.guessing--; } if ( synPredMatched241 ) { throwsClause(); tc_AST = (AST)returnAST; } else if ((LA(1)==LCURLY||LA(1)==NLS) && (_tokenSet_65.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } nlsWarn(); if ( inputState.guessing==0 ) { isConstructorIdent(id); } constructorBody(); cb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { constructorDefinition_AST = (AST)currentAST.root; constructorDefinition_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(CTOR_IDENT,"CTOR_IDENT",first,LT(1))).add(mods).add(param_AST).add(tc_AST).add(cb_AST)); currentAST.root = constructorDefinition_AST; currentAST.child = constructorDefinition_AST!=null &&constructorDefinition_AST.getFirstChild()!=null ? constructorDefinition_AST.getFirstChild() : constructorDefinition_AST; currentAST.advanceChildToEnd(); } constructorDefinition_AST = (AST)currentAST.root; returnAST = constructorDefinition_AST; } public final void multipleAssignmentDeclarationStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST multipleAssignmentDeclarationStart_AST = null; { _loop221: do { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: { modifier(); astFactory.addASTChild(currentAST, returnAST); nls(); astFactory.addASTChild(currentAST, returnAST); break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); nls(); astFactory.addASTChild(currentAST, returnAST); break; } default: { break _loop221; } } } while (true); } AST tmp182_AST = null; tmp182_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp182_AST); match(LITERAL_def); nls(); astFactory.addASTChild(currentAST, returnAST); AST tmp183_AST = null; tmp183_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp183_AST); match(LPAREN); multipleAssignmentDeclarationStart_AST = (AST)currentAST.root; returnAST = multipleAssignmentDeclarationStart_AST; } public final void multipleAssignmentDeclaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST multipleAssignmentDeclaration_AST = null; AST mods_AST = null; AST t_AST = null; Token first = cloneToken(LT(1)); modifiers(); mods_AST = (AST)returnAST; { switch ( LA(1)) { case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { typeSpec(false); t_AST = (AST)returnAST; break; } case LPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp184_AST = null; tmp184_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp184_AST); match(LPAREN); nls(); typeNamePairs(mods_AST,first); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); AST tmp186_AST = null; tmp186_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp186_AST); match(ASSIGN); nls(); assignmentExpression(0); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { multipleAssignmentDeclaration_AST = (AST)currentAST.root; multipleAssignmentDeclaration_AST=(AST)astFactory.make( (new ASTArray(4)).add(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1))).add(mods_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t_AST))).add(multipleAssignmentDeclaration_AST)); currentAST.root = multipleAssignmentDeclaration_AST; currentAST.child = multipleAssignmentDeclaration_AST!=null &&multipleAssignmentDeclaration_AST.getFirstChild()!=null ? multipleAssignmentDeclaration_AST.getFirstChild() : multipleAssignmentDeclaration_AST; currentAST.advanceChildToEnd(); } multipleAssignmentDeclaration_AST = (AST)currentAST.root; returnAST = multipleAssignmentDeclaration_AST; } public final void constructorBody() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constructorBody_AST = null; AST eci_AST = null; AST bb1_AST = null; AST bb2_AST = null; Token first = LT(1); match(LCURLY); nls(); { boolean synPredMatched211 = false; if (((_tokenSet_66.member(LA(1))) && (_tokenSet_67.member(LA(2))))) { int _m211 = mark(); synPredMatched211 = true; inputState.guessing++; try { { explicitConstructorInvocation(); } } catch (RecognitionException pe) { synPredMatched211 = false; } rewind(_m211); inputState.guessing--; } if ( synPredMatched211 ) { explicitConstructorInvocation(); eci_AST = (AST)returnAST; { switch ( LA(1)) { case SEMI: case NLS: { sep(); blockBody(sepToken); bb1_AST = (AST)returnAST; break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((_tokenSet_30.member(LA(1))) && (_tokenSet_68.member(LA(2)))) { blockBody(EOF); bb2_AST = (AST)returnAST; } else { throw new NoViableAltException(LT(1), getFilename()); } } match(RCURLY); if ( inputState.guessing==0 ) { constructorBody_AST = (AST)currentAST.root; if (eci_AST != null) constructorBody_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(SLIST,"{",first,LT(1))).add(eci_AST).add(bb1_AST)); else constructorBody_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(SLIST,"{",first,LT(1))).add(bb2_AST)); currentAST.root = constructorBody_AST; currentAST.child = constructorBody_AST!=null &&constructorBody_AST.getFirstChild()!=null ? constructorBody_AST.getFirstChild() : constructorBody_AST; currentAST.advanceChildToEnd(); } constructorBody_AST = (AST)currentAST.root; returnAST = constructorBody_AST; } /** Catch obvious constructor calls, but not the expr.super(...) calls */ public final void explicitConstructorInvocation() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST explicitConstructorInvocation_AST = null; Token lp1 = null; AST lp1_AST = null; Token lp2 = null; AST lp2_AST = null; { switch ( LA(1)) { case LT: { typeArguments(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_super: case LITERAL_this: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LITERAL_this: { match(LITERAL_this); lp1 = LT(1); lp1_AST = astFactory.create(lp1); astFactory.makeASTRoot(currentAST, lp1_AST); match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); if ( inputState.guessing==0 ) { lp1_AST.setType(CTOR_CALL); } break; } case LITERAL_super: { match(LITERAL_super); lp2 = LT(1); lp2_AST = astFactory.create(lp2); astFactory.makeASTRoot(currentAST, lp2_AST); match(LPAREN); argList(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); if ( inputState.guessing==0 ) { lp2_AST.setType(SUPER_CTOR_CALL); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } explicitConstructorInvocation_AST = (AST)currentAST.root; returnAST = explicitConstructorInvocation_AST; } public final void listOfVariables( AST mods, AST t, Token first ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST listOfVariables_AST = null; variableDeclarator(getASTFactory().dupTree(mods), getASTFactory().dupTree(t),first); astFactory.addASTChild(currentAST, returnAST); { _loop218: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); if ( inputState.guessing==0 ) { first = LT(1); } variableDeclarator(getASTFactory().dupTree(mods), getASTFactory().dupTree(t),first); astFactory.addASTChild(currentAST, returnAST); } else { break _loop218; } } while (true); } listOfVariables_AST = (AST)currentAST.root; returnAST = listOfVariables_AST; } /** Declaration of a variable. This can be a class/instance variable, * or a local variable in a method * It can also include possible initialization. */ public final void variableDeclarator( AST mods, AST t,Token first ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableDeclarator_AST = null; AST id_AST = null; AST v_AST = null; variableName(); id_AST = (AST)returnAST; { switch ( LA(1)) { case ASSIGN: { varInitializer(); v_AST = (AST)returnAST; break; } case EOF: case COMMA: case RPAREN: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_else: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { variableDeclarator_AST = (AST)currentAST.root; variableDeclarator_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(VARIABLE_DEF,"VARIABLE_DEF",first,LT(1))).add(mods).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t))).add(id_AST).add(v_AST)); currentAST.root = variableDeclarator_AST; currentAST.child = variableDeclarator_AST!=null &&variableDeclarator_AST.getFirstChild()!=null ? variableDeclarator_AST.getFirstChild() : variableDeclarator_AST; currentAST.advanceChildToEnd(); } returnAST = variableDeclarator_AST; } public final void typeNamePairs( AST mods, Token first ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST typeNamePairs_AST = null; AST t_AST = null; AST tn_AST = null; { if ((_tokenSet_24.member(LA(1))) && (_tokenSet_31.member(LA(2)))) { typeSpec(false); t_AST = (AST)returnAST; } else if ((LA(1)==IDENT) && (LA(2)==COMMA||LA(2)==RPAREN)) { } else { throw new NoViableAltException(LT(1), getFilename()); } } singleVariable(getASTFactory().dupTree(mods),t_AST); astFactory.addASTChild(currentAST, returnAST); { _loop226: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); if ( inputState.guessing==0 ) { first = LT(1); } { if ((_tokenSet_24.member(LA(1))) && (_tokenSet_31.member(LA(2)))) { typeSpec(false); tn_AST = (AST)returnAST; } else if ((LA(1)==IDENT) && (LA(2)==COMMA||LA(2)==RPAREN)) { } else { throw new NoViableAltException(LT(1), getFilename()); } } singleVariable(getASTFactory().dupTree(mods),tn_AST); astFactory.addASTChild(currentAST, returnAST); } else { break _loop226; } } while (true); } typeNamePairs_AST = (AST)currentAST.root; returnAST = typeNamePairs_AST; } public final void assignmentExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST assignmentExpression_AST = null; conditionalExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case ASSIGN: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: case STAR_STAR_ASSIGN: { { switch ( LA(1)) { case ASSIGN: { AST tmp195_AST = null; tmp195_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp195_AST); match(ASSIGN); break; } case PLUS_ASSIGN: { AST tmp196_AST = null; tmp196_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp196_AST); match(PLUS_ASSIGN); break; } case MINUS_ASSIGN: { AST tmp197_AST = null; tmp197_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp197_AST); match(MINUS_ASSIGN); break; } case STAR_ASSIGN: { AST tmp198_AST = null; tmp198_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp198_AST); match(STAR_ASSIGN); break; } case DIV_ASSIGN: { AST tmp199_AST = null; tmp199_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp199_AST); match(DIV_ASSIGN); break; } case MOD_ASSIGN: { AST tmp200_AST = null; tmp200_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp200_AST); match(MOD_ASSIGN); break; } case SR_ASSIGN: { AST tmp201_AST = null; tmp201_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp201_AST); match(SR_ASSIGN); break; } case BSR_ASSIGN: { AST tmp202_AST = null; tmp202_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp202_AST); match(BSR_ASSIGN); break; } case SL_ASSIGN: { AST tmp203_AST = null; tmp203_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp203_AST); match(SL_ASSIGN); break; } case BAND_ASSIGN: { AST tmp204_AST = null; tmp204_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp204_AST); match(BAND_ASSIGN); break; } case BXOR_ASSIGN: { AST tmp205_AST = null; tmp205_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp205_AST); match(BXOR_ASSIGN); break; } case BOR_ASSIGN: { AST tmp206_AST = null; tmp206_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp206_AST); match(BOR_ASSIGN); break; } case STAR_STAR_ASSIGN: { AST tmp207_AST = null; tmp207_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp207_AST); match(STAR_STAR_ASSIGN); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); expressionStatementNoCheck(); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case RBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case COMMA: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case RPAREN: case LCURLY: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case CLOSABLE_BLOCK_OP: case COLON: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } assignmentExpression_AST = (AST)currentAST.root; returnAST = assignmentExpression_AST; } /** Zero or more insignificant newlines, all gobbled up and thrown away, * but a warning message is left for the user, if there was a newline. */ public final void nlsWarn() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST nlsWarn_AST = null; { boolean synPredMatched576 = false; if (((_tokenSet_69.member(LA(1))) && (_tokenSet_1.member(LA(2))))) { int _m576 = mark(); synPredMatched576 = true; inputState.guessing++; try { { match(NLS); } } catch (RecognitionException pe) { synPredMatched576 = false; } rewind(_m576); inputState.guessing--; } if ( synPredMatched576 ) { if ( inputState.guessing==0 ) { addWarning( "A newline at this point does not follow the Groovy Coding Conventions.", "Keep this statement on one line, or use curly braces to break across multiple lines." ); } } else if ((_tokenSet_69.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } nls(); returnAST = nlsWarn_AST; } /** An open block is not allowed to have closure arguments. */ public final void openBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST openBlock_AST = null; AST bb_AST = null; Token first = LT(1); match(LCURLY); nls(); blockBody(EOF); bb_AST = (AST)returnAST; match(RCURLY); if ( inputState.guessing==0 ) { openBlock_AST = (AST)currentAST.root; openBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(SLIST,"{",first,LT(1))).add(bb_AST)); currentAST.root = openBlock_AST; currentAST.child = openBlock_AST!=null &&openBlock_AST.getFirstChild()!=null ? openBlock_AST.getFirstChild() : openBlock_AST; currentAST.advanceChildToEnd(); } openBlock_AST = (AST)currentAST.root; returnAST = openBlock_AST; } public final void variableName() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST variableName_AST = null; AST tmp210_AST = null; tmp210_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp210_AST); match(IDENT); variableName_AST = (AST)currentAST.root; returnAST = variableName_AST; } public final void expressionStatementNoCheck() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST expressionStatementNoCheck_AST = null; AST head_AST = null; AST cmd_AST = null; boolean isPathExpr = true; expression(LC_STMT); head_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { isPathExpr = (head_AST == lastPathExpression); } { if (((_tokenSet_70.member(LA(1))) && (_tokenSet_71.member(LA(2))))&&(LA(1)!=LITERAL_else && isPathExpr /*&& #head.getType()==METHOD_CALL*/)) { commandArgumentsGreedy(head_AST); cmd_AST = (AST)returnAST; if ( inputState.guessing==0 ) { expressionStatementNoCheck_AST = (AST)currentAST.root; expressionStatementNoCheck_AST = cmd_AST; currentAST.root = expressionStatementNoCheck_AST; currentAST.child = expressionStatementNoCheck_AST!=null &&expressionStatementNoCheck_AST.getFirstChild()!=null ? expressionStatementNoCheck_AST.getFirstChild() : expressionStatementNoCheck_AST; currentAST.advanceChildToEnd(); } } else if ((_tokenSet_70.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } expressionStatementNoCheck_AST = (AST)currentAST.root; returnAST = expressionStatementNoCheck_AST; } /** A formal parameter for a method or closure. */ public final void parameterDeclaration() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterDeclaration_AST = null; AST pm_AST = null; AST t_AST = null; Token id = null; AST id_AST = null; AST exp_AST = null; Token first = LT(1);boolean spreadParam = false; parameterModifiersOpt(); pm_AST = (AST)returnAST; { if ((_tokenSet_24.member(LA(1))) && (_tokenSet_72.member(LA(2)))) { typeSpec(false); t_AST = (AST)returnAST; } else if ((LA(1)==IDENT||LA(1)==TRIPLE_DOT) && (_tokenSet_73.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { switch ( LA(1)) { case TRIPLE_DOT: { match(TRIPLE_DOT); if ( inputState.guessing==0 ) { spreadParam = true; } break; } case IDENT: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } id = LT(1); id_AST = astFactory.create(id); match(IDENT); { switch ( LA(1)) { case ASSIGN: { varInitializer(); exp_AST = (AST)returnAST; break; } case COMMA: case RPAREN: case CLOSABLE_BLOCK_OP: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { parameterDeclaration_AST = (AST)currentAST.root; if (spreadParam) { parameterDeclaration_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(VARIABLE_PARAMETER_DEF,"VARIABLE_PARAMETER_DEF",first,LT(1))).add(pm_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t_AST))).add(id_AST).add(exp_AST)); } else { parameterDeclaration_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1))).add(pm_AST).add((AST)astFactory.make( (new ASTArray(2)).add(create(TYPE,"TYPE",first,LT(1))).add(t_AST))).add(id_AST).add(exp_AST)); } currentAST.root = parameterDeclaration_AST; currentAST.child = parameterDeclaration_AST!=null &¶meterDeclaration_AST.getFirstChild()!=null ? parameterDeclaration_AST.getFirstChild() : parameterDeclaration_AST; currentAST.advanceChildToEnd(); } returnAST = parameterDeclaration_AST; } public final void parameterModifiersOpt() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parameterModifiersOpt_AST = null; Token first = LT(1);int seenDef = 0; { _loop263: do { switch ( LA(1)) { case FINAL: { AST tmp212_AST = null; tmp212_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp212_AST); match(FINAL); nls(); break; } case AT: { annotation(); astFactory.addASTChild(currentAST, returnAST); nls(); break; } default: if (((LA(1)==LITERAL_def))&&(seenDef++ == 0)) { match(LITERAL_def); nls(); } else { break _loop263; } } } while (true); } if ( inputState.guessing==0 ) { parameterModifiersOpt_AST = (AST)currentAST.root; parameterModifiersOpt_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))).add(parameterModifiersOpt_AST)); currentAST.root = parameterModifiersOpt_AST; currentAST.child = parameterModifiersOpt_AST!=null &¶meterModifiersOpt_AST.getFirstChild()!=null ? parameterModifiersOpt_AST.getFirstChild() : parameterModifiersOpt_AST; currentAST.advanceChildToEnd(); } parameterModifiersOpt_AST = (AST)currentAST.root; returnAST = parameterModifiersOpt_AST; } /** Closure parameters are exactly like method parameters, * except that they are not enclosed in parentheses, but rather * are prepended to the front of a block, just after the brace. * They are separated from the closure body by a CLOSABLE_BLOCK_OP token '->'. */ public final void closableBlockParamsOpt( boolean addImplicit ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closableBlockParamsOpt_AST = null; boolean synPredMatched266 = false; if (((_tokenSet_74.member(LA(1))) && (_tokenSet_75.member(LA(2))))) { int _m266 = mark(); synPredMatched266 = true; inputState.guessing++; try { { parameterDeclarationList(); nls(); match(CLOSABLE_BLOCK_OP); } } catch (RecognitionException pe) { synPredMatched266 = false; } rewind(_m266); inputState.guessing--; } if ( synPredMatched266 ) { parameterDeclarationList(); astFactory.addASTChild(currentAST, returnAST); nls(); match(CLOSABLE_BLOCK_OP); nls(); closableBlockParamsOpt_AST = (AST)currentAST.root; } else if (((_tokenSet_30.member(LA(1))) && (_tokenSet_71.member(LA(2))))&&(addImplicit)) { implicitParameters(); astFactory.addASTChild(currentAST, returnAST); closableBlockParamsOpt_AST = (AST)currentAST.root; } else if ((_tokenSet_30.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { closableBlockParamsOpt_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = closableBlockParamsOpt_AST; } /** A block known to be a closure, but which omits its arguments, is given this placeholder. * A subsequent pass is responsible for deciding if there is an implicit 'it' parameter, * or if the parameter list should be empty. */ public final void implicitParameters() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST implicitParameters_AST = null; Token first = LT(1); if ( inputState.guessing==0 ) { implicitParameters_AST = (AST)currentAST.root; implicitParameters_AST = (AST)astFactory.make( (new ASTArray(1)).add(create(IMPLICIT_PARAMETERS,"IMPLICIT_PARAMETERS",first,LT(1)))); currentAST.root = implicitParameters_AST; currentAST.child = implicitParameters_AST!=null &&implicitParameters_AST.getFirstChild()!=null ? implicitParameters_AST.getFirstChild() : implicitParameters_AST; currentAST.advanceChildToEnd(); } implicitParameters_AST = (AST)currentAST.root; returnAST = implicitParameters_AST; } /** Lookahead to check whether a block begins with explicit closure arguments. */ public final void closableBlockParamsStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closableBlockParamsStart_AST = null; nls(); parameterDeclarationList(); nls(); AST tmp215_AST = null; tmp215_AST = astFactory.create(LT(1)); match(CLOSABLE_BLOCK_OP); returnAST = closableBlockParamsStart_AST; } /** Simple names, as in {x|...}, are completely equivalent to {(def x)|...}. Build the right AST. */ public final void closableBlockParam() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closableBlockParam_AST = null; Token id = null; AST id_AST = null; Token first = LT(1); id = LT(1); id_AST = astFactory.create(id); match(IDENT); if ( inputState.guessing==0 ) { closableBlockParam_AST = (AST)currentAST.root; closableBlockParam_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(PARAMETER_DEF,"PARAMETER_DEF",first,LT(1))).add((AST)astFactory.make( (new ASTArray(1)).add(create(MODIFIERS,"MODIFIERS",first,LT(1))))).add((AST)astFactory.make( (new ASTArray(1)).add(create(TYPE,"TYPE",first,LT(1))))).add(id_AST)); currentAST.root = closableBlockParam_AST; currentAST.child = closableBlockParam_AST!=null &&closableBlockParam_AST.getFirstChild()!=null ? closableBlockParam_AST.getFirstChild() : closableBlockParam_AST; currentAST.advanceChildToEnd(); } returnAST = closableBlockParam_AST; } /** A block which is known to be a closure, even if it has no apparent arguments. * A block inside an expression or after a method call is always assumed to be a closure. * Only labeled, unparameterized blocks which occur directly as substatements are kept open. */ public final void closableBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closableBlock_AST = null; AST cbp_AST = null; AST bb_AST = null; Token first = LT(1); match(LCURLY); nls(); closableBlockParamsOpt(true); cbp_AST = (AST)returnAST; blockBody(EOF); bb_AST = (AST)returnAST; match(RCURLY); if ( inputState.guessing==0 ) { closableBlock_AST = (AST)currentAST.root; closableBlock_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(CLOSABLE_BLOCK,"{",first,LT(1))).add(cbp_AST).add(bb_AST)); currentAST.root = closableBlock_AST; currentAST.child = closableBlock_AST!=null &&closableBlock_AST.getFirstChild()!=null ? closableBlock_AST.getFirstChild() : closableBlock_AST; currentAST.advanceChildToEnd(); } closableBlock_AST = (AST)currentAST.root; returnAST = closableBlock_AST; } /** A sub-block of a block can be either open or closable. * It is closable if and only if there are explicit closure arguments. * Compare this to a block which is appended to a method call, * which is given closure arguments, even if they are not explicit in the code. */ public final void openOrClosableBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST openOrClosableBlock_AST = null; AST cp_AST = null; AST bb_AST = null; Token first = LT(1); match(LCURLY); nls(); closableBlockParamsOpt(false); cp_AST = (AST)returnAST; blockBody(EOF); bb_AST = (AST)returnAST; match(RCURLY); if ( inputState.guessing==0 ) { openOrClosableBlock_AST = (AST)currentAST.root; if (cp_AST == null) openOrClosableBlock_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(SLIST,"{",first,LT(1))).add(bb_AST)); else openOrClosableBlock_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(CLOSABLE_BLOCK,"{",first,LT(1))).add(cp_AST).add(bb_AST)); currentAST.root = openOrClosableBlock_AST; currentAST.child = openOrClosableBlock_AST!=null &&openOrClosableBlock_AST.getFirstChild()!=null ? openOrClosableBlock_AST.getFirstChild() : openOrClosableBlock_AST; currentAST.advanceChildToEnd(); } openOrClosableBlock_AST = (AST)currentAST.root; returnAST = openOrClosableBlock_AST; } /** A labeled statement, consisting of a vanilla identifier followed by a colon. */ public final void statementLabelPrefix() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST statementLabelPrefix_AST = null; Token c = null; AST c_AST = null; AST tmp220_AST = null; tmp220_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp220_AST); match(IDENT); c = LT(1); c_AST = astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(LABELED_STAT); } nls(); statementLabelPrefix_AST = (AST)currentAST.root; returnAST = statementLabelPrefix_AST; } /** An expression statement can be any general expression. *

      * An expression statement can also be a command, * which is a simple method call in which the outermost parentheses are omitted. *

      * Certain "suspicious" looking forms are flagged for the user to disambiguate. */ public final void expressionStatement( int prevToken ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST expressionStatement_AST = null; AST esn_AST = null; Token first = LT(1); { boolean synPredMatched329 = false; if (((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2))))) { int _m329 = mark(); synPredMatched329 = true; inputState.guessing++; try { { suspiciousExpressionStatementStart(); } } catch (RecognitionException pe) { synPredMatched329 = false; } rewind(_m329); inputState.guessing--; } if ( synPredMatched329 ) { checkSuspiciousExpressionStatement(prevToken); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } expressionStatementNoCheck(); esn_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { expressionStatement_AST = (AST)currentAST.root; expressionStatement_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(esn_AST)); currentAST.root = expressionStatement_AST; currentAST.child = expressionStatement_AST!=null &&expressionStatement_AST.getFirstChild()!=null ? expressionStatement_AST.getFirstChild() : expressionStatement_AST; currentAST.advanceChildToEnd(); } expressionStatement_AST = (AST)currentAST.root; returnAST = expressionStatement_AST; } public final void assignmentLessExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST assignmentLessExpression_AST = null; Token first = LT(1); { conditionalExpression(0); astFactory.addASTChild(currentAST, returnAST); } if ( inputState.guessing==0 ) { assignmentLessExpression_AST = (AST)currentAST.root; assignmentLessExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(assignmentLessExpression_AST)); currentAST.root = assignmentLessExpression_AST; currentAST.child = assignmentLessExpression_AST!=null &&assignmentLessExpression_AST.getFirstChild()!=null ? assignmentLessExpression_AST.getFirstChild() : assignmentLessExpression_AST; currentAST.advanceChildToEnd(); } assignmentLessExpression_AST = (AST)currentAST.root; returnAST = assignmentLessExpression_AST; } /** In Java, "if", "while", and "for" statements can take random, non-braced statements as their bodies. * Support this practice, even though it isn't very Groovy. */ public final void compatibleBodyStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST compatibleBodyStatement_AST = null; boolean synPredMatched318 = false; if (((LA(1)==LCURLY) && (_tokenSet_30.member(LA(2))))) { int _m318 = mark(); synPredMatched318 = true; inputState.guessing++; try { { match(LCURLY); } } catch (RecognitionException pe) { synPredMatched318 = false; } rewind(_m318); inputState.guessing--; } if ( synPredMatched318 ) { compoundStatement(); astFactory.addASTChild(currentAST, returnAST); compatibleBodyStatement_AST = (AST)currentAST.root; } else if ((_tokenSet_18.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { statement(EOF); astFactory.addASTChild(currentAST, returnAST); compatibleBodyStatement_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = compatibleBodyStatement_AST; } public final void forStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forStatement_AST = null; AST cl_AST = null; AST fic_AST = null; Token s = null; AST s_AST = null; AST forCbs_AST = null; Token first = LT(1); match(LITERAL_for); match(LPAREN); { boolean synPredMatched305 = false; if (((_tokenSet_76.member(LA(1))) && (_tokenSet_77.member(LA(2))))) { int _m305 = mark(); synPredMatched305 = true; inputState.guessing++; try { { switch ( LA(1)) { case SEMI: { match(SEMI); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { { strictContextExpression(true); match(SEMI); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException pe) { synPredMatched305 = false; } rewind(_m305); inputState.guessing--; } if ( synPredMatched305 ) { closureList(); cl_AST = (AST)returnAST; } else if ((_tokenSet_15.member(LA(1))) && (_tokenSet_78.member(LA(2)))) { forInClause(); fic_AST = (AST)returnAST; } else { throw new NoViableAltException(LT(1), getFilename()); } } match(RPAREN); nls(); { switch ( LA(1)) { case SEMI: { s = LT(1); s_AST = astFactory.create(s); match(SEMI); break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { compatibleBodyStatement(); forCbs_AST = (AST)returnAST; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forStatement_AST = (AST)currentAST.root; if (cl_AST != null) { if (s_AST != null) forStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_for,"for",first,LT(1))).add(cl_AST).add(s_AST)); else forStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_for,"for",first,LT(1))).add(cl_AST).add(forCbs_AST)); } else { if (s_AST != null) forStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_for,"for",first,LT(1))).add(fic_AST).add(s_AST)); else forStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_for,"for",first,LT(1))).add(fic_AST).add(forCbs_AST)); } currentAST.root = forStatement_AST; currentAST.child = forStatement_AST!=null &&forStatement_AST.getFirstChild()!=null ? forStatement_AST.getFirstChild() : forStatement_AST; currentAST.advanceChildToEnd(); } forStatement_AST = (AST)currentAST.root; returnAST = forStatement_AST; } /** Things that can show up as expressions, but only in strict * contexts like inside parentheses, argument lists, and list constructors. */ public final boolean strictContextExpression( boolean allowDeclaration ) throws RecognitionException, TokenStreamException { boolean hasDeclaration=false; returnAST = null; ASTPair currentAST = new ASTPair(); AST strictContextExpression_AST = null; Token first = LT(1); { boolean synPredMatched511 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_79.member(LA(2))))) { int _m511 = mark(); synPredMatched511 = true; inputState.guessing++; try { { if (!(allowDeclaration)) throw new SemanticException("allowDeclaration"); declarationStart(); } } catch (RecognitionException pe) { synPredMatched511 = false; } rewind(_m511); inputState.guessing--; } if ( synPredMatched511 ) { if ( inputState.guessing==0 ) { hasDeclaration=true; } singleDeclaration(); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { expression(0); astFactory.addASTChild(currentAST, returnAST); } else if (((LA(1) >= LITERAL_return && LA(1) <= LITERAL_assert))) { branchStatement(); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==AT) && (LA(2)==IDENT)) { annotation(); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { strictContextExpression_AST = (AST)currentAST.root; strictContextExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(strictContextExpression_AST)); currentAST.root = strictContextExpression_AST; currentAST.child = strictContextExpression_AST!=null &&strictContextExpression_AST.getFirstChild()!=null ? strictContextExpression_AST.getFirstChild() : strictContextExpression_AST; currentAST.advanceChildToEnd(); } strictContextExpression_AST = (AST)currentAST.root; returnAST = strictContextExpression_AST; return hasDeclaration; } public final void casesGroup() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST casesGroup_AST = null; Token first = LT(1); { int _cnt342=0; _loop342: do { if ((LA(1)==LITERAL_default||LA(1)==LITERAL_case)) { aCase(); astFactory.addASTChild(currentAST, returnAST); } else { if ( _cnt342>=1 ) { break _loop342; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt342++; } while (true); } caseSList(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { casesGroup_AST = (AST)currentAST.root; casesGroup_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(CASE_GROUP,"CASE_GROUP",first,LT(1))).add(casesGroup_AST)); currentAST.root = casesGroup_AST; currentAST.child = casesGroup_AST!=null &&casesGroup_AST.getFirstChild()!=null ? casesGroup_AST.getFirstChild() : casesGroup_AST; currentAST.advanceChildToEnd(); } casesGroup_AST = (AST)currentAST.root; returnAST = casesGroup_AST; } public final void tryBlock() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST tryBlock_AST = null; AST tryCs_AST = null; AST h_AST = null; AST fc_AST = null; Token first = LT(1);List catchNodes = new ArrayList();AST newHandler_AST = null; match(LITERAL_try); nlsWarn(); compoundStatement(); tryCs_AST = (AST)returnAST; { _loop359: do { if (((LA(1)==LITERAL_catch||LA(1)==NLS) && (LA(2)==LPAREN||LA(2)==LITERAL_catch))&&(!(LA(1) == NLS && LA(2) == LPAREN))) { nls(); handler(); h_AST = (AST)returnAST; if ( inputState.guessing==0 ) { newHandler_AST = (AST)astFactory.make( (new ASTArray(3)).add(null).add(newHandler_AST).add(h_AST)); } } else { break _loop359; } } while (true); } { if ((LA(1)==LITERAL_finally||LA(1)==NLS) && (_tokenSet_80.member(LA(2)))) { nls(); finallyClause(); fc_AST = (AST)returnAST; } else if ((_tokenSet_10.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { tryBlock_AST = (AST)currentAST.root; tryBlock_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(LITERAL_try,"try",first,LT(1))).add(tryCs_AST).add(newHandler_AST).add(fc_AST)); currentAST.root = tryBlock_AST; currentAST.child = tryBlock_AST!=null &&tryBlock_AST.getFirstChild()!=null ? tryBlock_AST.getFirstChild() : tryBlock_AST; currentAST.advanceChildToEnd(); } tryBlock_AST = (AST)currentAST.root; returnAST = tryBlock_AST; } /** In Groovy, return, break, continue, throw, and assert can be used in a parenthesized expression context. * Example: println (x || (return)); println assert x, "won't print a false value!" * If an optional expression is missing, its value is void (this coerces to null when a value is required). */ public final void branchStatement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST branchStatement_AST = null; AST returnE_AST = null; Token breakI = null; AST breakI_AST = null; Token contI = null; AST contI_AST = null; AST throwE_AST = null; AST assertAle_AST = null; AST assertE_AST = null; Token first = LT(1); switch ( LA(1)) { case LITERAL_return: { match(LITERAL_return); { switch ( LA(1)) { case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { expression(0); returnE_AST = (AST)returnAST; break; } case EOF: case RBRACK: case COMMA: case RPAREN: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_else: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { branchStatement_AST = (AST)currentAST.root; branchStatement_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(LITERAL_return,"return",first,LT(1))).add(returnE_AST)); currentAST.root = branchStatement_AST; currentAST.child = branchStatement_AST!=null &&branchStatement_AST.getFirstChild()!=null ? branchStatement_AST.getFirstChild() : branchStatement_AST; currentAST.advanceChildToEnd(); } branchStatement_AST = (AST)currentAST.root; break; } case LITERAL_break: { match(LITERAL_break); { switch ( LA(1)) { case IDENT: { breakI = LT(1); breakI_AST = astFactory.create(breakI); match(IDENT); break; } case EOF: case RBRACK: case COMMA: case RPAREN: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_else: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { branchStatement_AST = (AST)currentAST.root; branchStatement_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(LITERAL_break,"break",first,LT(1))).add(breakI_AST)); currentAST.root = branchStatement_AST; currentAST.child = branchStatement_AST!=null &&branchStatement_AST.getFirstChild()!=null ? branchStatement_AST.getFirstChild() : branchStatement_AST; currentAST.advanceChildToEnd(); } branchStatement_AST = (AST)currentAST.root; break; } case LITERAL_continue: { match(LITERAL_continue); { switch ( LA(1)) { case IDENT: { contI = LT(1); contI_AST = astFactory.create(contI); match(IDENT); break; } case EOF: case RBRACK: case COMMA: case RPAREN: case RCURLY: case SEMI: case LITERAL_default: case LITERAL_else: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { branchStatement_AST = (AST)currentAST.root; branchStatement_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(LITERAL_continue,"continue",first,LT(1))).add(contI_AST)); currentAST.root = branchStatement_AST; currentAST.child = branchStatement_AST!=null &&branchStatement_AST.getFirstChild()!=null ? branchStatement_AST.getFirstChild() : branchStatement_AST; currentAST.advanceChildToEnd(); } branchStatement_AST = (AST)currentAST.root; break; } case LITERAL_throw: { match(LITERAL_throw); expression(0); throwE_AST = (AST)returnAST; if ( inputState.guessing==0 ) { branchStatement_AST = (AST)currentAST.root; branchStatement_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(LITERAL_throw,"throw",first,LT(1))).add(throwE_AST)); currentAST.root = branchStatement_AST; currentAST.child = branchStatement_AST!=null &&branchStatement_AST.getFirstChild()!=null ? branchStatement_AST.getFirstChild() : branchStatement_AST; currentAST.advanceChildToEnd(); } branchStatement_AST = (AST)currentAST.root; break; } case LITERAL_assert: { match(LITERAL_assert); assignmentLessExpression(); assertAle_AST = (AST)returnAST; { if ((LA(1)==COMMA||LA(1)==COLON) && (_tokenSet_81.member(LA(2)))) { { switch ( LA(1)) { case COMMA: { match(COMMA); nls(); break; } case COLON: { match(COLON); nls(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } expression(0); assertE_AST = (AST)returnAST; } else if ((_tokenSet_82.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { branchStatement_AST = (AST)currentAST.root; branchStatement_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_assert,"assert",first,LT(1))).add(assertAle_AST).add(assertE_AST)); currentAST.root = branchStatement_AST; currentAST.child = branchStatement_AST!=null &&branchStatement_AST.getFirstChild()!=null ? branchStatement_AST.getFirstChild() : branchStatement_AST; currentAST.advanceChildToEnd(); } branchStatement_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = branchStatement_AST; } public final void closureList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closureList_AST = null; Token first = LT(1); boolean sce=false; { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { sce=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); break; } case SEMI: { if ( inputState.guessing==0 ) { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { int _cnt310=0; _loop310: do { if ((LA(1)==SEMI) && (_tokenSet_83.member(LA(2)))) { match(SEMI); sce=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==SEMI) && (LA(2)==RPAREN||LA(2)==SEMI)) { match(SEMI); if ( inputState.guessing==0 ) { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); } } else { if ( _cnt310>=1 ) { break _loop310; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt310++; } while (true); } if ( inputState.guessing==0 ) { closureList_AST = (AST)currentAST.root; closureList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1))).add(closureList_AST)); currentAST.root = closureList_AST; currentAST.child = closureList_AST!=null &&closureList_AST.getFirstChild()!=null ? closureList_AST.getFirstChild() : closureList_AST; currentAST.advanceChildToEnd(); } closureList_AST = (AST)currentAST.root; returnAST = closureList_AST; } public final void forInClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forInClause_AST = null; AST decl_AST = null; Token i = null; AST i_AST = null; Token c = null; AST c_AST = null; { boolean synPredMatched314 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_79.member(LA(2))))) { int _m314 = mark(); synPredMatched314 = true; inputState.guessing++; try { { declarationStart(); } } catch (RecognitionException pe) { synPredMatched314 = false; } rewind(_m314); inputState.guessing--; } if ( synPredMatched314 ) { singleDeclarationNoInit(); decl_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==IDENT) && (LA(2)==COLON||LA(2)==LITERAL_in)) { AST tmp234_AST = null; tmp234_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp234_AST); match(IDENT); } else { throw new NoViableAltException(LT(1), getFilename()); } } { switch ( LA(1)) { case LITERAL_in: { i = LT(1); i_AST = astFactory.create(i); astFactory.makeASTRoot(currentAST, i_AST); match(LITERAL_in); if ( inputState.guessing==0 ) { i_AST.setType(FOR_IN_ITERABLE); } shiftExpression(0); astFactory.addASTChild(currentAST, returnAST); break; } case COLON: { if ( inputState.guessing==0 ) { addWarning( "A colon at this point is legal Java but not recommended in Groovy.", "Use the 'in' keyword." ); require(decl_AST != null, "Java-style for-each statement requires a type declaration." , "Use the 'in' keyword, as for (x in y) {...}" ); } c = LT(1); c_AST = astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(FOR_IN_ITERABLE); } expression(0); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } forInClause_AST = (AST)currentAST.root; returnAST = forInClause_AST; } public final void shiftExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST shiftExpression_AST = null; additiveExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop462: do { if ((_tokenSet_84.member(LA(1)))) { { switch ( LA(1)) { case SR: case BSR: case SL: { { switch ( LA(1)) { case SL: { AST tmp235_AST = null; tmp235_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp235_AST); match(SL); break; } case SR: { AST tmp236_AST = null; tmp236_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp236_AST); match(SR); break; } case BSR: { AST tmp237_AST = null; tmp237_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp237_AST); match(BSR); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case RANGE_INCLUSIVE: { AST tmp238_AST = null; tmp238_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp238_AST); match(RANGE_INCLUSIVE); break; } case RANGE_EXCLUSIVE: { AST tmp239_AST = null; tmp239_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp239_AST); match(RANGE_EXCLUSIVE); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); additiveExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop462; } } while (true); } shiftExpression_AST = (AST)currentAST.root; returnAST = shiftExpression_AST; } public final void expression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST expression_AST = null; Token lp = null; AST lp_AST = null; AST m_AST = null; boolean synPredMatched385 = false; if (((LA(1)==LPAREN) && (_tokenSet_24.member(LA(2))))) { int _m385 = mark(); synPredMatched385 = true; inputState.guessing++; try { { match(LPAREN); typeSpec(true); match(RPAREN); expression(lc_stmt); } } catch (RecognitionException pe) { synPredMatched385 = false; } rewind(_m385); inputState.guessing--; } if ( synPredMatched385 ) { lp = LT(1); lp_AST = astFactory.create(lp); astFactory.makeASTRoot(currentAST, lp_AST); match(LPAREN); if ( inputState.guessing==0 ) { lp_AST.setType(TYPECAST); } typeSpec(true); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); expression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); expression_AST = (AST)currentAST.root; } else { boolean synPredMatched389 = false; if (((LA(1)==LPAREN) && (LA(2)==IDENT||LA(2)==NLS))) { int _m389 = mark(); synPredMatched389 = true; inputState.guessing++; try { { match(LPAREN); nls(); match(IDENT); { _loop388: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); match(IDENT); } else { break _loop388; } } while (true); } match(RPAREN); match(ASSIGN); } } catch (RecognitionException pe) { synPredMatched389 = false; } rewind(_m389); inputState.guessing--; } if ( synPredMatched389 ) { multipleAssignment(lc_stmt); m_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { expression_AST = (AST)currentAST.root; expression_AST=m_AST; currentAST.root = expression_AST; currentAST.child = expression_AST!=null &&expression_AST.getFirstChild()!=null ? expression_AST.getFirstChild() : expression_AST; currentAST.advanceChildToEnd(); } expression_AST = (AST)currentAST.root; } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { assignmentExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); expression_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = expression_AST; } /** Lookahead for suspicious statement warnings and errors. */ public final void suspiciousExpressionStatementStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST suspiciousExpressionStatementStart_AST = null; { switch ( LA(1)) { case PLUS: case MINUS: { { switch ( LA(1)) { case PLUS: { AST tmp241_AST = null; tmp241_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp241_AST); match(PLUS); break; } case MINUS: { AST tmp242_AST = null; tmp242_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp242_AST); match(MINUS); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LBRACK: case LPAREN: case LCURLY: { { switch ( LA(1)) { case LBRACK: { AST tmp243_AST = null; tmp243_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp243_AST); match(LBRACK); break; } case LPAREN: { AST tmp244_AST = null; tmp244_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp244_AST); match(LPAREN); break; } case LCURLY: { AST tmp245_AST = null; tmp245_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp245_AST); match(LCURLY); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } suspiciousExpressionStatementStart_AST = (AST)currentAST.root; returnAST = suspiciousExpressionStatementStart_AST; } /** * If two statements are separated by newline (not SEMI), the second had * better not look like the latter half of an expression. If it does, issue a warning. *

      * Also, if the expression starts with a closure, it needs to * have an explicit parameter list, in order to avoid the appearance of a * compound statement. This is a hard error. *

      * These rules are different from Java's "dumb expression" restriction. * Unlike Java, Groovy blocks can end with arbitrary (even dumb) expressions, * as a consequence of optional 'return' and 'continue' tokens. *

      * To make the programmer's intention clear, a leading closure must have an * explicit parameter list, and must not follow a previous statement separated * only by newlines. */ public final void checkSuspiciousExpressionStatement( int prevToken ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST checkSuspiciousExpressionStatement_AST = null; boolean synPredMatched334 = false; if (((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2))))) { int _m334 = mark(); synPredMatched334 = true; inputState.guessing++; try { { if ((_tokenSet_85.member(LA(1)))) { matchNot(LCURLY); } else if ((LA(1)==LCURLY)) { match(LCURLY); closableBlockParamsStart(); } else { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException pe) { synPredMatched334 = false; } rewind(_m334); inputState.guessing--; } if ( synPredMatched334 ) { { if (((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2))))&&(prevToken == NLS)) { if ( inputState.guessing==0 ) { addWarning( "Expression statement looks like it may continue a previous statement", "Either remove the previous newline, or add an explicit semicolon ';'."); } } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } checkSuspiciousExpressionStatement_AST = (AST)currentAST.root; } else if (((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2))))&&(prevToken == NLS)) { if ( inputState.guessing==0 ) { require(false, "Ambiguous expression could be a parameterless closure expression, "+ "an isolated open code block, or it may continue a previous statement", "Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated "+ "as an open block by giving it a label, e.g. L:{...}, "+ "and also either remove the previous newline, or add an explicit semicolon ';'" ); } checkSuspiciousExpressionStatement_AST = (AST)currentAST.root; } else if (((_tokenSet_19.member(LA(1))) && (_tokenSet_1.member(LA(2))))&&(prevToken != NLS)) { if ( inputState.guessing==0 ) { require(false, "Ambiguous expression could be either a parameterless closure expression or "+ "an isolated open code block", "Add an explicit closure parameter list, e.g. {it -> ...}, or force it to "+ "be treated as an open block by giving it a label, e.g. L:{...}"); } checkSuspiciousExpressionStatement_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = checkSuspiciousExpressionStatement_AST; } public final void commandArgumentsGreedy( AST head ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST commandArgumentsGreedy_AST = null; AST first_AST = null; AST pre_AST = null; AST pc_AST = null; AST ca_AST = null; AST prev = head; { boolean synPredMatched369 = false; if (((_tokenSet_86.member(LA(1))) && (_tokenSet_37.member(LA(2))))) { int _m369 = mark(); synPredMatched369 = true; inputState.guessing++; try { { if (!(prev==null || prev.getType()!=METHOD_CALL)) throw new SemanticException("prev==null || prev.getType()!=METHOD_CALL"); commandArgument(); } } catch (RecognitionException pe) { synPredMatched369 = false; } rewind(_m369); inputState.guessing--; } if ( synPredMatched369 ) { { commandArguments(head); first_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prev = first_AST; } } } else if ((_tokenSet_70.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } { { _loop378: do { if ((_tokenSet_87.member(LA(1))) && (_tokenSet_88.member(LA(2)))) { primaryExpression(); pre_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prev = (AST)astFactory.make( (new ASTArray(3)).add(create(DOT,".",prev)).add(prev).add(pre_AST)); } { boolean synPredMatched375 = false; if (((_tokenSet_89.member(LA(1))) && (_tokenSet_90.member(LA(2))))) { int _m375 = mark(); synPredMatched375 = true; inputState.guessing++; try { { pathElementStart(); } } catch (RecognitionException pe) { synPredMatched375 = false; } rewind(_m375); inputState.guessing--; } if ( synPredMatched375 ) { { pathChain(LC_STMT,prev); pc_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prev = pc_AST; } } } else if ((_tokenSet_86.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { { commandArguments(prev); ca_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prev = ca_AST; } } } else if ((_tokenSet_70.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } } else { break _loop378; } } while (true); } } if ( inputState.guessing==0 ) { commandArgumentsGreedy_AST = (AST)currentAST.root; commandArgumentsGreedy_AST = prev; currentAST.root = commandArgumentsGreedy_AST; currentAST.child = commandArgumentsGreedy_AST!=null &&commandArgumentsGreedy_AST.getFirstChild()!=null ? commandArgumentsGreedy_AST.getFirstChild() : commandArgumentsGreedy_AST; currentAST.advanceChildToEnd(); } commandArgumentsGreedy_AST = (AST)currentAST.root; returnAST = commandArgumentsGreedy_AST; } public final void aCase() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST aCase_AST = null; { switch ( LA(1)) { case LITERAL_case: { AST tmp246_AST = null; tmp246_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp246_AST); match(LITERAL_case); expression(0); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_default: { AST tmp247_AST = null; tmp247_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp247_AST); match(LITERAL_default); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(COLON); nls(); aCase_AST = (AST)currentAST.root; returnAST = aCase_AST; } public final void caseSList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST caseSList_AST = null; Token first = LT(1); statement(COLON); astFactory.addASTChild(currentAST, returnAST); { _loop348: do { if ((LA(1)==SEMI||LA(1)==NLS)) { sep(); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_if: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_try: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { statement(sepToken); astFactory.addASTChild(currentAST, returnAST); break; } case RCURLY: case SEMI: case LITERAL_default: case LITERAL_case: case NLS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop348; } } while (true); } if ( inputState.guessing==0 ) { caseSList_AST = (AST)currentAST.root; caseSList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(SLIST,"SLIST",first,LT(1))).add(caseSList_AST)); currentAST.root = caseSList_AST; currentAST.child = caseSList_AST!=null &&caseSList_AST.getFirstChild()!=null ? caseSList_AST.getFirstChild() : caseSList_AST; currentAST.advanceChildToEnd(); } caseSList_AST = (AST)currentAST.root; returnAST = caseSList_AST; } public final void forInit() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forInit_AST = null; Token first = LT(1); boolean synPredMatched351 = false; if (((_tokenSet_15.member(LA(1))) && (_tokenSet_16.member(LA(2))))) { int _m351 = mark(); synPredMatched351 = true; inputState.guessing++; try { { declarationStart(); } } catch (RecognitionException pe) { synPredMatched351 = false; } rewind(_m351); inputState.guessing--; } if ( synPredMatched351 ) { declaration(); astFactory.addASTChild(currentAST, returnAST); forInit_AST = (AST)currentAST.root; } else if ((_tokenSet_91.member(LA(1))) && (_tokenSet_92.member(LA(2)))) { { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { controlExpressionList(); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forInit_AST = (AST)currentAST.root; forInit_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_INIT,"FOR_INIT",first,LT(1))).add(forInit_AST)); currentAST.root = forInit_AST; currentAST.child = forInit_AST!=null &&forInit_AST.getFirstChild()!=null ? forInit_AST.getFirstChild() : forInit_AST; currentAST.advanceChildToEnd(); } forInit_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = forInit_AST; } public final void controlExpressionList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST controlExpressionList_AST = null; Token first = LT(1); boolean sce=false; sce=strictContextExpression(false); astFactory.addASTChild(currentAST, returnAST); { _loop393: do { if ((LA(1)==COMMA)) { match(COMMA); nls(); sce=strictContextExpression(false); astFactory.addASTChild(currentAST, returnAST); } else { break _loop393; } } while (true); } if ( inputState.guessing==0 ) { controlExpressionList_AST = (AST)currentAST.root; controlExpressionList_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(ELIST,"ELIST",first,LT(1))).add(controlExpressionList_AST)); currentAST.root = controlExpressionList_AST; currentAST.child = controlExpressionList_AST!=null &&controlExpressionList_AST.getFirstChild()!=null ? controlExpressionList_AST.getFirstChild() : controlExpressionList_AST; currentAST.advanceChildToEnd(); } controlExpressionList_AST = (AST)currentAST.root; returnAST = controlExpressionList_AST; } public final void forCond() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forCond_AST = null; Token first = LT(1); boolean sce=false; { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { sce=strictContextExpression(false); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forCond_AST = (AST)currentAST.root; forCond_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_CONDITION,"FOR_CONDITION",first,LT(1))).add(forCond_AST)); currentAST.root = forCond_AST; currentAST.child = forCond_AST!=null &&forCond_AST.getFirstChild()!=null ? forCond_AST.getFirstChild() : forCond_AST; currentAST.advanceChildToEnd(); } forCond_AST = (AST)currentAST.root; returnAST = forCond_AST; } public final void forIter() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST forIter_AST = null; Token first = LT(1); { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { controlExpressionList(); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { forIter_AST = (AST)currentAST.root; forIter_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(FOR_ITERATOR,"FOR_ITERATOR",first,LT(1))).add(forIter_AST)); currentAST.root = forIter_AST; currentAST.child = forIter_AST!=null &&forIter_AST.getFirstChild()!=null ? forIter_AST.getFirstChild() : forIter_AST; currentAST.advanceChildToEnd(); } forIter_AST = (AST)currentAST.root; returnAST = forIter_AST; } public final void handler() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST handler_AST = null; AST pd_AST = null; AST handlerCs_AST = null; Token first = LT(1); match(LITERAL_catch); match(LPAREN); parameterDeclaration(); pd_AST = (AST)returnAST; match(RPAREN); nlsWarn(); compoundStatement(); handlerCs_AST = (AST)returnAST; if ( inputState.guessing==0 ) { handler_AST = (AST)currentAST.root; handler_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(LITERAL_catch,"catch",first,LT(1))).add(pd_AST).add(handlerCs_AST)); currentAST.root = handler_AST; currentAST.child = handler_AST!=null &&handler_AST.getFirstChild()!=null ? handler_AST.getFirstChild() : handler_AST; currentAST.advanceChildToEnd(); } handler_AST = (AST)currentAST.root; returnAST = handler_AST; } public final void finallyClause() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST finallyClause_AST = null; AST finallyCs_AST = null; Token first = LT(1); match(LITERAL_finally); nlsWarn(); compoundStatement(); finallyCs_AST = (AST)returnAST; if ( inputState.guessing==0 ) { finallyClause_AST = (AST)currentAST.root; finallyClause_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(LITERAL_finally,"finally",first,LT(1))).add(finallyCs_AST)); currentAST.root = finallyClause_AST; currentAST.child = finallyClause_AST!=null &&finallyClause_AST.getFirstChild()!=null ? finallyClause_AST.getFirstChild() : finallyClause_AST; currentAST.advanceChildToEnd(); } finallyClause_AST = (AST)currentAST.root; returnAST = finallyClause_AST; } /** A member name (x.y) or element name (x[y]) can serve as a command name, * which may be followed by a list of arguments. * Unlike parenthesized arguments, these must be plain expressions, * without labels or spread operators. */ public final void commandArguments( AST head ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST commandArguments_AST = null; Token first = LT(1); commandArgument(); astFactory.addASTChild(currentAST, returnAST); { _loop365: do { if ((LA(1)==COMMA) && (_tokenSet_93.member(LA(2)))) { match(COMMA); nls(); commandArgument(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop365; } } while (true); } if ( inputState.guessing==0 ) { commandArguments_AST = (AST)currentAST.root; AST elist = (AST)astFactory.make( (new ASTArray(2)).add(create(ELIST,"ELIST",first,LT(1))).add(commandArguments_AST)); AST headid = (AST)astFactory.make( (new ASTArray(3)).add(create(METHOD_CALL,"",first,LT(1))).add(head).add(elist)); commandArguments_AST = headid; currentAST.root = commandArguments_AST; currentAST.child = commandArguments_AST!=null &&commandArguments_AST.getFirstChild()!=null ? commandArguments_AST.getFirstChild() : commandArguments_AST; currentAST.advanceChildToEnd(); } commandArguments_AST = (AST)currentAST.root; returnAST = commandArguments_AST; } public final void commandArgument() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST commandArgument_AST = null; Token c = null; AST c_AST = null; boolean synPredMatched381 = false; if (((_tokenSet_94.member(LA(1))) && (_tokenSet_95.member(LA(2))))) { int _m381 = mark(); synPredMatched381 = true; inputState.guessing++; try { { argumentLabel(); match(COLON); nls(); } } catch (RecognitionException pe) { synPredMatched381 = false; } rewind(_m381); inputState.guessing--; } if ( synPredMatched381 ) { { argumentLabel(); astFactory.addASTChild(currentAST, returnAST); c = LT(1); c_AST = astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); nls(); expression(0); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { c_AST.setType(LABELED_ARG); } } commandArgument_AST = (AST)currentAST.root; } else if ((_tokenSet_19.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { expression(0); astFactory.addASTChild(currentAST, returnAST); commandArgument_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = commandArgument_AST; } public final void primaryExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST primaryExpression_AST = null; AST pe_AST = null; Token first = LT(1); switch ( LA(1)) { case IDENT: { AST tmp255_AST = null; tmp255_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp255_AST); match(IDENT); primaryExpression_AST = (AST)currentAST.root; break; } case STRING_LITERAL: case LITERAL_false: case LITERAL_null: case LITERAL_true: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { constant(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_new: { newExpression(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_this: { AST tmp256_AST = null; tmp256_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp256_AST); match(LITERAL_this); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_super: { AST tmp257_AST = null; tmp257_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp257_AST); match(LITERAL_super); primaryExpression_AST = (AST)currentAST.root; break; } case LPAREN: { parenthesizedExpression(); pe_AST = (AST)returnAST; if ( inputState.guessing==0 ) { primaryExpression_AST = (AST)currentAST.root; primaryExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(pe_AST)); currentAST.root = primaryExpression_AST; currentAST.child = primaryExpression_AST!=null &&primaryExpression_AST.getFirstChild()!=null ? primaryExpression_AST.getFirstChild() : primaryExpression_AST; currentAST.advanceChildToEnd(); } primaryExpression_AST = (AST)currentAST.root; break; } case LCURLY: { closableBlockConstructorExpression(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LBRACK: { listOrMapConstructorExpression(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case STRING_CTOR_START: { stringConstructorExpression(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { builtInType(); astFactory.addASTChild(currentAST, returnAST); primaryExpression_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = primaryExpression_AST; } public final void pathElementStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST pathElementStart_AST = null; switch ( LA(1)) { case DOT: case NLS: { { nls(); AST tmp258_AST = null; tmp258_AST = astFactory.create(LT(1)); match(DOT); } break; } case SPREAD_DOT: { AST tmp259_AST = null; tmp259_AST = astFactory.create(LT(1)); match(SPREAD_DOT); break; } case OPTIONAL_DOT: { AST tmp260_AST = null; tmp260_AST = astFactory.create(LT(1)); match(OPTIONAL_DOT); break; } case MEMBER_POINTER: { AST tmp261_AST = null; tmp261_AST = astFactory.create(LT(1)); match(MEMBER_POINTER); break; } case LBRACK: { AST tmp262_AST = null; tmp262_AST = astFactory.create(LT(1)); match(LBRACK); break; } case LPAREN: { AST tmp263_AST = null; tmp263_AST = astFactory.create(LT(1)); match(LPAREN); break; } case LCURLY: { AST tmp264_AST = null; tmp264_AST = astFactory.create(LT(1)); match(LCURLY); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = pathElementStart_AST; } public final void pathChain( int lc_stmt, AST prefix ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST pathChain_AST = null; AST pe_AST = null; AST apb_AST = null; { int _cnt400=0; _loop400: do { boolean synPredMatched397 = false; if (((_tokenSet_89.member(LA(1))) && (_tokenSet_90.member(LA(2))))) { int _m397 = mark(); synPredMatched397 = true; inputState.guessing++; try { { pathElementStart(); } } catch (RecognitionException pe) { synPredMatched397 = false; } rewind(_m397); inputState.guessing--; } if ( synPredMatched397 ) { nls(); pathElement(prefix); pe_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prefix = pe_AST; } } else { boolean synPredMatched399 = false; if ((((LA(1)==LCURLY||LA(1)==NLS) && (_tokenSet_17.member(LA(2))))&&(lc_stmt == LC_STMT || lc_stmt == LC_INIT))) { int _m399 = mark(); synPredMatched399 = true; inputState.guessing++; try { { nls(); match(LCURLY); } } catch (RecognitionException pe) { synPredMatched399 = false; } rewind(_m399); inputState.guessing--; } if ( synPredMatched399 ) { nlsWarn(); appendedBlock(prefix); apb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prefix = apb_AST; } } else { if ( _cnt400>=1 ) { break _loop400; } else {throw new NoViableAltException(LT(1), getFilename());} } } _cnt400++; } while (true); } if ( inputState.guessing==0 ) { pathChain_AST = (AST)currentAST.root; pathChain_AST = prefix; currentAST.root = pathChain_AST; currentAST.child = pathChain_AST!=null &&pathChain_AST.getFirstChild()!=null ? pathChain_AST.getFirstChild() : pathChain_AST; currentAST.advanceChildToEnd(); } pathChain_AST = (AST)currentAST.root; returnAST = pathChain_AST; } /** A label for an argument is of the form a:b, 'a':b, "a":b, (a):b, etc.. * The labels in (a:b), ('a':b), and ("a":b) are in all ways equivalent, * except that the quotes allow more spellings. * Equivalent dynamically computed labels are (('a'):b) and ("${'a'}":b) * but not ((a):b) or "$a":b, since the latter cases evaluate (a) as a normal identifier. * Bottom line: If you want a truly variable label, use parens and say ((a):b). */ public final void argumentLabel() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST argumentLabel_AST = null; Token id = null; AST id_AST = null; AST kw_AST = null; boolean synPredMatched546 = false; if (((LA(1)==IDENT) && (LA(2)==COLON))) { int _m546 = mark(); synPredMatched546 = true; inputState.guessing++; try { { match(IDENT); } } catch (RecognitionException pe) { synPredMatched546 = false; } rewind(_m546); inputState.guessing--; } if ( synPredMatched546 ) { id = LT(1); id_AST = astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(IDENT); if ( inputState.guessing==0 ) { id_AST.setType(STRING_LITERAL); } argumentLabel_AST = (AST)currentAST.root; } else { boolean synPredMatched548 = false; if (((_tokenSet_96.member(LA(1))) && (LA(2)==COLON))) { int _m548 = mark(); synPredMatched548 = true; inputState.guessing++; try { { keywordPropertyNames(); } } catch (RecognitionException pe) { synPredMatched548 = false; } rewind(_m548); inputState.guessing--; } if ( synPredMatched548 ) { keywordPropertyNames(); kw_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { kw_AST.setType(STRING_LITERAL); } argumentLabel_AST = (AST)currentAST.root; } else if ((_tokenSet_87.member(LA(1))) && (_tokenSet_95.member(LA(2)))) { primaryExpression(); astFactory.addASTChild(currentAST, returnAST); argumentLabel_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = argumentLabel_AST; } public final void multipleAssignment( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST multipleAssignment_AST = null; Token first = cloneToken(LT(1)); AST tmp265_AST = null; tmp265_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp265_AST); match(LPAREN); nls(); listOfVariables(null,null,first); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); AST tmp267_AST = null; tmp267_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp267_AST); match(ASSIGN); nls(); assignmentExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); multipleAssignment_AST = (AST)currentAST.root; returnAST = multipleAssignment_AST; } public final void pathElement( AST prefix ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST pathElement_AST = null; AST ta_AST = null; AST np_AST = null; AST mca_AST = null; AST apb_AST = null; AST ipa_AST = null; Token operator = LT(1); switch ( LA(1)) { case DOT: case SPREAD_DOT: case OPTIONAL_DOT: case MEMBER_POINTER: case NLS: { if ( inputState.guessing==0 ) { pathElement_AST = (AST)currentAST.root; pathElement_AST = prefix; currentAST.root = pathElement_AST; currentAST.child = pathElement_AST!=null &&pathElement_AST.getFirstChild()!=null ? pathElement_AST.getFirstChild() : pathElement_AST; currentAST.advanceChildToEnd(); } { switch ( LA(1)) { case SPREAD_DOT: { match(SPREAD_DOT); break; } case OPTIONAL_DOT: { match(OPTIONAL_DOT); break; } case MEMBER_POINTER: { match(MEMBER_POINTER); break; } case DOT: case NLS: { { nls(); match(DOT); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); { switch ( LA(1)) { case LT: { typeArguments(); ta_AST = (AST)returnAST; break; } case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case AT: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case STRING_CTOR_START: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } namePart(); np_AST = (AST)returnAST; if ( inputState.guessing==0 ) { pathElement_AST = (AST)currentAST.root; pathElement_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(operator.getType(),operator.getText(),prefix,LT(1))).add(prefix).add(ta_AST).add(np_AST)); currentAST.root = pathElement_AST; currentAST.child = pathElement_AST!=null &&pathElement_AST.getFirstChild()!=null ? pathElement_AST.getFirstChild() : pathElement_AST; currentAST.advanceChildToEnd(); } pathElement_AST = (AST)currentAST.root; break; } case LPAREN: { methodCallArgs(prefix); mca_AST = (AST)returnAST; if ( inputState.guessing==0 ) { pathElement_AST = (AST)currentAST.root; pathElement_AST = mca_AST; currentAST.root = pathElement_AST; currentAST.child = pathElement_AST!=null &&pathElement_AST.getFirstChild()!=null ? pathElement_AST.getFirstChild() : pathElement_AST; currentAST.advanceChildToEnd(); } pathElement_AST = (AST)currentAST.root; break; } case LCURLY: { appendedBlock(prefix); apb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { pathElement_AST = (AST)currentAST.root; pathElement_AST = apb_AST; currentAST.root = pathElement_AST; currentAST.child = pathElement_AST!=null &&pathElement_AST.getFirstChild()!=null ? pathElement_AST.getFirstChild() : pathElement_AST; currentAST.advanceChildToEnd(); } pathElement_AST = (AST)currentAST.root; break; } case LBRACK: { indexPropertyArgs(prefix); ipa_AST = (AST)returnAST; if ( inputState.guessing==0 ) { pathElement_AST = (AST)currentAST.root; pathElement_AST = ipa_AST; currentAST.root = pathElement_AST; currentAST.child = pathElement_AST!=null &&pathElement_AST.getFirstChild()!=null ? pathElement_AST.getFirstChild() : pathElement_AST; currentAST.advanceChildToEnd(); } pathElement_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = pathElement_AST; } /** An appended block follows any expression. * If the expression is not a method call, it is given an empty argument list. */ public final void appendedBlock( AST callee ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST appendedBlock_AST = null; AST cb_AST = null; closableBlock(); cb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { appendedBlock_AST = (AST)currentAST.root; // If the callee is itself a call, flatten the AST. if (callee != null && callee.getType() == METHOD_CALL) { appendedBlock_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(METHOD_CALL,"(",callee,LT(1))).add(callee.getFirstChild()).add(cb_AST)); } else { appendedBlock_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(METHOD_CALL,"{",callee,LT(1))).add(callee).add(cb_AST)); } currentAST.root = appendedBlock_AST; currentAST.child = appendedBlock_AST!=null &&appendedBlock_AST.getFirstChild()!=null ? appendedBlock_AST.getFirstChild() : appendedBlock_AST; currentAST.advanceChildToEnd(); } appendedBlock_AST = (AST)currentAST.root; returnAST = appendedBlock_AST; } /** A "path expression" is a name or other primary, possibly qualified by various * forms of dot, and/or followed by various kinds of brackets. * It can be used for value or assigned to, or else further qualified, indexed, or called. * It is called a "path" because it looks like a linear path through a data structure. * Examples: x.y, x?.y, x*.y, x.@y; x[], x[y], x[y,z]; x(), x(y), x(y,z); x{s}; a.b[n].c(x).d{s} * (Compare to a C lvalue, or LeftHandSide in the JLS section 15.26.) * General expressions are built up from path expressions, using operators like '+' and '='. */ public final void pathExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST pathExpression_AST = null; AST pre_AST = null; AST pe_AST = null; AST apb_AST = null; AST prefix = null; primaryExpression(); pre_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prefix = pre_AST; } { _loop407: do { boolean synPredMatched404 = false; if (((_tokenSet_89.member(LA(1))) && (_tokenSet_90.member(LA(2))))) { int _m404 = mark(); synPredMatched404 = true; inputState.guessing++; try { { pathElementStart(); } } catch (RecognitionException pe) { synPredMatched404 = false; } rewind(_m404); inputState.guessing--; } if ( synPredMatched404 ) { nls(); pathElement(prefix); pe_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prefix = pe_AST; } } else { boolean synPredMatched406 = false; if ((((LA(1)==LCURLY||LA(1)==NLS) && (_tokenSet_17.member(LA(2))))&&(lc_stmt == LC_STMT || lc_stmt == LC_INIT))) { int _m406 = mark(); synPredMatched406 = true; inputState.guessing++; try { { nls(); match(LCURLY); } } catch (RecognitionException pe) { synPredMatched406 = false; } rewind(_m406); inputState.guessing--; } if ( synPredMatched406 ) { nlsWarn(); appendedBlock(prefix); apb_AST = (AST)returnAST; if ( inputState.guessing==0 ) { prefix = apb_AST; } } else { break _loop407; } } } while (true); } if ( inputState.guessing==0 ) { pathExpression_AST = (AST)currentAST.root; pathExpression_AST = prefix; lastPathExpression = pathExpression_AST; currentAST.root = pathExpression_AST; currentAST.child = pathExpression_AST!=null &&pathExpression_AST.getFirstChild()!=null ? pathExpression_AST.getFirstChild() : pathExpression_AST; currentAST.advanceChildToEnd(); } pathExpression_AST = (AST)currentAST.root; returnAST = pathExpression_AST; } /** This is the grammar for what can follow a dot: x.a, x.@a, x.&a, x.'a', etc. * Note: typeArguments is handled by the caller of namePart. */ public final void namePart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST namePart_AST = null; Token ats = null; AST ats_AST = null; Token sl = null; AST sl_AST = null; Token first = LT(1); { switch ( LA(1)) { case AT: { ats = LT(1); ats_AST = astFactory.create(ats); astFactory.makeASTRoot(currentAST, ats_AST); match(AT); if ( inputState.guessing==0 ) { ats_AST.setType(SELECT_SLOT); } break; } case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: case STRING_CTOR_START: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case IDENT: { AST tmp272_AST = null; tmp272_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp272_AST); match(IDENT); break; } case STRING_LITERAL: { sl = LT(1); sl_AST = astFactory.create(sl); astFactory.addASTChild(currentAST, sl_AST); match(STRING_LITERAL); if ( inputState.guessing==0 ) { sl_AST.setType(IDENT); } break; } case LPAREN: case STRING_CTOR_START: { dynamicMemberName(); astFactory.addASTChild(currentAST, returnAST); break; } case LCURLY: { openBlock(); astFactory.addASTChild(currentAST, returnAST); break; } case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: { keywordPropertyNames(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } namePart_AST = (AST)currentAST.root; returnAST = namePart_AST; } /** An expression may be followed by one or both of (...) and {...}. * Note: If either is (...) or {...} present, it is a method call. * The {...} is appended to the argument list, and matches a formal of type Closure. * If there is no method member, a property (or field) is used instead, and must itself be callable. *

      * If the methodCallArgs are absent, it is a property reference. * If there is no property, it is treated as a field reference, but never a method reference. *

      * Arguments in the (...) can be labeled, and the appended block can be labeled also. * If there is a mix of unlabeled and labeled arguments, * all the labeled arguments must follow the unlabeled arguments, * except that the closure (labeled or not) is always a separate final argument. * Labeled arguments are collected up and passed as a single argument to a formal of type Map. *

      * Therefore, f(x,y, a:p, b:q) {s} is equivalent in all ways to f(x,y, [a:p,b:q], {s}). * Spread arguments of sequence type count as unlabeled arguments, * while spread arguments of map type count as labeled arguments. * (This distinction must sometimes be checked dynamically.) * * A plain unlabeled argument is allowed to match a trailing Map or Closure argument: * f(x, a:p) {s} === f(*[ x, [a:p], {s} ]) */ public final void methodCallArgs( AST callee ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST methodCallArgs_AST = null; AST al_AST = null; match(LPAREN); argList(); al_AST = (AST)returnAST; match(RPAREN); if ( inputState.guessing==0 ) { methodCallArgs_AST = (AST)currentAST.root; if (callee != null && callee.getFirstChild() != null) { //method call like obj.method() methodCallArgs_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(METHOD_CALL,"(",callee.getFirstChild(),LT(1))).add(callee).add(al_AST)); } else { //method call like method() or new Expr(), in the latter case "callee" is null methodCallArgs_AST = (AST)astFactory.make( (new ASTArray(3)).add(create(METHOD_CALL,"(",callee,LT(1))).add(callee).add(al_AST)); } currentAST.root = methodCallArgs_AST; currentAST.child = methodCallArgs_AST!=null &&methodCallArgs_AST.getFirstChild()!=null ? methodCallArgs_AST.getFirstChild() : methodCallArgs_AST; currentAST.advanceChildToEnd(); } methodCallArgs_AST = (AST)currentAST.root; returnAST = methodCallArgs_AST; } /** An expression may be followed by [...]. * Unlike Java, these brackets may contain a general argument list, * which is passed to the array element operator, which can make of it what it wants. * The brackets may also be empty, as in T[]. This is how Groovy names array types. *

      Returned AST is [INDEX_OP, indexee, ELIST]. */ public final void indexPropertyArgs( AST indexee ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST indexPropertyArgs_AST = null; Token lb = null; AST lb_AST = null; AST al_AST = null; lb = LT(1); lb_AST = astFactory.create(lb); astFactory.addASTChild(currentAST, lb_AST); match(LBRACK); argList(); al_AST = (AST)returnAST; match(RBRACK); if ( inputState.guessing==0 ) { indexPropertyArgs_AST = (AST)currentAST.root; if (indexee != null && indexee.getFirstChild() != null) { //expression like obj.index[] indexPropertyArgs_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(INDEX_OP,"INDEX_OP",indexee.getFirstChild(),LT(1))).add(lb_AST).add(indexee).add(al_AST)); } else { //expression like obj[] indexPropertyArgs_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(INDEX_OP,"INDEX_OP",indexee,LT(1))).add(lb_AST).add(indexee).add(al_AST)); } currentAST.root = indexPropertyArgs_AST; currentAST.child = indexPropertyArgs_AST!=null &&indexPropertyArgs_AST.getFirstChild()!=null ? indexPropertyArgs_AST.getFirstChild() : indexPropertyArgs_AST; currentAST.advanceChildToEnd(); } indexPropertyArgs_AST = (AST)currentAST.root; returnAST = indexPropertyArgs_AST; } /** If a dot is followed by a parenthesized or quoted expression, the member is computed dynamically, * and the member selection is done only at runtime. This forces a statically unchecked member access. */ public final void dynamicMemberName() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST dynamicMemberName_AST = null; AST pe_AST = null; Token first = LT(1); { switch ( LA(1)) { case LPAREN: { parenthesizedExpression(); pe_AST = (AST)returnAST; if ( inputState.guessing==0 ) { dynamicMemberName_AST = (AST)currentAST.root; dynamicMemberName_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(EXPR,"EXPR",first,LT(1))).add(pe_AST)); currentAST.root = dynamicMemberName_AST; currentAST.child = dynamicMemberName_AST!=null &&dynamicMemberName_AST.getFirstChild()!=null ? dynamicMemberName_AST.getFirstChild() : dynamicMemberName_AST; currentAST.advanceChildToEnd(); } break; } case STRING_CTOR_START: { stringConstructorExpression(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { dynamicMemberName_AST = (AST)currentAST.root; dynamicMemberName_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(DYNAMIC_MEMBER,"DYNAMIC_MEMBER",first,LT(1))).add(dynamicMemberName_AST)); currentAST.root = dynamicMemberName_AST; currentAST.child = dynamicMemberName_AST!=null &&dynamicMemberName_AST.getFirstChild()!=null ? dynamicMemberName_AST.getFirstChild() : dynamicMemberName_AST; currentAST.advanceChildToEnd(); } dynamicMemberName_AST = (AST)currentAST.root; returnAST = dynamicMemberName_AST; } public final void parenthesizedExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST parenthesizedExpression_AST = null; Token first = LT(1); Token declaration = null; boolean hasClosureList=false; boolean firstContainsDeclaration=false; boolean sce=false; match(LPAREN); if ( inputState.guessing==0 ) { declaration=LT(1); } firstContainsDeclaration=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); { _loop507: do { if ((LA(1)==SEMI)) { match(SEMI); if ( inputState.guessing==0 ) { hasClosureList=true; } { switch ( LA(1)) { case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { sce=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); break; } case RPAREN: case SEMI: { if ( inputState.guessing==0 ) { astFactory.addASTChild(currentAST,astFactory.create(EMPTY_STAT, "EMPTY_STAT")); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop507; } } while (true); } if ( inputState.guessing==0 ) { if (firstContainsDeclaration && !hasClosureList) throw new NoViableAltException(declaration, getFilename()); } match(RPAREN); if ( inputState.guessing==0 ) { parenthesizedExpression_AST = (AST)currentAST.root; if (hasClosureList) { parenthesizedExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(CLOSURE_LIST,"CLOSURE_LIST",first,LT(1))).add(parenthesizedExpression_AST)); } currentAST.root = parenthesizedExpression_AST; currentAST.child = parenthesizedExpression_AST!=null &&parenthesizedExpression_AST.getFirstChild()!=null ? parenthesizedExpression_AST.getFirstChild() : parenthesizedExpression_AST; currentAST.advanceChildToEnd(); } parenthesizedExpression_AST = (AST)currentAST.root; returnAST = parenthesizedExpression_AST; } public final void stringConstructorExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST stringConstructorExpression_AST = null; Token cs = null; AST cs_AST = null; Token cm = null; AST cm_AST = null; Token ce = null; AST ce_AST = null; Token first = LT(1); cs = LT(1); cs_AST = astFactory.create(cs); astFactory.addASTChild(currentAST, cs_AST); match(STRING_CTOR_START); if ( inputState.guessing==0 ) { cs_AST.setType(STRING_LITERAL); } stringConstructorValuePart(); astFactory.addASTChild(currentAST, returnAST); { _loop517: do { if ((LA(1)==STRING_CTOR_MIDDLE)) { cm = LT(1); cm_AST = astFactory.create(cm); astFactory.addASTChild(currentAST, cm_AST); match(STRING_CTOR_MIDDLE); if ( inputState.guessing==0 ) { cm_AST.setType(STRING_LITERAL); } stringConstructorValuePart(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop517; } } while (true); } ce = LT(1); ce_AST = astFactory.create(ce); astFactory.addASTChild(currentAST, ce_AST); match(STRING_CTOR_END); if ( inputState.guessing==0 ) { stringConstructorExpression_AST = (AST)currentAST.root; ce_AST.setType(STRING_LITERAL); stringConstructorExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(STRING_CONSTRUCTOR,"STRING_CONSTRUCTOR",first,LT(1))).add(stringConstructorExpression_AST)); currentAST.root = stringConstructorExpression_AST; currentAST.child = stringConstructorExpression_AST!=null &&stringConstructorExpression_AST.getFirstChild()!=null ? stringConstructorExpression_AST.getFirstChild() : stringConstructorExpression_AST; currentAST.advanceChildToEnd(); } stringConstructorExpression_AST = (AST)currentAST.root; returnAST = stringConstructorExpression_AST; } public final void logicalOrExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST logicalOrExpression_AST = null; logicalAndExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop433: do { if ((LA(1)==LOR)) { AST tmp279_AST = null; tmp279_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp279_AST); match(LOR); nls(); logicalAndExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop433; } } while (true); } logicalOrExpression_AST = (AST)currentAST.root; returnAST = logicalOrExpression_AST; } public final void logicalAndExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST logicalAndExpression_AST = null; inclusiveOrExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop436: do { if ((LA(1)==LAND)) { AST tmp280_AST = null; tmp280_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp280_AST); match(LAND); nls(); inclusiveOrExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop436; } } while (true); } logicalAndExpression_AST = (AST)currentAST.root; returnAST = logicalAndExpression_AST; } public final void inclusiveOrExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST inclusiveOrExpression_AST = null; exclusiveOrExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop439: do { if ((LA(1)==BOR)) { AST tmp281_AST = null; tmp281_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp281_AST); match(BOR); nls(); exclusiveOrExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop439; } } while (true); } inclusiveOrExpression_AST = (AST)currentAST.root; returnAST = inclusiveOrExpression_AST; } public final void exclusiveOrExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST exclusiveOrExpression_AST = null; andExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop442: do { if ((LA(1)==BXOR)) { AST tmp282_AST = null; tmp282_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp282_AST); match(BXOR); nls(); andExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop442; } } while (true); } exclusiveOrExpression_AST = (AST)currentAST.root; returnAST = exclusiveOrExpression_AST; } public final void andExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST andExpression_AST = null; regexExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop445: do { if ((LA(1)==BAND)) { AST tmp283_AST = null; tmp283_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp283_AST); match(BAND); nls(); regexExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop445; } } while (true); } andExpression_AST = (AST)currentAST.root; returnAST = andExpression_AST; } public final void regexExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST regexExpression_AST = null; equalityExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop449: do { if ((LA(1)==REGEX_FIND||LA(1)==REGEX_MATCH)) { { switch ( LA(1)) { case REGEX_FIND: { AST tmp284_AST = null; tmp284_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp284_AST); match(REGEX_FIND); break; } case REGEX_MATCH: { AST tmp285_AST = null; tmp285_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp285_AST); match(REGEX_MATCH); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); equalityExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop449; } } while (true); } regexExpression_AST = (AST)currentAST.root; returnAST = regexExpression_AST; } public final void equalityExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST equalityExpression_AST = null; relationalExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop453: do { if (((LA(1) >= NOT_EQUAL && LA(1) <= COMPARE_TO))) { { switch ( LA(1)) { case NOT_EQUAL: { AST tmp286_AST = null; tmp286_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp286_AST); match(NOT_EQUAL); break; } case EQUAL: { AST tmp287_AST = null; tmp287_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp287_AST); match(EQUAL); break; } case IDENTICAL: { AST tmp288_AST = null; tmp288_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp288_AST); match(IDENTICAL); break; } case NOT_IDENTICAL: { AST tmp289_AST = null; tmp289_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp289_AST); match(NOT_IDENTICAL); break; } case COMPARE_TO: { AST tmp290_AST = null; tmp290_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp290_AST); match(COMPARE_TO); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); relationalExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop453; } } while (true); } equalityExpression_AST = (AST)currentAST.root; returnAST = equalityExpression_AST; } public final void relationalExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST relationalExpression_AST = null; shiftExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { if ((_tokenSet_97.member(LA(1))) && (_tokenSet_81.member(LA(2)))) { { { switch ( LA(1)) { case LT: { AST tmp291_AST = null; tmp291_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp291_AST); match(LT); break; } case GT: { AST tmp292_AST = null; tmp292_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp292_AST); match(GT); break; } case LE: { AST tmp293_AST = null; tmp293_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp293_AST); match(LE); break; } case GE: { AST tmp294_AST = null; tmp294_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp294_AST); match(GE); break; } case LITERAL_in: { AST tmp295_AST = null; tmp295_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp295_AST); match(LITERAL_in); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); shiftExpression(0); astFactory.addASTChild(currentAST, returnAST); } } else if ((LA(1)==LITERAL_instanceof) && (_tokenSet_98.member(LA(2)))) { AST tmp296_AST = null; tmp296_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp296_AST); match(LITERAL_instanceof); nls(); typeSpec(true); astFactory.addASTChild(currentAST, returnAST); } else if ((LA(1)==LITERAL_as) && (_tokenSet_98.member(LA(2)))) { AST tmp297_AST = null; tmp297_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp297_AST); match(LITERAL_as); nls(); typeSpec(true); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_99.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } relationalExpression_AST = (AST)currentAST.root; returnAST = relationalExpression_AST; } public final void additiveExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST additiveExpression_AST = null; multiplicativeExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop466: do { if ((LA(1)==PLUS||LA(1)==MINUS) && (_tokenSet_81.member(LA(2)))) { { switch ( LA(1)) { case PLUS: { AST tmp298_AST = null; tmp298_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp298_AST); match(PLUS); break; } case MINUS: { AST tmp299_AST = null; tmp299_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp299_AST); match(MINUS); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); multiplicativeExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop466; } } while (true); } additiveExpression_AST = (AST)currentAST.root; returnAST = additiveExpression_AST; } public final void multiplicativeExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST multiplicativeExpression_AST = null; switch ( LA(1)) { case INC: { { AST tmp300_AST = null; tmp300_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp300_AST); match(INC); nls(); powerExpressionNotPlusMinus(0); astFactory.addASTChild(currentAST, returnAST); { _loop471: do { if ((_tokenSet_100.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp301_AST = null; tmp301_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp301_AST); match(STAR); break; } case DIV: { AST tmp302_AST = null; tmp302_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp302_AST); match(DIV); break; } case MOD: { AST tmp303_AST = null; tmp303_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp303_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); powerExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop471; } } while (true); } } multiplicativeExpression_AST = (AST)currentAST.root; break; } case DEC: { { AST tmp304_AST = null; tmp304_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp304_AST); match(DEC); nls(); powerExpressionNotPlusMinus(0); astFactory.addASTChild(currentAST, returnAST); { _loop475: do { if ((_tokenSet_100.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp305_AST = null; tmp305_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp305_AST); match(STAR); break; } case DIV: { AST tmp306_AST = null; tmp306_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp306_AST); match(DIV); break; } case MOD: { AST tmp307_AST = null; tmp307_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp307_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); powerExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop475; } } while (true); } } multiplicativeExpression_AST = (AST)currentAST.root; break; } case MINUS: { { AST tmp308_AST = null; tmp308_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp308_AST); match(MINUS); if ( inputState.guessing==0 ) { tmp308_AST.setType(UNARY_MINUS); } nls(); powerExpressionNotPlusMinus(0); astFactory.addASTChild(currentAST, returnAST); { _loop479: do { if ((_tokenSet_100.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp309_AST = null; tmp309_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp309_AST); match(STAR); break; } case DIV: { AST tmp310_AST = null; tmp310_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp310_AST); match(DIV); break; } case MOD: { AST tmp311_AST = null; tmp311_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp311_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); powerExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop479; } } while (true); } } multiplicativeExpression_AST = (AST)currentAST.root; break; } case PLUS: { { AST tmp312_AST = null; tmp312_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp312_AST); match(PLUS); if ( inputState.guessing==0 ) { tmp312_AST.setType(UNARY_PLUS); } nls(); powerExpressionNotPlusMinus(0); astFactory.addASTChild(currentAST, returnAST); { _loop483: do { if ((_tokenSet_100.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp313_AST = null; tmp313_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp313_AST); match(STAR); break; } case DIV: { AST tmp314_AST = null; tmp314_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp314_AST); match(DIV); break; } case MOD: { AST tmp315_AST = null; tmp315_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp315_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); powerExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop483; } } while (true); } } multiplicativeExpression_AST = (AST)currentAST.root; break; } case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { { powerExpressionNotPlusMinus(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop487: do { if ((_tokenSet_100.member(LA(1)))) { { switch ( LA(1)) { case STAR: { AST tmp316_AST = null; tmp316_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp316_AST); match(STAR); break; } case DIV: { AST tmp317_AST = null; tmp317_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp317_AST); match(DIV); break; } case MOD: { AST tmp318_AST = null; tmp318_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp318_AST); match(MOD); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } nls(); powerExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop487; } } while (true); } } multiplicativeExpression_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = multiplicativeExpression_AST; } public final void powerExpressionNotPlusMinus( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST powerExpressionNotPlusMinus_AST = null; unaryExpressionNotPlusMinus(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop493: do { if ((LA(1)==STAR_STAR)) { AST tmp319_AST = null; tmp319_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp319_AST); match(STAR_STAR); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop493; } } while (true); } powerExpressionNotPlusMinus_AST = (AST)currentAST.root; returnAST = powerExpressionNotPlusMinus_AST; } public final void powerExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST powerExpression_AST = null; unaryExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { _loop490: do { if ((LA(1)==STAR_STAR)) { AST tmp320_AST = null; tmp320_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp320_AST); match(STAR_STAR); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { break _loop490; } } while (true); } powerExpression_AST = (AST)currentAST.root; returnAST = powerExpression_AST; } public final void unaryExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST unaryExpression_AST = null; switch ( LA(1)) { case INC: { AST tmp321_AST = null; tmp321_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp321_AST); match(INC); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case DEC: { AST tmp322_AST = null; tmp322_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp322_AST); match(DEC); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case MINUS: { AST tmp323_AST = null; tmp323_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp323_AST); match(MINUS); if ( inputState.guessing==0 ) { tmp323_AST.setType(UNARY_MINUS); } nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case PLUS: { AST tmp324_AST = null; tmp324_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp324_AST); match(PLUS); if ( inputState.guessing==0 ) { tmp324_AST.setType(UNARY_PLUS); } nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { unaryExpressionNotPlusMinus(lc_stmt); astFactory.addASTChild(currentAST, returnAST); unaryExpression_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = unaryExpression_AST; } public final void unaryExpressionNotPlusMinus( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST unaryExpressionNotPlusMinus_AST = null; Token lpb = null; AST lpb_AST = null; Token lp = null; AST lp_AST = null; switch ( LA(1)) { case BNOT: { AST tmp325_AST = null; tmp325_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp325_AST); match(BNOT); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } case LNOT: { AST tmp326_AST = null; tmp326_AST = astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp326_AST); match(LNOT); nls(); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { { boolean synPredMatched498 = false; if (((LA(1)==LPAREN) && ((LA(2) >= LITERAL_void && LA(2) <= LITERAL_double)))) { int _m498 = mark(); synPredMatched498 = true; inputState.guessing++; try { { match(LPAREN); builtInTypeSpec(true); match(RPAREN); unaryExpression(0); } } catch (RecognitionException pe) { synPredMatched498 = false; } rewind(_m498); inputState.guessing--; } if ( synPredMatched498 ) { lpb = LT(1); lpb_AST = astFactory.create(lpb); astFactory.makeASTRoot(currentAST, lpb_AST); match(LPAREN); if ( inputState.guessing==0 ) { lpb_AST.setType(TYPECAST); } builtInTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); unaryExpression(0); astFactory.addASTChild(currentAST, returnAST); } else { boolean synPredMatched500 = false; if (((LA(1)==LPAREN) && (LA(2)==IDENT))) { int _m500 = mark(); synPredMatched500 = true; inputState.guessing++; try { { match(LPAREN); classTypeSpec(true); match(RPAREN); unaryExpressionNotPlusMinus(0); } } catch (RecognitionException pe) { synPredMatched500 = false; } rewind(_m500); inputState.guessing--; } if ( synPredMatched500 ) { lp = LT(1); lp_AST = astFactory.create(lp); astFactory.makeASTRoot(currentAST, lp_AST); match(LPAREN); if ( inputState.guessing==0 ) { lp_AST.setType(TYPECAST); } classTypeSpec(true); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); unaryExpressionNotPlusMinus(0); astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_87.member(LA(1))) && (_tokenSet_37.member(LA(2)))) { postfixExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); } else { throw new NoViableAltException(LT(1), getFilename()); } } } unaryExpressionNotPlusMinus_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = unaryExpressionNotPlusMinus_AST; } public final void postfixExpression( int lc_stmt ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST postfixExpression_AST = null; Token in = null; AST in_AST = null; Token de = null; AST de_AST = null; pathExpression(lc_stmt); astFactory.addASTChild(currentAST, returnAST); { if ((LA(1)==INC) && (_tokenSet_101.member(LA(2)))) { in = LT(1); in_AST = astFactory.create(in); astFactory.makeASTRoot(currentAST, in_AST); match(INC); if ( inputState.guessing==0 ) { in_AST.setType(POST_INC); } } else if ((LA(1)==DEC) && (_tokenSet_101.member(LA(2)))) { de = LT(1); de_AST = astFactory.create(de); astFactory.makeASTRoot(currentAST, de_AST); match(DEC); if ( inputState.guessing==0 ) { de_AST.setType(POST_DEC); } } else if ((_tokenSet_101.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } postfixExpression_AST = (AST)currentAST.root; returnAST = postfixExpression_AST; } /** Numeric, string, regexp, boolean, or null constant. */ public final void constant() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constant_AST = null; switch ( LA(1)) { case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { constantNumber(); astFactory.addASTChild(currentAST, returnAST); constant_AST = (AST)currentAST.root; break; } case STRING_LITERAL: { AST tmp329_AST = null; tmp329_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp329_AST); match(STRING_LITERAL); constant_AST = (AST)currentAST.root; break; } case LITERAL_true: { AST tmp330_AST = null; tmp330_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp330_AST); match(LITERAL_true); constant_AST = (AST)currentAST.root; break; } case LITERAL_false: { AST tmp331_AST = null; tmp331_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp331_AST); match(LITERAL_false); constant_AST = (AST)currentAST.root; break; } case LITERAL_null: { AST tmp332_AST = null; tmp332_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp332_AST); match(LITERAL_null); constant_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = constant_AST; } /** object instantiation. * Trees are built as illustrated by the following input/tree pairs: * * new T() * * new * | * T -- ELIST * | * arg1 -- arg2 -- .. -- argn * * new int[] * * new * | * int -- ARRAY_DECLARATOR * * new int[] {1,2} * * new * | * int -- ARRAY_DECLARATOR -- ARRAY_INIT * | * EXPR -- EXPR * | | * 1 2 * * new int[3] * new * | * int -- ARRAY_DECLARATOR * | * EXPR * | * 3 * * new int[1][2] * * new * | * int -- ARRAY_DECLARATOR * | * ARRAY_DECLARATOR -- EXPR * | | * EXPR 1 * | * 2 * */ public final void newExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST newExpression_AST = null; AST ta_AST = null; AST t_AST = null; AST mca_AST = null; AST cb_AST = null; AST ad_AST = null; Token first = LT(1); match(LITERAL_new); nls(); { switch ( LA(1)) { case LT: { typeArguments(); ta_AST = (AST)returnAST; break; } case IDENT: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } type(); t_AST = (AST)returnAST; { switch ( LA(1)) { case LPAREN: case NLS: { nls(); methodCallArgs(null); mca_AST = (AST)returnAST; { if ((LA(1)==LCURLY) && (_tokenSet_51.member(LA(2)))) { classBlock(); cb_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); } else if ((_tokenSet_102.member(LA(1))) && (_tokenSet_71.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } if ( inputState.guessing==0 ) { newExpression_AST = (AST)currentAST.root; mca_AST = mca_AST.getFirstChild(); newExpression_AST = (AST)astFactory.make( (new ASTArray(5)).add(create(LITERAL_new,"new",first,LT(1))).add(ta_AST).add(t_AST).add(mca_AST).add(cb_AST)); currentAST.root = newExpression_AST; currentAST.child = newExpression_AST!=null &&newExpression_AST.getFirstChild()!=null ? newExpression_AST.getFirstChild() : newExpression_AST; currentAST.advanceChildToEnd(); } break; } case LBRACK: { newArrayDeclarator(); ad_AST = (AST)returnAST; if ( inputState.guessing==0 ) { newExpression_AST = (AST)currentAST.root; newExpression_AST = (AST)astFactory.make( (new ASTArray(4)).add(create(LITERAL_new,"new",first,LT(1))).add(ta_AST).add(t_AST).add(ad_AST)); currentAST.root = newExpression_AST; currentAST.child = newExpression_AST!=null &&newExpression_AST.getFirstChild()!=null ? newExpression_AST.getFirstChild() : newExpression_AST; currentAST.advanceChildToEnd(); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } newExpression_AST = (AST)currentAST.root; returnAST = newExpression_AST; } public final void closableBlockConstructorExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST closableBlockConstructorExpression_AST = null; closableBlock(); astFactory.addASTChild(currentAST, returnAST); closableBlockConstructorExpression_AST = (AST)currentAST.root; returnAST = closableBlockConstructorExpression_AST; } /** * A list constructor is a argument list enclosed in square brackets, without labels. * Any argument can be decorated with a spread operator (*x), but not a label (a:x). * Examples: [], [1], [1,2], [1,*l1,2], [*l1,*l2]. * (The l1, l2 must be a sequence or null.) *

      * A map constructor is an argument list enclosed in square brackets, with labels everywhere, * except on spread arguments, which stand for whole maps spliced in. * A colon alone between the brackets also forces the expression to be an empty map constructor. * Examples: [:], [a:1], [a:1,b:2], [a:1,*:m1,b:2], [*:m1,*:m2] * (The m1, m2 must be a map or null.) * Values associated with identical keys overwrite from left to right: * [a:1,a:2] === [a:2] *

      * Some malformed constructor expressions are not detected in the parser, but in a post-pass. * Bad examples: [1,b:2], [a:1,2], [:1]. * (Note that method call arguments, by contrast, can be a mix of keyworded and non-keyworded arguments.) */ public final void listOrMapConstructorExpression() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST listOrMapConstructorExpression_AST = null; Token lcon = null; AST lcon_AST = null; AST args_AST = null; Token emcon = null; AST emcon_AST = null; boolean hasLabels = false; if ((LA(1)==LBRACK) && (_tokenSet_103.member(LA(2)))) { lcon = LT(1); lcon_AST = astFactory.create(lcon); match(LBRACK); argList(); args_AST = (AST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { hasLabels |= argListHasLabels; } match(RBRACK); if ( inputState.guessing==0 ) { listOrMapConstructorExpression_AST = (AST)currentAST.root; int type = hasLabels ? MAP_CONSTRUCTOR : LIST_CONSTRUCTOR; listOrMapConstructorExpression_AST = (AST)astFactory.make( (new ASTArray(2)).add(create(type,"[",lcon_AST,LT(1))).add(args_AST)); currentAST.root = listOrMapConstructorExpression_AST; currentAST.child = listOrMapConstructorExpression_AST!=null &&listOrMapConstructorExpression_AST.getFirstChild()!=null ? listOrMapConstructorExpression_AST.getFirstChild() : listOrMapConstructorExpression_AST; currentAST.advanceChildToEnd(); } listOrMapConstructorExpression_AST = (AST)currentAST.root; } else if ((LA(1)==LBRACK) && (LA(2)==COLON)) { emcon = LT(1); emcon_AST = astFactory.create(emcon); astFactory.makeASTRoot(currentAST, emcon_AST); match(LBRACK); match(COLON); match(RBRACK); if ( inputState.guessing==0 ) { emcon_AST.setType(MAP_CONSTRUCTOR); } listOrMapConstructorExpression_AST = (AST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } returnAST = listOrMapConstructorExpression_AST; } public final void stringConstructorValuePart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST stringConstructorValuePart_AST = null; { switch ( LA(1)) { case IDENT: { identifier(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_this: { AST tmp337_AST = null; tmp337_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp337_AST); match(LITERAL_this); break; } case LITERAL_super: { AST tmp338_AST = null; tmp338_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp338_AST); match(LITERAL_super); break; } case LCURLY: { openOrClosableBlock(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } stringConstructorValuePart_AST = (AST)currentAST.root; returnAST = stringConstructorValuePart_AST; } public final void newArrayDeclarator() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST newArrayDeclarator_AST = null; Token lb = null; AST lb_AST = null; { int _cnt556=0; _loop556: do { if ((LA(1)==LBRACK) && (_tokenSet_104.member(LA(2)))) { lb = LT(1); lb_AST = astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(ARRAY_DECLARATOR); } { switch ( LA(1)) { case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LCURLY: case LITERAL_this: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { expression(0); astFactory.addASTChild(currentAST, returnAST); break; } case RBRACK: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RBRACK); } else { if ( _cnt556>=1 ) { break _loop556; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt556++; } while (true); } newArrayDeclarator_AST = (AST)currentAST.root; returnAST = newArrayDeclarator_AST; } /** A single argument in (...) or [...]. Corresponds to to a method or closure parameter. * May be labeled. May be modified by the spread operator '*' ('*:' for keywords). */ public final byte argument() throws RecognitionException, TokenStreamException { byte hasLabelOrSpread = 0; returnAST = null; ASTPair currentAST = new ASTPair(); AST argument_AST = null; Token c = null; AST c_AST = null; Token sp = null; AST sp_AST = null; boolean sce=false; { boolean synPredMatched542 = false; if (((_tokenSet_94.member(LA(1))) && (_tokenSet_95.member(LA(2))))) { int _m542 = mark(); synPredMatched542 = true; inputState.guessing++; try { { argumentLabelStart(); } } catch (RecognitionException pe) { synPredMatched542 = false; } rewind(_m542); inputState.guessing--; } if ( synPredMatched542 ) { argumentLabel(); astFactory.addASTChild(currentAST, returnAST); c = LT(1); c_AST = astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(LABELED_ARG); } if ( inputState.guessing==0 ) { hasLabelOrSpread |= 1; } } else if ((LA(1)==STAR)) { sp = LT(1); sp_AST = astFactory.create(sp); astFactory.makeASTRoot(currentAST, sp_AST); match(STAR); if ( inputState.guessing==0 ) { sp_AST.setType(SPREAD_ARG); } if ( inputState.guessing==0 ) { hasLabelOrSpread |= 2; } { switch ( LA(1)) { case COLON: { match(COLON); if ( inputState.guessing==0 ) { sp_AST.setType(SPREAD_MAP_ARG); } if ( inputState.guessing==0 ) { hasLabelOrSpread |= 1; } break; } case FINAL: case ABSTRACT: case STRICTFP: case LITERAL_static: case LITERAL_def: case LBRACK: case IDENT: case STRING_LITERAL: case LPAREN: case AT: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LCURLY: case LITERAL_this: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case PLUS: case MINUS: case LITERAL_false: case LITERAL_new: case LITERAL_null: case LITERAL_true: case INC: case DEC: case BNOT: case LNOT: case STRING_CTOR_START: case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((_tokenSet_83.member(LA(1))) && (_tokenSet_105.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } sce=strictContextExpression(true); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { require(LA(1) != COLON, "illegal colon after argument expression", "a complex label expression before a colon must be parenthesized"); } argument_AST = (AST)currentAST.root; returnAST = argument_AST; return hasLabelOrSpread; } /** For lookahead only. Fast approximate parse of an argumentLabel followed by a colon. */ public final void argumentLabelStart() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST argumentLabelStart_AST = null; { switch ( LA(1)) { case IDENT: { AST tmp341_AST = null; tmp341_AST = astFactory.create(LT(1)); match(IDENT); break; } case FINAL: case ABSTRACT: case UNUSED_GOTO: case UNUSED_CONST: case UNUSED_DO: case STRICTFP: case LITERAL_package: case LITERAL_import: case LITERAL_static: case LITERAL_def: case LITERAL_class: case LITERAL_interface: case LITERAL_enum: case LITERAL_extends: case LITERAL_super: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_as: case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: case LITERAL_synchronized: case LITERAL_volatile: case LITERAL_default: case LITERAL_throws: case LITERAL_implements: case LITERAL_this: case LITERAL_if: case LITERAL_else: case LITERAL_while: case LITERAL_switch: case LITERAL_for: case LITERAL_in: case LITERAL_return: case LITERAL_break: case LITERAL_continue: case LITERAL_throw: case LITERAL_assert: case LITERAL_case: case LITERAL_try: case LITERAL_finally: case LITERAL_catch: case LITERAL_false: case LITERAL_instanceof: case LITERAL_new: case LITERAL_null: case LITERAL_true: { keywordPropertyNames(); break; } case NUM_INT: case NUM_FLOAT: case NUM_LONG: case NUM_DOUBLE: case NUM_BIG_INT: case NUM_BIG_DECIMAL: { constantNumber(); break; } case STRING_LITERAL: { AST tmp342_AST = null; tmp342_AST = astFactory.create(LT(1)); match(STRING_LITERAL); break; } case LBRACK: case LPAREN: case LCURLY: case STRING_CTOR_START: { balancedBrackets(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } AST tmp343_AST = null; tmp343_AST = astFactory.create(LT(1)); match(COLON); returnAST = argumentLabelStart_AST; } /** Numeric constant. */ public final void constantNumber() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST constantNumber_AST = null; switch ( LA(1)) { case NUM_INT: { AST tmp344_AST = null; tmp344_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp344_AST); match(NUM_INT); constantNumber_AST = (AST)currentAST.root; break; } case NUM_FLOAT: { AST tmp345_AST = null; tmp345_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp345_AST); match(NUM_FLOAT); constantNumber_AST = (AST)currentAST.root; break; } case NUM_LONG: { AST tmp346_AST = null; tmp346_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp346_AST); match(NUM_LONG); constantNumber_AST = (AST)currentAST.root; break; } case NUM_DOUBLE: { AST tmp347_AST = null; tmp347_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp347_AST); match(NUM_DOUBLE); constantNumber_AST = (AST)currentAST.root; break; } case NUM_BIG_INT: { AST tmp348_AST = null; tmp348_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp348_AST); match(NUM_BIG_INT); constantNumber_AST = (AST)currentAST.root; break; } case NUM_BIG_DECIMAL: { AST tmp349_AST = null; tmp349_AST = astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp349_AST); match(NUM_BIG_DECIMAL); constantNumber_AST = (AST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = constantNumber_AST; } /** Fast lookahead across balanced brackets of all sorts. */ public final void balancedBrackets() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); AST balancedBrackets_AST = null; switch ( LA(1)) { case LPAREN: { AST tmp350_AST = null; tmp350_AST = astFactory.create(LT(1)); match(LPAREN); balancedTokens(); AST tmp351_AST = null; tmp351_AST = astFactory.create(LT(1)); match(RPAREN); break; } case LBRACK: { AST tmp352_AST = null; tmp352_AST = astFactory.create(LT(1)); match(LBRACK); balancedTokens(); AST tmp353_AST = null; tmp353_AST = astFactory.create(LT(1)); match(RBRACK); break; } case LCURLY: { AST tmp354_AST = null; tmp354_AST = astFactory.create(LT(1)); match(LCURLY); balancedTokens(); AST tmp355_AST = null; tmp355_AST = astFactory.create(LT(1)); match(RCURLY); break; } case STRING_CTOR_START: { AST tmp356_AST = null; tmp356_AST = astFactory.create(LT(1)); match(STRING_CTOR_START); balancedTokens(); AST tmp357_AST = null; tmp357_AST = astFactory.create(LT(1)); match(STRING_CTOR_END); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } returnAST = balancedBrackets_AST; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "BLOCK", "MODIFIERS", "OBJBLOCK", "SLIST", "METHOD_DEF", "VARIABLE_DEF", "INSTANCE_INIT", "STATIC_INIT", "TYPE", "CLASS_DEF", "INTERFACE_DEF", "PACKAGE_DEF", "ARRAY_DECLARATOR", "EXTENDS_CLAUSE", "IMPLEMENTS_CLAUSE", "PARAMETERS", "PARAMETER_DEF", "LABELED_STAT", "TYPECAST", "INDEX_OP", "POST_INC", "POST_DEC", "METHOD_CALL", "EXPR", "IMPORT", "UNARY_MINUS", "UNARY_PLUS", "CASE_GROUP", "ELIST", "FOR_INIT", "FOR_CONDITION", "FOR_ITERATOR", "EMPTY_STAT", "\"final\"", "\"abstract\"", "\"goto\"", "\"const\"", "\"do\"", "\"strictfp\"", "SUPER_CTOR_CALL", "CTOR_CALL", "CTOR_IDENT", "VARIABLE_PARAMETER_DEF", "STRING_CONSTRUCTOR", "STRING_CTOR_MIDDLE", "CLOSABLE_BLOCK", "IMPLICIT_PARAMETERS", "SELECT_SLOT", "DYNAMIC_MEMBER", "LABELED_ARG", "SPREAD_ARG", "SPREAD_MAP_ARG", "LIST_CONSTRUCTOR", "MAP_CONSTRUCTOR", "FOR_IN_ITERABLE", "STATIC_IMPORT", "ENUM_DEF", "ENUM_CONSTANT_DEF", "FOR_EACH_CLAUSE", "ANNOTATION_DEF", "ANNOTATIONS", "ANNOTATION", "ANNOTATION_MEMBER_VALUE_PAIR", "ANNOTATION_FIELD_DEF", "ANNOTATION_ARRAY_INIT", "TYPE_ARGUMENTS", "TYPE_ARGUMENT", "TYPE_PARAMETERS", "TYPE_PARAMETER", "WILDCARD_TYPE", "TYPE_UPPER_BOUNDS", "TYPE_LOWER_BOUNDS", "CLOSURE_LIST", "a script header", "\"package\"", "\"import\"", "\"static\"", "\"def\"", "'['", "']'", "an identifier", "a string literal", "'<'", "'.'", "'('", "\"class\"", "\"interface\"", "\"enum\"", "'@'", "'?'", "\"extends\"", "\"super\"", "'>'", "','", "'>>'", "'>>>'", "\"void\"", "\"boolean\"", "\"byte\"", "\"char\"", "\"short\"", "\"int\"", "\"float\"", "\"long\"", "\"double\"", "'*'", "\"as\"", "\"private\"", "\"public\"", "\"protected\"", "\"transient\"", "\"native\"", "\"threadsafe\"", "\"synchronized\"", "\"volatile\"", "')'", "'='", "'&'", "'{'", "'}'", "';'", "\"default\"", "\"throws\"", "\"implements\"", "\"this\"", "'...'", "'->'", "':'", "\"if\"", "\"else\"", "\"while\"", "\"switch\"", "\"for\"", "\"in\"", "\"return\"", "\"break\"", "\"continue\"", "\"throw\"", "\"assert\"", "'+'", "'-'", "\"case\"", "\"try\"", "\"finally\"", "\"catch\"", "'*.'", "'?.'", "'.&'", "\"false\"", "\"instanceof\"", "\"new\"", "\"null\"", "\"true\"", "'+='", "'-='", "'*='", "'/='", "'%='", "'>>='", "'>>>='", "'<<='", "'&='", "'^='", "'|='", "'**='", "'?:'", "'||'", "'&&'", "'|'", "'^'", "'=~'", "'==~'", "'!='", "'=='", "'==='", "'!=='", "'<=>'", "'<='", "'>='", "'<<'", "'..'", "'..<'", "'++'", "'/'", "'%'", "'--'", "'**'", "'~'", "'!'", "STRING_CTOR_START", "a string literal end", "a numeric literal", "NUM_FLOAT", "NUM_LONG", "NUM_DOUBLE", "NUM_BIG_INT", "NUM_BIG_DECIMAL", "some newlines, whitespace or comments", "'$'", "whitespace", "a newline", "a single line comment", "a comment", "a string character", "a multiline regular expression literal", "a multiline dollar escaping regular expression literal", "a multiline regular expression literal end", "a multiline dollar escaping regular expression literal end", "ESCAPED_SLASH", "ESCAPED_DOLLAR", "a multiline regular expression character", "a multiline dollar escaping regular expression character", "an escape sequence", "a newline inside a string", "a hexadecimal digit", "a character", "a letter", "a digit", "an exponent", "a float or double suffix", "a big decimal suffix" }; protected void buildTokenTypeASTClassMap() { tokenTypeToASTClassMap=null; }; private static final long[] mk_tokenSet_0() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=1477075058612994048L; data[2]=-6629298651002438191L; data[3]=1019L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-36028805608914944L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-16384L; data[2]=-6620291452234629121L; data[3]=1019L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[16]; data[0]=-14L; for (int i = 1; i<=2; i++) { data[i]=-1L; } data[3]=8589934591L; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = { 0L, 269533184L, 0L, 0L}; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535817188704256L; data[3]=512L; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = { 0L, 1097728L, 0L, 0L}; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535817121595392L; data[3]=512L; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = new long[8]; data[1]=1152921504606846976L; data[2]=32L; data[3]=512L; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=1477075058612994048L; data[2]=-6629298651002438159L; data[3]=1019L; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = new long[8]; data[0]=2L; data[1]=4035225266123964416L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = new long[8]; data[0]=290133630779394L; data[1]=-16384L; data[2]=-3L; data[3]=1023L; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = { 4810363371520L, 35888059799240704L, 0L, 0L}; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); private static final long[] mk_tokenSet_13() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35888059871592448L; data[3]=512L; return data; } public static final BitSet _tokenSet_13 = new BitSet(mk_tokenSet_13()); private static final long[] mk_tokenSet_14() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35923175536787456L; data[3]=512L; return data; } public static final BitSet _tokenSet_14 = new BitSet(mk_tokenSet_14()); private static final long[] mk_tokenSet_15() { long[] data = { 4810363371520L, 35923175452901376L, 0L, 0L}; return data; } public static final BitSet _tokenSet_15 = new BitSet(mk_tokenSet_15()); private static final long[] mk_tokenSet_16() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35923175534952448L; data[3]=512L; return data; } public static final BitSet _tokenSet_16 = new BitSet(mk_tokenSet_16()); private static final long[] mk_tokenSet_17() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535810916417536L; data[2]=-6629298651002438185L; data[3]=1019L; return data; } public static final BitSet _tokenSet_17 = new BitSet(mk_tokenSet_17()); private static final long[] mk_tokenSet_18() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=324153554006147072L; data[2]=-6629298651002438191L; data[3]=507L; return data; } public static final BitSet _tokenSet_18 = new BitSet(mk_tokenSet_18()); private static final long[] mk_tokenSet_19() { long[] data = new long[8]; data[1]=288265493971992576L; data[2]=-6629298651002732543L; data[3]=507L; return data; } public static final BitSet _tokenSet_19 = new BitSet(mk_tokenSet_19()); private static final long[] mk_tokenSet_20() { long[] data = { 0L, 68222976L, 0L, 0L}; return data; } public static final BitSet _tokenSet_20 = new BitSet(mk_tokenSet_20()); private static final long[] mk_tokenSet_21() { long[] data = { 4810363371520L, 35888060034121728L, 0L, 0L}; return data; } public static final BitSet _tokenSet_21 = new BitSet(mk_tokenSet_21()); private static final long[] mk_tokenSet_22() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35888060035170304L; data[3]=512L; return data; } public static final BitSet _tokenSet_22 = new BitSet(mk_tokenSet_22()); private static final long[] mk_tokenSet_23() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=4359378820134305792L; data[2]=-6629298651002307087L; data[3]=1019L; return data; } public static final BitSet _tokenSet_23 = new BitSet(mk_tokenSet_23()); private static final long[] mk_tokenSet_24() { long[] data = { 0L, 35115653660672L, 0L, 0L}; return data; } public static final BitSet _tokenSet_24 = new BitSet(mk_tokenSet_24()); private static final long[] mk_tokenSet_25() { long[] data = { 0L, 15990784L, 0L, 0L}; return data; } public static final BitSet _tokenSet_25 = new BitSet(mk_tokenSet_25()); private static final long[] mk_tokenSet_26() { long[] data = new long[8]; data[0]=2L; data[1]=4107282868768604160L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_26 = new BitSet(mk_tokenSet_26()); private static final long[] mk_tokenSet_27() { long[] data = new long[8]; data[0]=2L; data[1]=4107282868751826944L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_27 = new BitSet(mk_tokenSet_27()); private static final long[] mk_tokenSet_28() { long[] data = new long[8]; data[1]=4611686018428436480L; data[3]=512L; return data; } public static final BitSet _tokenSet_28 = new BitSet(mk_tokenSet_28()); private static final long[] mk_tokenSet_29() { long[] data = new long[8]; data[0]=2L; data[1]=4323455642275676160L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_29 = new BitSet(mk_tokenSet_29()); private static final long[] mk_tokenSet_30() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535810916417536L; data[2]=-6629298651002438191L; data[3]=1019L; return data; } public static final BitSet _tokenSet_30 = new BitSet(mk_tokenSet_30()); private static final long[] mk_tokenSet_31() { long[] data = { 0L, 13893632L, 0L, 0L}; return data; } public static final BitSet _tokenSet_31 = new BitSet(mk_tokenSet_31()); private static final long[] mk_tokenSet_32() { long[] data = { 2L, 1261007904254197760L, 520L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_32 = new BitSet(mk_tokenSet_32()); private static final long[] mk_tokenSet_33() { long[] data = { 4810363371520L, 35923175467843584L, 0L, 0L}; return data; } public static final BitSet _tokenSet_33 = new BitSet(mk_tokenSet_33()); private static final long[] mk_tokenSet_34() { long[] data = { 4810363371520L, 35923175459454976L, 0L, 0L}; return data; } public static final BitSet _tokenSet_34 = new BitSet(mk_tokenSet_34()); private static final long[] mk_tokenSet_35() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-1945590288370647040L; data[2]=-6629298650967179279L; data[3]=507L; return data; } public static final BitSet _tokenSet_35 = new BitSet(mk_tokenSet_35()); private static final long[] mk_tokenSet_36() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=1801334238230593536L; data[2]=2L; data[3]=512L; return data; } public static final BitSet _tokenSet_36 = new BitSet(mk_tokenSet_36()); private static final long[] mk_tokenSet_37() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-16384L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_37 = new BitSet(mk_tokenSet_37()); private static final long[] mk_tokenSet_38() { long[] data = new long[8]; data[1]=35116190531584L; data[3]=512L; return data; } public static final BitSet _tokenSet_38 = new BitSet(mk_tokenSet_38()); private static final long[] mk_tokenSet_39() { long[] data = { 0L, 55834574848L, 0L, 0L}; return data; } public static final BitSet _tokenSet_39 = new BitSet(mk_tokenSet_39()); private static final long[] mk_tokenSet_40() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-35184376299520L; data[2]=-6620291452249309185L; data[3]=1019L; return data; } public static final BitSet _tokenSet_40 = new BitSet(mk_tokenSet_40()); private static final long[] mk_tokenSet_41() { long[] data = new long[8]; data[1]=288230376168751104L; data[3]=2L; return data; } public static final BitSet _tokenSet_41 = new BitSet(mk_tokenSet_41()); private static final long[] mk_tokenSet_42() { long[] data = new long[16]; data[0]=-16L; data[1]=-900719925491662849L; data[2]=-1L; data[3]=8589934585L; return data; } public static final BitSet _tokenSet_42 = new BitSet(mk_tokenSet_42()); private static final long[] mk_tokenSet_43() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35923175691976704L; data[3]=512L; return data; } public static final BitSet _tokenSet_43 = new BitSet(mk_tokenSet_43()); private static final long[] mk_tokenSet_44() { long[] data = { 0L, 35116161171456L, 0L, 0L}; return data; } public static final BitSet _tokenSet_44 = new BitSet(mk_tokenSet_44()); private static final long[] mk_tokenSet_45() { long[] data = new long[8]; data[0]=2L; data[1]=99876864L; data[3]=512L; return data; } public static final BitSet _tokenSet_45 = new BitSet(mk_tokenSet_45()); private static final long[] mk_tokenSet_46() { long[] data = { 4810363371520L, 35888059530674176L, 0L, 0L}; return data; } public static final BitSet _tokenSet_46 = new BitSet(mk_tokenSet_46()); private static final long[] mk_tokenSet_47() { long[] data = new long[8]; data[1]=288265494240428032L; data[2]=-6629298651002732543L; data[3]=507L; return data; } public static final BitSet _tokenSet_47 = new BitSet(mk_tokenSet_47()); private static final long[] mk_tokenSet_48() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-72057602627878912L; data[2]=-2198486384641L; data[3]=1019L; return data; } public static final BitSet _tokenSet_48 = new BitSet(mk_tokenSet_48()); private static final long[] mk_tokenSet_49() { long[] data = { 8658654068736L, -2269849461828894720L, 522092529L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_49 = new BitSet(mk_tokenSet_49()); private static final long[] mk_tokenSet_50() { long[] data = new long[8]; data[1]=2017612641736851456L; data[3]=512L; return data; } public static final BitSet _tokenSet_50 = new BitSet(mk_tokenSet_50()); private static final long[] mk_tokenSet_51() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535808749764608L; data[3]=512L; return data; } public static final BitSet _tokenSet_51 = new BitSet(mk_tokenSet_51()); private static final long[] mk_tokenSet_52() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=4359378820142694400L; data[2]=-6629298651002307087L; data[3]=1019L; return data; } public static final BitSet _tokenSet_52 = new BitSet(mk_tokenSet_52()); private static final long[] mk_tokenSet_53() { long[] data = new long[8]; data[1]=-8935106479551152128L; data[3]=512L; return data; } public static final BitSet _tokenSet_53 = new BitSet(mk_tokenSet_53()); private static final long[] mk_tokenSet_54() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=-7169836171181752320L; data[3]=512L; return data; } public static final BitSet _tokenSet_54 = new BitSet(mk_tokenSet_54()); private static final long[] mk_tokenSet_55() { long[] data = { 4810363371520L, 35888059800289280L, 0L, 0L}; return data; } public static final BitSet _tokenSet_55 = new BitSet(mk_tokenSet_55()); private static final long[] mk_tokenSet_56() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35888059884175360L; data[3]=512L; return data; } public static final BitSet _tokenSet_56 = new BitSet(mk_tokenSet_56()); private static final long[] mk_tokenSet_57() { long[] data = new long[8]; data[1]=1801439859554910208L; data[3]=512L; return data; } public static final BitSet _tokenSet_57 = new BitSet(mk_tokenSet_57()); private static final long[] mk_tokenSet_58() { long[] data = new long[8]; data[1]=1729382265500205056L; data[3]=512L; return data; } public static final BitSet _tokenSet_58 = new BitSet(mk_tokenSet_58()); private static final long[] mk_tokenSet_59() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=4359378826553393152L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_59 = new BitSet(mk_tokenSet_59()); private static final long[] mk_tokenSet_60() { long[] data = new long[8]; data[1]=1729382265769689088L; data[3]=512L; return data; } public static final BitSet _tokenSet_60 = new BitSet(mk_tokenSet_60()); private static final long[] mk_tokenSet_61() { long[] data = new long[8]; data[1]=269484032L; data[3]=512L; return data; } public static final BitSet _tokenSet_61 = new BitSet(mk_tokenSet_61()); private static final long[] mk_tokenSet_62() { long[] data = new long[8]; data[1]=2017612642005286912L; data[3]=512L; return data; } public static final BitSet _tokenSet_62 = new BitSet(mk_tokenSet_62()); private static final long[] mk_tokenSet_63() { long[] data = new long[8]; data[1]=2017612633061982208L; data[3]=512L; return data; } public static final BitSet _tokenSet_63 = new BitSet(mk_tokenSet_63()); private static final long[] mk_tokenSet_64() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535819510546432L; data[2]=-6629298651002438191L; data[3]=1019L; return data; } public static final BitSet _tokenSet_64 = new BitSet(mk_tokenSet_64()); private static final long[] mk_tokenSet_65() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2053535810920611840L; data[2]=-6629298651002438191L; data[3]=1019L; return data; } public static final BitSet _tokenSet_65 = new BitSet(mk_tokenSet_65()); private static final long[] mk_tokenSet_66() { long[] data = { 0L, 2151677952L, 1L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_66 = new BitSet(mk_tokenSet_66()); private static final long[] mk_tokenSet_67() { long[] data = new long[8]; data[1]=35116207308800L; data[3]=512L; return data; } public static final BitSet _tokenSet_67 = new BitSet(mk_tokenSet_67()); private static final long[] mk_tokenSet_68() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-36028805608914944L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_68 = new BitSet(mk_tokenSet_68()); private static final long[] mk_tokenSet_69() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=1477075058612994048L; data[2]=-6629298651002438191L; data[3]=1019L; return data; } public static final BitSet _tokenSet_69 = new BitSet(mk_tokenSet_69()); private static final long[] mk_tokenSet_70() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-216208023138353152L; data[2]=-6629298650967179267L; data[3]=1019L; return data; } public static final BitSet _tokenSet_70 = new BitSet(mk_tokenSet_70()); private static final long[] mk_tokenSet_71() { long[] data = new long[8]; data[0]=290133630779394L; data[1]=-16384L; data[2]=-1L; data[3]=1023L; return data; } public static final BitSet _tokenSet_71 = new BitSet(mk_tokenSet_71()); private static final long[] mk_tokenSet_72() { long[] data = { 0L, 13893632L, 2L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_72 = new BitSet(mk_tokenSet_72()); private static final long[] mk_tokenSet_73() { long[] data = new long[8]; data[1]=108086399647875072L; data[2]=4L; data[3]=512L; return data; } public static final BitSet _tokenSet_73 = new BitSet(mk_tokenSet_73()); private static final long[] mk_tokenSet_74() { long[] data = new long[8]; data[0]=137438953472L; data[1]=35115922227200L; data[2]=6L; data[3]=512L; return data; } public static final BitSet _tokenSet_74 = new BitSet(mk_tokenSet_74()); private static final long[] mk_tokenSet_75() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=2125593413556862976L; data[2]=-6629298651002438185L; data[3]=1019L; return data; } public static final BitSet _tokenSet_75 = new BitSet(mk_tokenSet_75()); private static final long[] mk_tokenSet_76() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=1477075058378080256L; data[2]=-6629298651002700799L; data[3]=507L; return data; } public static final BitSet _tokenSet_76 = new BitSet(mk_tokenSet_76()); private static final long[] mk_tokenSet_77() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-8589950976L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_77 = new BitSet(mk_tokenSet_77()); private static final long[] mk_tokenSet_78() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35923175532855296L; data[2]=520L; data[3]=512L; return data; } public static final BitSet _tokenSet_78 = new BitSet(mk_tokenSet_78()); private static final long[] mk_tokenSet_79() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=35923175532855296L; data[3]=512L; return data; } public static final BitSet _tokenSet_79 = new BitSet(mk_tokenSet_79()); private static final long[] mk_tokenSet_80() { long[] data = new long[8]; data[1]=288230376151711744L; data[2]=524288L; data[3]=512L; return data; } public static final BitSet _tokenSet_80 = new BitSet(mk_tokenSet_80()); private static final long[] mk_tokenSet_81() { long[] data = new long[8]; data[1]=288265493971992576L; data[2]=-6629298651002732543L; data[3]=1019L; return data; } public static final BitSet _tokenSet_81 = new BitSet(mk_tokenSet_81()); private static final long[] mk_tokenSet_82() { long[] data = new long[8]; data[0]=2L; data[1]=4071254071733387264L; data[2]=131104L; data[3]=512L; return data; } public static final BitSet _tokenSet_82 = new BitSet(mk_tokenSet_82()); private static final long[] mk_tokenSet_83() { long[] data = new long[8]; data[0]=4810363371520L; data[1]=324153553771233280L; data[2]=-6629298651002700799L; data[3]=507L; return data; } public static final BitSet _tokenSet_83 = new BitSet(mk_tokenSet_83()); private static final long[] mk_tokenSet_84() { long[] data = { 0L, 51539607552L, 252201579132747776L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_84 = new BitSet(mk_tokenSet_84()); private static final long[] mk_tokenSet_85() { long[] data = new long[8]; data[0]=-16L; data[1]=-288230376151711745L; data[2]=-1L; data[3]=8589934591L; return data; } public static final BitSet _tokenSet_85 = new BitSet(mk_tokenSet_85()); private static final long[] mk_tokenSet_86() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-1981619085658046464L; data[2]=-6629298650967179279L; data[3]=507L; return data; } public static final BitSet _tokenSet_86 = new BitSet(mk_tokenSet_86()); private static final long[] mk_tokenSet_87() { long[] data = new long[8]; data[1]=288265493971992576L; data[2]=486539265L; data[3]=506L; return data; } public static final BitSet _tokenSet_87 = new BitSet(mk_tokenSet_87()); private static final long[] mk_tokenSet_88() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-216172838485245952L; data[2]=-6629298650952499201L; data[3]=1019L; return data; } public static final BitSet _tokenSet_88 = new BitSet(mk_tokenSet_88()); private static final long[] mk_tokenSet_89() { long[] data = new long[8]; data[1]=288230376177139712L; data[2]=14680064L; data[3]=512L; return data; } public static final BitSet _tokenSet_89 = new BitSet(mk_tokenSet_89()); private static final long[] mk_tokenSet_90() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-216172847075180544L; data[2]=-6629298650952499209L; data[3]=1019L; return data; } public static final BitSet _tokenSet_90 = new BitSet(mk_tokenSet_90()); private static final long[] mk_tokenSet_91() { long[] data = new long[8]; data[0]=4810363371522L; data[1]=324153553771233280L; data[2]=-6629298651002700799L; data[3]=507L; return data; } public static final BitSet _tokenSet_91 = new BitSet(mk_tokenSet_91()); private static final long[] mk_tokenSet_92() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-36028797018980352L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_92 = new BitSet(mk_tokenSet_92()); private static final long[] mk_tokenSet_93() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-1981619085658046464L; data[2]=-6629298650967179279L; data[3]=1019L; return data; } public static final BitSet _tokenSet_93 = new BitSet(mk_tokenSet_93()); private static final long[] mk_tokenSet_94() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-1981619085658046464L; data[2]=522092529L; data[3]=506L; return data; } public static final BitSet _tokenSet_94 = new BitSet(mk_tokenSet_94()); private static final long[] mk_tokenSet_95() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-252201644102533120L; data[2]=-6629298650967179265L; data[3]=1019L; return data; } public static final BitSet _tokenSet_95 = new BitSet(mk_tokenSet_95()); private static final long[] mk_tokenSet_96() { long[] data = { 8658654068736L, -2269849461829943296L, 522092529L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_96 = new BitSet(mk_tokenSet_96()); private static final long[] mk_tokenSet_97() { long[] data = { 0L, 4299161600L, 27021597764223488L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_97 = new BitSet(mk_tokenSet_97()); private static final long[] mk_tokenSet_98() { long[] data = new long[8]; data[1]=35115653660672L; data[3]=512L; return data; } public static final BitSet _tokenSet_98 = new BitSet(mk_tokenSet_98()); private static final long[] mk_tokenSet_99() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-35240487698432L; data[2]=-6620291452249309187L; data[3]=1019L; return data; } public static final BitSet _tokenSet_99 = new BitSet(mk_tokenSet_99()); private static final long[] mk_tokenSet_100() { long[] data = { 0L, 35184372088832L, 1729382256910270464L, 0L, 0L, 0L}; return data; } public static final BitSet _tokenSet_100 = new BitSet(mk_tokenSet_100()); private static final long[] mk_tokenSet_101() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-276840448L; data[2]=-14680067L; data[3]=1019L; return data; } public static final BitSet _tokenSet_101 = new BitSet(mk_tokenSet_101()); private static final long[] mk_tokenSet_102() { long[] data = new long[8]; data[0]=8658654068738L; data[1]=-268451840L; data[2]=-3L; data[3]=1019L; return data; } public static final BitSet _tokenSet_102 = new BitSet(mk_tokenSet_102()); private static final long[] mk_tokenSet_103() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-1981583901016997888L; data[2]=-6629298650967179279L; data[3]=507L; return data; } public static final BitSet _tokenSet_103 = new BitSet(mk_tokenSet_103()); private static final long[] mk_tokenSet_104() { long[] data = new long[8]; data[1]=288265493972516864L; data[2]=-6629298651002732543L; data[3]=507L; return data; } public static final BitSet _tokenSet_104 = new BitSet(mk_tokenSet_104()); private static final long[] mk_tokenSet_105() { long[] data = new long[8]; data[0]=8658654068736L; data[1]=-16384L; data[2]=-1L; data[3]=1019L; return data; } public static final BitSet _tokenSet_105 = new BitSet(mk_tokenSet_105()); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/GroovySourceToken.java0000644001501200150120000000420011627206700025442 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.Token; /** * This is a Token sub class to track line information * * @author Jochen Theodorou */ public class GroovySourceToken extends Token implements SourceInfo{ protected int line; protected String text = ""; protected int col; protected int lineLast; protected int colLast; /** * Constructor using a token type * * @param t the type */ public GroovySourceToken(int t) { super(t); } public int getLine() { return line; } /** * get the source token text * @return the source token text */ public String getText() { return text; } public void setLine(int l) { line = l; } /** * set the source token text * @param s the text */ public void setText(String s) { text = s; } public String toString() { return "[\"" + getText() + "\",<" + type + ">,"+ "line=" + line + ",col=" + col + ",lineLast=" + lineLast + ",colLast=" + colLast + "]"; } public int getColumn() { return col; } public void setColumn(int c) { col = c; } public int getLineLast() { return lineLast; } public void setLineLast(int lineLast) { this.lineLast = lineLast; } public int getColumnLast() { return colLast; } public void setColumnLast(int colLast) { this.colLast = colLast; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/ASTRuntimeException.java0000644001501200150120000000302611627206700025652 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.collections.AST; /** * @author James Strachan * @version $Revision$ */ public class ASTRuntimeException extends RuntimeException { private final AST ast; public ASTRuntimeException(AST ast, String message) { super(message + description(ast)); this.ast = ast; } public ASTRuntimeException(AST ast, String message, Throwable throwable) { super(message + description(ast), throwable); this.ast = null; } protected static String description(AST node) { return (node != null) ? " at line: " + node.getLine() + " column: " + node.getColumn() : ""; } public AST getAst() { return ast; } public int getLine() { return ast != null ? ast.getLine() : -1; } public int getColumn() { return ast != null ? ast.getColumn() : -1; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/SourceInfo.java0000644001501200150120000000277411627206700024065 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; public interface SourceInfo { /** * get start line * * @return the starting line */ int getLine(); /** * set start line * * @param l the line */ void setLine(int l); /** * get starting column * * @return the starting column */ int getColumn(); /** * set start column * * @param c the column */ void setColumn(int c); /** * get ending line * * @return the ending line */ int getLineLast(); /** * set ending line * * @param lineLast the line */ void setLineLast(int lineLast); /** * get ending column * * @return the ending column */ int getColumnLast(); /** * set ending column * * @param colLast the column */ void setColumnLast(int colLast); } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/UnicodeEscapingReader.java0000644001501200150120000001242611707612044026170 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import java.io.IOException; import java.io.Reader; import antlr.CharScanner; import antlr.Token; import antlr.TokenStreamException; /** * Translates GLS-defined unicode escapes into characters. Throws an exception * in the event of an invalid unicode escape being detected. * *

      No attempt has been made to optimize this class for speed or * space.

      * * @version $Revision$ */ public class UnicodeEscapingReader extends Reader { private final Reader reader; private CharScanner lexer; private boolean hasNextChar = false; private int nextChar; private final SourceBuffer sourceBuffer; private int previousLine; private int numUnicodeEscapesFound = 0; private int numUnicodeEscapesFoundOnCurrentLine = 0; private static class DummyLexer extends CharScanner { final private Token t = new Token(); public Token nextToken() throws TokenStreamException { return t; } @Override public int getColumn() { return 0; } @Override public int getLine() { return 0; } } /** * Constructor. * @param reader The reader that this reader will filter over. */ public UnicodeEscapingReader(Reader reader,SourceBuffer sourceBuffer) { this.reader = reader; this.sourceBuffer = sourceBuffer; this.lexer = new DummyLexer(); } /** * Sets the lexer that is using this reader. Must be called before the * lexer is used. */ public void setLexer(CharScanner lexer) { this.lexer = lexer; } /** * Reads characters from the underlying reader. * @see java.io.Reader#read(char[],int,int) */ public int read(char cbuf[], int off, int len) throws IOException { int c = 0; int count = 0; while (count < len && (c = read())!= -1) { cbuf[off + count] = (char) c; count++; } return (count == 0 && c == -1) ? -1 : count; } /** * Gets the next character from the underlying reader, * translating escapes as required. * @see java.io.Reader#close() */ public int read() throws IOException { if (hasNextChar) { hasNextChar = false; write(nextChar); return nextChar; } if (previousLine != lexer.getLine()) { // new line, so reset unicode escapes numUnicodeEscapesFoundOnCurrentLine = 0; previousLine = lexer.getLine(); } int c = reader.read(); if (c != '\\') { write(c); return c; } // Have one backslash, continue if next char is 'u' c = reader.read(); if (c != 'u') { hasNextChar = true; nextChar = c; write('\\'); return '\\'; } // Swallow multiple 'u's int numberOfUChars = 0; do { numberOfUChars++; c = reader.read(); } while (c == 'u'); // Get first hex digit checkHexDigit(c); StringBuffer charNum = new StringBuffer(); charNum.append((char) c); // Must now be three more hex digits for (int i = 0; i < 3; i++) { c = reader.read(); checkHexDigit(c); charNum.append((char) c); } int rv = Integer.parseInt(charNum.toString(), 16); write(rv); numUnicodeEscapesFound += 4 + numberOfUChars; numUnicodeEscapesFoundOnCurrentLine += 4 + numberOfUChars; return rv; } private void write(int c) { if (sourceBuffer != null) {sourceBuffer.write(c);} } /** * Checks that the given character is indeed a hex digit. */ private void checkHexDigit(int c) throws IOException { if (c >= '0' && c <= '9') { return; } if (c >= 'a' && c <= 'f') { return; } if (c >= 'A' && c <= 'F') { return; } // Causes the invalid escape to be skipped hasNextChar = true; nextChar = c; throw new IOException("Did not find four digit hex character code." + " line: " + lexer.getLine() + " col:" + lexer.getColumn()); } public int getUnescapedUnicodeColumnCount() { return numUnicodeEscapesFoundOnCurrentLine; } public int getUnescapedUnicodeOffsetCount() { return numUnicodeEscapesFound; } /** * Closes this reader by calling close on the underlying reader. * @see java.io.Reader#close() */ public void close() throws IOException { reader.close(); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/EnumHelper.java0000644001501200150120000000526711707612044024056 0ustar miguelmiguel/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MixinNode; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.objectweb.asm.Opcodes; public class EnumHelper { private static final int FS = Opcodes.ACC_FINAL | Opcodes.ACC_STATIC; private static final int PUBLIC_FS = Opcodes.ACC_PUBLIC | FS; public static ClassNode makeEnumNode(String name, int modifiers, ClassNode[] interfaces, ClassNode outerClass) { modifiers = modifiers | Opcodes.ACC_FINAL | Opcodes.ACC_ENUM; ClassNode enumClass; if (outerClass==null) { enumClass = new ClassNode(name,modifiers,null,interfaces,MixinNode.EMPTY_ARRAY); } else { name = outerClass.getName() + "$" + name; enumClass = new InnerClassNode(outerClass,name,modifiers,null,interfaces,MixinNode.EMPTY_ARRAY); } // set super class and generics info // "enum X" -> class X extends Enum GenericsType gt = new GenericsType(enumClass); ClassNode superClass = ClassHelper.makeWithoutCaching("java.lang.Enum"); superClass.setGenericsTypes(new GenericsType[]{gt}); enumClass.setSuperClass(superClass); superClass.setRedirect(ClassHelper.Enum_Type); return enumClass; } public static void addEnumConstant(ClassNode enumClass, String name, Expression init) { int modifiers = PUBLIC_FS | Opcodes.ACC_ENUM; if (init!=null && !(init instanceof ListExpression)) { ListExpression list = new ListExpression(); list.addExpression(init); init = list; } FieldNode fn = new FieldNode(name,modifiers,enumClass.getPlainNodeReference(),enumClass,init); enumClass.addField(fn); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/ASTParserException.java0000644001501200150120000000236611627206700025471 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.collections.AST; import org.codehaus.groovy.syntax.ParserException; /** * Thrown when trying to parse the AST * * @version $Revision$ */ public class ASTParserException extends ParserException { private final AST ast; public ASTParserException(ASTRuntimeException e) { super(e.getMessage(), e, e.getLine(), e.getColumn()); this.ast = e.getAst(); } public ASTParserException(String message, ASTRuntimeException e) { super(message, e, e.getLine(), e.getColumn()); this.ast = e.getAst(); } public AST getAst() { return ast; } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/AntlrParserPlugin.java0000644001501200150120000035377211715031256025434 0ustar miguelmiguel/* * Copyright 2003-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.TokenStreamRecognitionException; import antlr.collections.AST; import com.thoughtworks.xstream.XStream; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.antlr.parser.GroovyLexer; import org.codehaus.groovy.antlr.parser.GroovyRecognizer; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import org.codehaus.groovy.antlr.treewalker.*; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.ParserPlugin; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.syntax.*; import org.objectweb.asm.Opcodes; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintStream; import java.io.Reader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * A parser plugin which adapts the JSR Antlr Parser to the Groovy runtime * * @author James Strachan */ public class AntlrParserPlugin extends ASTHelper implements ParserPlugin, GroovyTokenTypes { private static class AnonymousInnerClassCarrier extends Expression { ClassNode innerClass; public Expression transformExpression(ExpressionTransformer transformer) { return null; } @Override public void setSourcePosition(final ASTNode node) { super.setSourcePosition(node); innerClass.setSourcePosition(node); } @Override public void setColumnNumber(final int columnNumber) { super.setColumnNumber(columnNumber); innerClass.setColumnNumber(columnNumber); } @Override public void setLineNumber(final int lineNumber) { super.setLineNumber(lineNumber); innerClass.setLineNumber(lineNumber); } @Override public void setLastColumnNumber(final int columnNumber) { super.setLastColumnNumber(columnNumber); innerClass.setLastColumnNumber(columnNumber); } @Override public void setLastLineNumber(final int lineNumber) { super.setLastLineNumber(lineNumber); innerClass.setLastLineNumber(lineNumber); } } protected AST ast; private ClassNode classNode; private String[] tokenNames; private int innerClassCounter = 1; private boolean enumConstantBeingDef = false; private boolean forStatementBeingDef = false; private boolean firstParamIsVarArg = false; private boolean firstParam = false; public /*final*/ Reduction parseCST(final SourceUnit sourceUnit, Reader reader) throws CompilationFailedException { final SourceBuffer sourceBuffer = new SourceBuffer(); transformCSTIntoAST(sourceUnit, reader, sourceBuffer); processAST(); return outputAST(sourceUnit, sourceBuffer); } protected void transformCSTIntoAST(SourceUnit sourceUnit, Reader reader, SourceBuffer sourceBuffer) throws CompilationFailedException { ast = null; setController(sourceUnit); // TODO find a way to inject any GroovyLexer/GroovyRecognizer UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(reader, sourceBuffer); UnicodeLexerSharedInputState inputState = new UnicodeLexerSharedInputState(unicodeReader); GroovyLexer lexer = new GroovyLexer(inputState); unicodeReader.setLexer(lexer); GroovyRecognizer parser = GroovyRecognizer.make(lexer); parser.setSourceBuffer(sourceBuffer); tokenNames = parser.getTokenNames(); parser.setFilename(sourceUnit.getName()); // start parsing at the compilationUnit rule try { parser.compilationUnit(); } catch (TokenStreamRecognitionException tsre) { RecognitionException e = tsre.recog; SyntaxException se = new SyntaxException(e.getMessage(), e, e.getLine(), e.getColumn()); se.setFatal(true); sourceUnit.addError(se); } catch (RecognitionException e) { SyntaxException se = new SyntaxException(e.getMessage(), e, e.getLine(), e.getColumn()); se.setFatal(true); sourceUnit.addError(se); } catch (TokenStreamException e) { sourceUnit.addException(e); } ast = parser.getAST(); } protected void processAST() { AntlrASTProcessor snippets = new AntlrASTProcessSnippets(); ast = snippets.process(ast); } public Reduction outputAST(final SourceUnit sourceUnit, final SourceBuffer sourceBuffer) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { outputASTInVariousFormsIfNeeded(sourceUnit, sourceBuffer); return null; } }); return null; //new Reduction(Tpken.EOF); } private void outputASTInVariousFormsIfNeeded(SourceUnit sourceUnit, SourceBuffer sourceBuffer) { // straight xstream output of AST if ("xml".equals(System.getProperty("antlr.ast"))) { saveAsXML(sourceUnit.getName(), ast); } // 'pretty printer' output of AST if ("groovy".equals(System.getProperty("antlr.ast"))) { try { PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".pretty.groovy")); Visitor visitor = new SourcePrinter(out, tokenNames); AntlrASTProcessor treewalker = new SourceCodeTraversal(visitor); treewalker.process(ast); } catch (FileNotFoundException e) { System.out.println("Cannot create " + sourceUnit.getName() + ".pretty.groovy"); } } // output AST in format suitable for opening in http://freemind.sourceforge.net // which is a really nice way of seeing the AST, folding nodes etc if ("mindmap".equals(System.getProperty("antlr.ast"))) { try { PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".mm")); Visitor visitor = new MindMapPrinter(out, tokenNames); AntlrASTProcessor treewalker = new PreOrderTraversal(visitor); treewalker.process(ast); } catch (FileNotFoundException e) { System.out.println("Cannot create " + sourceUnit.getName() + ".mm"); } } // include original line/col info and source code on the mindmap output if ("extendedMindmap".equals(System.getProperty("antlr.ast"))) { try { PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".mm")); Visitor visitor = new MindMapPrinter(out, tokenNames, sourceBuffer); AntlrASTProcessor treewalker = new PreOrderTraversal(visitor); treewalker.process(ast); } catch (FileNotFoundException e) { System.out.println("Cannot create " + sourceUnit.getName() + ".mm"); } } // html output of AST if ("html".equals(System.getProperty("antlr.ast"))) { try { PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".html")); List v = new ArrayList(); v.add(new NodeAsHTMLPrinter(out, tokenNames)); v.add(new SourcePrinter(out, tokenNames)); Visitor visitors = new CompositeVisitor(v); AntlrASTProcessor treewalker = new SourceCodeTraversal(visitors); treewalker.process(ast); } catch (FileNotFoundException e) { System.out.println("Cannot create " + sourceUnit.getName() + ".html"); } } } private void saveAsXML(String name, AST ast) { XStream xstream = new XStream(); try { xstream.toXML(ast, new FileWriter(name + ".antlr.xml")); System.out.println("Written AST to " + name + ".antlr.xml"); } catch (Exception e) { System.out.println("Couldn't write to " + name + ".antlr.xml"); e.printStackTrace(); } } public ModuleNode buildAST(SourceUnit sourceUnit, ClassLoader classLoader, Reduction cst) throws ParserException { setClassLoader(classLoader); makeModule(); try { convertGroovy(ast); if (output.getStatementBlock().isEmpty() && output.getMethods().isEmpty() && output.getClasses().isEmpty()) { output.addStatement(ReturnStatement.RETURN_NULL_OR_VOID); } // set the script source position ClassNode scriptClassNode = output.getScriptClassDummy(); if (scriptClassNode != null) { List statements = output.getStatementBlock().getStatements(); if (statements.size() > 0) { Statement firstStatement = statements.get(0); Statement lastStatement = statements.get(statements.size() - 1); scriptClassNode.setSourcePosition(firstStatement); scriptClassNode.setLastColumnNumber(lastStatement.getLastColumnNumber()); scriptClassNode.setLastLineNumber(lastStatement.getLastLineNumber()); } } } catch (ASTRuntimeException e) { throw new ASTParserException(e.getMessage() + ". File: " + sourceUnit.getName(), e); } return output; } /** * Converts the Antlr AST to the Groovy AST */ protected void convertGroovy(AST node) { while (node != null) { int type = node.getType(); switch (type) { case PACKAGE_DEF: packageDef(node); break; case STATIC_IMPORT: case IMPORT: importDef(node); break; case CLASS_DEF: classDef(node); break; case INTERFACE_DEF: interfaceDef(node); break; case METHOD_DEF: methodDef(node); break; case ENUM_DEF: enumDef(node); break; case ANNOTATION_DEF: annotationDef(node); break; default: { Statement statement = statement(node); output.addStatement(statement); } } node = node.getNextSibling(); } } // Top level control structures //------------------------------------------------------------------------- protected void packageDef(AST packageDef) { List annotations = new ArrayList(); AST node = packageDef.getFirstChild(); if (isType(ANNOTATIONS, node)) { processAnnotations(annotations, node); node = node.getNextSibling(); } String name = qualifiedName(node); // TODO should we check package node doesn't already exist? conflict? PackageNode packageNode = setPackage(name, annotations); configureAST(packageNode, packageDef); } protected void importDef(AST importNode) { boolean isStatic = importNode.getType() == STATIC_IMPORT; List annotations = new ArrayList(); AST node = importNode.getFirstChild(); if (isType(ANNOTATIONS, node)) { processAnnotations(annotations, node); node = node.getNextSibling(); } String alias = null; if (isType(LITERAL_as, node)) { //import is like "import Foo as Bar" node = node.getFirstChild(); AST aliasNode = node.getNextSibling(); alias = identifier(aliasNode); } if (node.getNumberOfChildren() == 0) { String name = identifier(node); // import is like "import Foo" ClassNode type = ClassHelper.make(name); configureAST(type, importNode); addImport(type, name, alias, annotations); return; } AST packageNode = node.getFirstChild(); String packageName = qualifiedName(packageNode); AST nameNode = packageNode.getNextSibling(); if (isType(STAR, nameNode)) { if (isStatic) { // import is like "import static foo.Bar.*" // packageName is actually a className in this case ClassNode type = ClassHelper.make(packageName); configureAST(type, importNode); addStaticStarImport(type, packageName, annotations); } else { // import is like "import foo.*" addStarImport(packageName, annotations); } if (alias != null) throw new GroovyBugError( "imports like 'import foo.* as Bar' are not " + "supported and should be caught by the grammar"); } else { String name = identifier(nameNode); if (isStatic) { // import is like "import static foo.Bar.method" // packageName is really class name in this case ClassNode type = ClassHelper.make(packageName); configureAST(type, importNode); addStaticImport(type, name, alias, annotations); } else { // import is like "import foo.Bar" ClassNode type = ClassHelper.make(packageName + "." + name); configureAST(type, importNode); addImport(type, name, alias, annotations); } } } private void processAnnotations(List annotations, AST node) { AST child = node.getFirstChild(); while (child != null) { if (isType(ANNOTATION, child)) annotations.add(annotation(child)); child = child.getNextSibling(); } } protected void annotationDef(AST classDef) { List annotations = new ArrayList(); AST node = classDef.getFirstChild(); int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); checkNoInvalidModifier(classDef, "Annotation Definition", modifiers, Opcodes.ACC_SYNCHRONIZED, "synchronized"); node = node.getNextSibling(); } modifiers |= Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE | Opcodes.ACC_ANNOTATION; String name = identifier(node); node = node.getNextSibling(); ClassNode superClass = ClassHelper.OBJECT_TYPE; GenericsType[] genericsType = null; if (isType(TYPE_PARAMETERS, node)) { genericsType = makeGenericsType(node); node = node.getNextSibling(); } ClassNode[] interfaces = ClassNode.EMPTY_ARRAY; if (isType(EXTENDS_CLAUSE, node)) { interfaces = interfaces(node); node = node.getNextSibling(); } boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; classNode = new ClassNode(dot(getPackageName(), name), modifiers, superClass, interfaces, null); classNode.setSyntheticPublic(syntheticPublic); classNode.addAnnotations(annotations); classNode.setGenericsTypes(genericsType); classNode.addInterface(ClassHelper.Annotation_TYPE); configureAST(classNode, classDef); assertNodeType(OBJBLOCK, node); objectBlock(node); output.addClass(classNode); classNode = null; } protected void interfaceDef(AST classDef) { int oldInnerClassCounter = innerClassCounter; innerInterfaceDef(classDef); classNode = null; innerClassCounter = oldInnerClassCounter; } protected void innerInterfaceDef(AST classDef) { List annotations = new ArrayList(); AST node = classDef.getFirstChild(); int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); checkNoInvalidModifier(classDef, "Interface", modifiers, Opcodes.ACC_SYNCHRONIZED, "synchronized"); node = node.getNextSibling(); } modifiers |= Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE; String name = identifier(node); node = node.getNextSibling(); ClassNode superClass = ClassHelper.OBJECT_TYPE; GenericsType[] genericsType = null; if (isType(TYPE_PARAMETERS, node)) { genericsType = makeGenericsType(node); node = node.getNextSibling(); } ClassNode[] interfaces = ClassNode.EMPTY_ARRAY; if (isType(EXTENDS_CLAUSE, node)) { interfaces = interfaces(node); node = node.getNextSibling(); } ClassNode outerClass = classNode; boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; if (classNode != null) { name = classNode.getNameWithoutPackage() + "$" + name; String fullName = dot(classNode.getPackageName(), name); classNode = new InnerClassNode(classNode, fullName, modifiers, superClass, interfaces, null); } else { classNode = new ClassNode(dot(getPackageName(), name), modifiers, superClass, interfaces, null); } classNode.setSyntheticPublic(syntheticPublic); classNode.addAnnotations(annotations); classNode.setGenericsTypes(genericsType); configureAST(classNode, classDef); int oldClassCount = innerClassCounter; assertNodeType(OBJBLOCK, node); objectBlock(node); output.addClass(classNode); classNode = outerClass; innerClassCounter = oldClassCount; } protected void classDef(AST classDef) { int oldInnerClassCounter = innerClassCounter; innerClassDef(classDef); classNode = null; innerClassCounter = oldInnerClassCounter; } private ClassNode getClassOrScript(ClassNode node) { if (node != null) return node; return output.getScriptClassDummy(); } protected Expression anonymousInnerClassDef(AST node) { ClassNode oldNode = classNode; ClassNode outerClass = getClassOrScript(oldNode); String fullName = outerClass.getName() + '$' + innerClassCounter; innerClassCounter++; if (enumConstantBeingDef) { classNode = new EnumConstantClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE); } else { classNode = new InnerClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE); } ((InnerClassNode) classNode).setAnonymous(true); assertNodeType(OBJBLOCK, node); objectBlock(node); output.addClass(classNode); AnonymousInnerClassCarrier ret = new AnonymousInnerClassCarrier(); ret.innerClass = classNode; classNode = oldNode; return ret; } protected void innerClassDef(AST classDef) { List annotations = new ArrayList(); AST node = classDef.getFirstChild(); int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); checkNoInvalidModifier(classDef, "Class", modifiers, Opcodes.ACC_SYNCHRONIZED, "synchronized"); node = node.getNextSibling(); } String name = identifier(node); node = node.getNextSibling(); GenericsType[] genericsType = null; if (isType(TYPE_PARAMETERS, node)) { genericsType = makeGenericsType(node); node = node.getNextSibling(); } ClassNode superClass = null; if (isType(EXTENDS_CLAUSE, node)) { superClass = makeTypeWithArguments(node); node = node.getNextSibling(); } ClassNode[] interfaces = ClassNode.EMPTY_ARRAY; if (isType(IMPLEMENTS_CLAUSE, node)) { interfaces = interfaces(node); node = node.getNextSibling(); } // TODO read mixins MixinNode[] mixins = {}; ClassNode outerClass = classNode; boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; if (classNode != null) { name = classNode.getNameWithoutPackage() + "$" + name; String fullName = dot(classNode.getPackageName(), name); classNode = new InnerClassNode(classNode, fullName, modifiers, superClass, interfaces, mixins); } else { classNode = new ClassNode(dot(getPackageName(), name), modifiers, superClass, interfaces, mixins); } classNode.addAnnotations(annotations); classNode.setGenericsTypes(genericsType); classNode.setSyntheticPublic(syntheticPublic); configureAST(classNode, classDef); // we put the class already in output to avoid the most inner classes // will be used as first class later in the loader. The first class // there determines what GCL#parseClass for example will return, so we // have here to ensure it won't be the inner class output.addClass(classNode); int oldClassCount = innerClassCounter; assertNodeType(OBJBLOCK, node); objectBlock(node); classNode = outerClass; innerClassCounter = oldClassCount; } protected void objectBlock(AST objectBlock) { for (AST node = objectBlock.getFirstChild(); node != null; node = node.getNextSibling()) { int type = node.getType(); switch (type) { case OBJBLOCK: objectBlock(node); break; case ANNOTATION_FIELD_DEF: case METHOD_DEF: methodDef(node); break; case CTOR_IDENT: constructorDef(node); break; case VARIABLE_DEF: fieldDef(node); break; case STATIC_INIT: staticInit(node); break; case INSTANCE_INIT: objectInit(node); break; case ENUM_DEF: enumDef(node); break; case ENUM_CONSTANT_DEF: enumConstantDef(node); break; case CLASS_DEF: innerClassDef(node); break; case INTERFACE_DEF: innerInterfaceDef(node); break; default: unknownAST(node); } } } protected void enumDef(AST enumNode) { assertNodeType(ENUM_DEF, enumNode); List annotations = new ArrayList(); AST node = enumNode.getFirstChild(); int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); node = node.getNextSibling(); } String name = identifier(node); node = node.getNextSibling(); ClassNode[] interfaces = interfaces(node); node = node.getNextSibling(); boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; String enumName = (classNode != null ? name : dot(getPackageName(), name)); ClassNode enumClass = EnumHelper.makeEnumNode(enumName, modifiers, interfaces, classNode); enumClass.setSyntheticPublic(syntheticPublic); ClassNode oldNode = classNode; enumClass.addAnnotations(annotations); classNode = enumClass; configureAST(classNode, enumNode); assertNodeType(OBJBLOCK, node); objectBlock(node); classNode = oldNode; output.addClass(enumClass); } protected void enumConstantDef(AST node) { enumConstantBeingDef = true; assertNodeType(ENUM_CONSTANT_DEF, node); AST element = node.getFirstChild(); if (isType(ANNOTATIONS, element)) { element = element.getNextSibling(); } String identifier = identifier(element); Expression init = null; element = element.getNextSibling(); if (element != null) { init = expression(element); ClassNode innerClass = getAnonymousInnerClassNode(init); if (innerClass != null) { // we have to handle an enum that defines a class for a constant // for example the constant having overwriting a method. we need // to configure the inner class innerClass.setSuperClass(classNode.getPlainNodeReference()); innerClass.setModifiers(classNode.getModifiers() | Opcodes.ACC_FINAL); // we use a ClassExpression for transportation o EnumVisitor init = new ClassExpression(innerClass); // and remove the final modifier from classNode to allow the sub class classNode.setModifiers(classNode.getModifiers() & ~Opcodes.ACC_FINAL); } else if (isType(ELIST, element)) { if (init instanceof ListExpression && !((ListExpression) init).isWrapped()) { ListExpression le = new ListExpression(); le.addExpression(init); init = le; } } } EnumHelper.addEnumConstant(classNode, identifier, init); enumConstantBeingDef = false; } protected void throwsList(AST node, List list) { String name; if (isType(DOT, node)) { name = qualifiedName(node); } else { name = identifier(node); } ClassNode exception = ClassHelper.make(name); configureAST(exception, node); list.add(exception); AST next = node.getNextSibling(); if (next != null) throwsList(next, list); } protected void methodDef(AST methodDef) { List annotations = new ArrayList(); AST node = methodDef.getFirstChild(); GenericsType[] generics = null; if (isType(TYPE_PARAMETERS, node)) { generics = makeGenericsType(node); node = node.getNextSibling(); } int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); checkNoInvalidModifier(methodDef, "Method", modifiers, Opcodes.ACC_VOLATILE, "volatile"); node = node.getNextSibling(); } if (isAnInterface()) { modifiers |= Opcodes.ACC_ABSTRACT; } ClassNode returnType = null; if (isType(TYPE, node)) { returnType = makeTypeWithArguments(node); node = node.getNextSibling(); } String name = identifier(node); if (classNode != null && !classNode.isAnnotationDefinition()) { if (classNode.getNameWithoutPackage().equals(name)) { if (isAnInterface()) { throw new ASTRuntimeException(methodDef, "Constructor not permitted within an interface."); } throw new ASTRuntimeException(methodDef, "Invalid constructor format. Remove '" + returnType.getName() + "' as the return type if you want a constructor, or use a different name if you want a method."); } } node = node.getNextSibling(); Parameter[] parameters = Parameter.EMPTY_ARRAY; ClassNode[] exceptions = ClassNode.EMPTY_ARRAY; if (classNode == null || !classNode.isAnnotationDefinition()) { assertNodeType(PARAMETERS, node); parameters = parameters(node); if (parameters == null) parameters = Parameter.EMPTY_ARRAY; node = node.getNextSibling(); if (isType(LITERAL_throws, node)) { AST throwsNode = node.getFirstChild(); List exceptionList = new ArrayList(); throwsList(throwsNode, exceptionList); exceptions = exceptionList.toArray(exceptions); node = node.getNextSibling(); } } boolean hasAnnotationDefault = false; Statement code = null; if ((modifiers & Opcodes.ACC_ABSTRACT) == 0) { if (node == null) { throw new ASTRuntimeException(methodDef, "You defined a method without body. Try adding a body, or declare it abstract."); } assertNodeType(SLIST, node); code = statementList(node); } else if (node != null && classNode.isAnnotationDefinition()) { code = statement(node); hasAnnotationDefault = true; } else if ((modifiers & Opcodes.ACC_ABSTRACT) > 0) { if (node != null) { throw new ASTRuntimeException(methodDef, "Abstract methods do not define a body."); } } boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; MethodNode methodNode = new MethodNode(name, modifiers, returnType, parameters, exceptions, code); methodNode.addAnnotations(annotations); methodNode.setGenericsTypes(generics); methodNode.setAnnotationDefault(hasAnnotationDefault); methodNode.setSyntheticPublic(syntheticPublic); configureAST(methodNode, methodDef); if (classNode != null) { classNode.addMethod(methodNode); } else { output.addMethod(methodNode); } } private void checkNoInvalidModifier(AST node, String nodeType, int modifiers, int modifier, String modifierText) { if ((modifiers & modifier) != 0) { throw new ASTRuntimeException(node, nodeType + " has an incorrect modifier '" + modifierText + "'."); } } private boolean isAnInterface() { return classNode != null && (classNode.getModifiers() & Opcodes.ACC_INTERFACE) > 0; } protected void staticInit(AST staticInit) { BlockStatement code = (BlockStatement) statementList(staticInit); classNode.addStaticInitializerStatements(code.getStatements(), false); } protected void objectInit(AST init) { BlockStatement code = (BlockStatement) statementList(init); classNode.addObjectInitializerStatements(code); } protected void constructorDef(AST constructorDef) { List annotations = new ArrayList(); AST node = constructorDef.getFirstChild(); int modifiers = Opcodes.ACC_PUBLIC; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); checkNoInvalidModifier(constructorDef, "Constructor", modifiers, Opcodes.ACC_STATIC, "static"); checkNoInvalidModifier(constructorDef, "Constructor", modifiers, Opcodes.ACC_FINAL, "final"); checkNoInvalidModifier(constructorDef, "Constructor", modifiers, Opcodes.ACC_ABSTRACT, "abstract"); checkNoInvalidModifier(constructorDef, "Constructor", modifiers, Opcodes.ACC_NATIVE, "native"); node = node.getNextSibling(); } assertNodeType(PARAMETERS, node); Parameter[] parameters = parameters(node); if (parameters == null) parameters = Parameter.EMPTY_ARRAY; node = node.getNextSibling(); ClassNode[] exceptions = ClassNode.EMPTY_ARRAY; if (isType(LITERAL_throws, node)) { AST throwsNode = node.getFirstChild(); List exceptionList = new ArrayList(); throwsList(throwsNode, exceptionList); exceptions = exceptionList.toArray(exceptions); node = node.getNextSibling(); } assertNodeType(SLIST, node); Statement code = statementList(node); boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; ConstructorNode constructorNode = classNode.addConstructor(modifiers, parameters, exceptions, code); constructorNode.setSyntheticPublic(syntheticPublic); constructorNode.addAnnotations(annotations); configureAST(constructorNode, constructorDef); } protected void fieldDef(AST fieldDef) { List annotations = new ArrayList(); AST node = fieldDef.getFirstChild(); int modifiers = 0; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); node = node.getNextSibling(); } if (classNode.isInterface()) { modifiers |= Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; if ((modifiers & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) { modifiers |= Opcodes.ACC_PUBLIC; } } ClassNode type = null; if (isType(TYPE, node)) { type = makeTypeWithArguments(node); node = node.getNextSibling(); } String name = identifier(node); node = node.getNextSibling(); Expression initialValue = null; if (node != null) { assertNodeType(ASSIGN, node); initialValue = expression(node.getFirstChild()); } if (classNode.isInterface() && initialValue == null && type != null) { if (type == ClassHelper.int_TYPE) { initialValue = new ConstantExpression(0); } else if (type == ClassHelper.long_TYPE) { initialValue = new ConstantExpression(0L); } else if (type == ClassHelper.double_TYPE) { initialValue = new ConstantExpression(0.0); } else if (type == ClassHelper.float_TYPE) { initialValue = new ConstantExpression(0.0F); } else if (type == ClassHelper.boolean_TYPE) { initialValue = ConstantExpression.FALSE; } else if (type == ClassHelper.short_TYPE) { initialValue = new ConstantExpression((short) 0); } else if (type == ClassHelper.byte_TYPE) { initialValue = new ConstantExpression((byte) 0); } else if (type == ClassHelper.char_TYPE) { initialValue = new ConstantExpression((char) 0); } } FieldNode fieldNode = new FieldNode(name, modifiers, type, classNode, initialValue); fieldNode.addAnnotations(annotations); configureAST(fieldNode, fieldDef); if (!hasVisibility(modifiers)) { // let's set the modifiers on the field int fieldModifiers = 0; int flags = Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT | Opcodes.ACC_VOLATILE | Opcodes.ACC_FINAL; if (!hasVisibility(modifiers)) { modifiers |= Opcodes.ACC_PUBLIC; fieldModifiers |= Opcodes.ACC_PRIVATE; } // let's pass along any other modifiers we need fieldModifiers |= (modifiers & flags); fieldNode.setModifiers(fieldModifiers); fieldNode.setSynthetic(true); // in the case that there is already a field, we would // like to use that field, instead of the default field // for the property FieldNode storedNode = classNode.getDeclaredField(fieldNode.getName()); if (storedNode != null && !classNode.hasProperty(name)) { fieldNode = storedNode; // we remove it here, because addProperty will add it // again and we want to avoid it showing up multiple // times in the fields list. classNode.getFields().remove(storedNode); } PropertyNode propertyNode = new PropertyNode(fieldNode, modifiers, null, null); configureAST(propertyNode, fieldDef); classNode.addProperty(propertyNode); } else { fieldNode.setModifiers(modifiers); // if there is a property of that name, then a field of that // name already exists, which means this new field here should // be used instead of the field the property originally has. PropertyNode pn = classNode.getProperty(name); if (pn != null && pn.getField().isSynthetic()) { classNode.getFields().remove(pn.getField()); pn.setField(fieldNode); } classNode.addField(fieldNode); } } protected ClassNode[] interfaces(AST node) { List interfaceList = new ArrayList(); for (AST implementNode = node.getFirstChild(); implementNode != null; implementNode = implementNode.getNextSibling()) { interfaceList.add(makeTypeWithArguments(implementNode)); } ClassNode[] interfaces = ClassNode.EMPTY_ARRAY; if (!interfaceList.isEmpty()) { interfaces = new ClassNode[interfaceList.size()]; interfaceList.toArray(interfaces); } return interfaces; } protected Parameter[] parameters(AST parametersNode) { AST node = parametersNode.getFirstChild(); firstParam = false; firstParamIsVarArg = false; if (node == null) { if (isType(IMPLICIT_PARAMETERS, parametersNode)) return Parameter.EMPTY_ARRAY; return null; } else { List parameters = new ArrayList(); AST firstParameterNode = null; do { firstParam = (firstParameterNode == null); if (firstParameterNode == null) firstParameterNode = node; parameters.add(parameter(node)); node = node.getNextSibling(); } while (node != null); verifyParameters(parameters, firstParameterNode); Parameter[] answer = new Parameter[parameters.size()]; parameters.toArray(answer); return answer; } } private void verifyParameters(List parameters, AST firstParameterNode) { if (parameters.size() <= 1) return; Parameter first = parameters.get(0); if (firstParamIsVarArg) { throw new ASTRuntimeException(firstParameterNode, "The var-arg parameter " + first.getName() + " must be the last parameter."); } } protected Parameter parameter(AST paramNode) { List annotations = new ArrayList(); boolean variableParameterDef = isType(VARIABLE_PARAMETER_DEF, paramNode); AST node = paramNode.getFirstChild(); int modifiers = 0; if (isType(MODIFIERS, node)) { modifiers = modifiers(node, annotations, modifiers); node = node.getNextSibling(); } ClassNode type = ClassHelper.DYNAMIC_TYPE; if (isType(TYPE, node)) { type = makeTypeWithArguments(node); if (variableParameterDef) type = type.makeArray(); node = node.getNextSibling(); } String name = identifier(node); node = node.getNextSibling(); VariableExpression leftExpression = new VariableExpression(name, type); leftExpression.setModifiers(modifiers); configureAST(leftExpression, paramNode); Parameter parameter = null; if (node != null) { assertNodeType(ASSIGN, node); Expression rightExpression = expression(node.getFirstChild()); if (isAnInterface()) { throw new ASTRuntimeException(node, "Cannot specify default value for method parameter '" + name + " = " + rightExpression.getText() + "' inside an interface"); } parameter = new Parameter(type, name, rightExpression); } else parameter = new Parameter(type, name); if (firstParam) firstParamIsVarArg = variableParameterDef; configureAST(parameter, paramNode); parameter.addAnnotations(annotations); parameter.setModifiers(modifiers); return parameter; } protected int modifiers(AST modifierNode, List annotations, int defaultModifiers) { assertNodeType(MODIFIERS, modifierNode); boolean access = false; int answer = 0; for (AST node = modifierNode.getFirstChild(); node != null; node = node.getNextSibling()) { int type = node.getType(); switch (type) { case STATIC_IMPORT: // ignore break; // annotations case ANNOTATION: annotations.add(annotation(node)); break; // core access scope modifiers case LITERAL_private: answer = setModifierBit(node, answer, Opcodes.ACC_PRIVATE); access = setAccessTrue(node, access); break; case LITERAL_protected: answer = setModifierBit(node, answer, Opcodes.ACC_PROTECTED); access = setAccessTrue(node, access); break; case LITERAL_public: answer = setModifierBit(node, answer, Opcodes.ACC_PUBLIC); access = setAccessTrue(node, access); break; // other modifiers case ABSTRACT: answer = setModifierBit(node, answer, Opcodes.ACC_ABSTRACT); break; case FINAL: answer = setModifierBit(node, answer, Opcodes.ACC_FINAL); break; case LITERAL_native: answer = setModifierBit(node, answer, Opcodes.ACC_NATIVE); break; case LITERAL_static: answer = setModifierBit(node, answer, Opcodes.ACC_STATIC); break; case STRICTFP: answer = setModifierBit(node, answer, Opcodes.ACC_STRICT); break; case LITERAL_synchronized: answer = setModifierBit(node, answer, Opcodes.ACC_SYNCHRONIZED); break; case LITERAL_transient: answer = setModifierBit(node, answer, Opcodes.ACC_TRANSIENT); break; case LITERAL_volatile: answer = setModifierBit(node, answer, Opcodes.ACC_VOLATILE); break; default: unknownAST(node); } } if (!access) { answer |= defaultModifiers; // ACC_SYNTHETIC isn't used here, use it as a special flag if (defaultModifiers == Opcodes.ACC_PUBLIC) answer |= Opcodes.ACC_SYNTHETIC; } return answer; } protected boolean setAccessTrue(AST node, boolean access) { if (!access) { return true; } else { throw new ASTRuntimeException(node, "Cannot specify modifier: " + node.getText() + " when access scope has already been defined"); } } protected int setModifierBit(AST node, int answer, int bit) { if ((answer & bit) != 0) { throw new ASTRuntimeException(node, "Cannot repeat modifier: " + node.getText()); } return answer | bit; } protected AnnotationNode annotation(AST annotationNode) { AST node = annotationNode.getFirstChild(); String name = qualifiedName(node); AnnotationNode annotatedNode = new AnnotationNode(ClassHelper.make(name)); configureAST(annotatedNode, annotationNode); while (true) { node = node.getNextSibling(); if (isType(ANNOTATION_MEMBER_VALUE_PAIR, node)) { AST memberNode = node.getFirstChild(); String param = identifier(memberNode); Expression expression = expression(memberNode.getNextSibling()); if (annotatedNode.getMember(param) != null) { throw new ASTRuntimeException(memberNode, "Annotation member '" + param + "' has already been associated with a value"); } annotatedNode.setMember(param, expression); } else { break; } } return annotatedNode; } // Statements //------------------------------------------------------------------------- protected Statement statement(AST node) { Statement statement = null; int type = node.getType(); switch (type) { case SLIST: case LITERAL_finally: statement = statementList(node); break; case METHOD_CALL: statement = methodCall(node); break; case VARIABLE_DEF: statement = variableDef(node); break; case LABELED_STAT: return labelledStatement(node); case LITERAL_assert: statement = assertStatement(node); break; case LITERAL_break: statement = breakStatement(node); break; case LITERAL_continue: statement = continueStatement(node); break; case LITERAL_if: statement = ifStatement(node); break; case LITERAL_for: statement = forStatement(node); break; case LITERAL_return: statement = returnStatement(node); break; case LITERAL_synchronized: statement = synchronizedStatement(node); break; case LITERAL_switch: statement = switchStatement(node); break; case LITERAL_try: statement = tryStatement(node); break; case LITERAL_throw: statement = throwStatement(node); break; case LITERAL_while: statement = whileStatement(node); break; default: statement = new ExpressionStatement(expression(node)); } if (statement != null) { configureAST(statement, node); } return statement; } protected Statement statementList(AST code) { return statementListNoChild(code.getFirstChild(), code); } protected Statement statementListNoChild(AST node, AST alternativeConfigureNode) { BlockStatement block = new BlockStatement(); // alternativeConfigureNode is used only to set the source position if (node != null) { configureAST(block, node); } else { configureAST(block, alternativeConfigureNode); } for (; node != null; node = node.getNextSibling()) { block.addStatement(statement(node)); } return block; } protected Statement assertStatement(AST assertNode) { AST node = assertNode.getFirstChild(); BooleanExpression booleanExpression = booleanExpression(node); Expression messageExpression = null; node = node.getNextSibling(); if (node != null) { messageExpression = expression(node); } else { messageExpression = ConstantExpression.NULL; } AssertStatement assertStatement = new AssertStatement(booleanExpression, messageExpression); configureAST(assertStatement, assertNode); return assertStatement; } protected Statement breakStatement(AST node) { BreakStatement breakStatement = new BreakStatement(label(node)); configureAST(breakStatement, node); return breakStatement; } protected Statement continueStatement(AST node) { ContinueStatement continueStatement = new ContinueStatement(label(node)); configureAST(continueStatement, node); return continueStatement; } protected Statement forStatement(AST forNode) { AST inNode = forNode.getFirstChild(); Expression collectionExpression; Parameter forParameter; if (isType(CLOSURE_LIST, inNode)) { forStatementBeingDef = true; ClosureListExpression clist = closureListExpression(inNode); forStatementBeingDef = false; int size = clist.getExpressions().size(); if (size != 3) { throw new ASTRuntimeException(inNode, "3 expressions are required for the classic for loop, you gave " + size); } collectionExpression = clist; forParameter = ForStatement.FOR_LOOP_DUMMY; } else { AST variableNode = inNode.getFirstChild(); AST collectionNode = variableNode.getNextSibling(); ClassNode type = ClassHelper.OBJECT_TYPE; if (isType(VARIABLE_DEF, variableNode)) { AST node = variableNode.getFirstChild(); // skip the final modifier if it's present if (isType(MODIFIERS, node)) { int modifiersMask = modifiers(node, new ArrayList(), 0); // only final modifier allowed if ((modifiersMask & ~Opcodes.ACC_FINAL) != 0) { throw new ASTRuntimeException(node, "Only the 'final' modifier is allowed in front of the for loop variable."); } node = node.getNextSibling(); } type = makeTypeWithArguments(node); variableNode = node.getNextSibling(); } String variable = identifier(variableNode); collectionExpression = expression(collectionNode); forParameter = new Parameter(type, variable); configureAST(forParameter, variableNode); } final AST node = inNode.getNextSibling(); Statement block; if (isType(SEMI, node)) { block = EmptyStatement.INSTANCE; } else { block = statement(node); } ForStatement forStatement = new ForStatement(forParameter, collectionExpression, block); configureAST(forStatement, forNode); return forStatement; } protected Statement ifStatement(AST ifNode) { AST node = ifNode.getFirstChild(); assertNodeType(EXPR, node); BooleanExpression booleanExpression = booleanExpression(node); node = node.getNextSibling(); Statement ifBlock = statement(node); Statement elseBlock = EmptyStatement.INSTANCE; node = node.getNextSibling(); if (node != null) { elseBlock = statement(node); } IfStatement ifStatement = new IfStatement(booleanExpression, ifBlock, elseBlock); configureAST(ifStatement, ifNode); return ifStatement; } protected Statement labelledStatement(AST labelNode) { AST node = labelNode.getFirstChild(); String label = identifier(node); Statement statement = statement(node.getNextSibling()); if (statement.getStatementLabel() == null) // if statement has multiple labels, retain the last one statement.setStatementLabel(label); return statement; } protected Statement methodCall(AST code) { Expression expression = methodCallExpression(code); ExpressionStatement expressionStatement = new ExpressionStatement(expression); configureAST(expressionStatement, code); return expressionStatement; } protected Expression declarationExpression(AST variableDef) { AST node = variableDef.getFirstChild(); ClassNode type = null; List annotations = new ArrayList(); int modifiers = 0; if (isType(MODIFIERS, node)) { // force check of modifier conflicts modifiers = modifiers(node, annotations, 0); node = node.getNextSibling(); } if (isType(TYPE, node)) { type = makeTypeWithArguments(node); node = node.getNextSibling(); } Expression leftExpression; Expression rightExpression = EmptyExpression.INSTANCE; AST right; if (isType(ASSIGN, node)) { node = node.getFirstChild(); AST left = node.getFirstChild(); ArgumentListExpression alist = new ArgumentListExpression(); for (AST varDef = left; varDef != null; varDef = varDef.getNextSibling()) { assertNodeType(VARIABLE_DEF, varDef); DeclarationExpression de = (DeclarationExpression) declarationExpression(varDef); alist.addExpression(de.getVariableExpression()); } leftExpression = alist; right = node.getNextSibling(); if (right != null) rightExpression = expression(right); } else { String name = identifier(node); VariableExpression ve = new VariableExpression(name, type); ve.setModifiers(modifiers); leftExpression = ve; right = node.getNextSibling(); if (right != null) { assertNodeType(ASSIGN, right); rightExpression = expression(right.getFirstChild()); } } configureAST(leftExpression, node); Token token = makeToken(Types.ASSIGN, variableDef); DeclarationExpression expression = new DeclarationExpression(leftExpression, token, rightExpression); expression.addAnnotations(annotations); configureAST(expression, variableDef); ExpressionStatement expressionStatement = new ExpressionStatement(expression); configureAST(expressionStatement, variableDef); return expression; } protected Statement variableDef(AST variableDef) { ExpressionStatement expressionStatement = new ExpressionStatement(declarationExpression(variableDef)); configureAST(expressionStatement, variableDef); return expressionStatement; } protected Statement returnStatement(AST node) { AST exprNode = node.getFirstChild(); // This will pick up incorrect sibling node if 'node' is a plain 'return' // //if (exprNode == null) { // exprNode = node.getNextSibling(); //} Expression expression = exprNode == null ? ConstantExpression.NULL : expression(exprNode); ReturnStatement returnStatement = new ReturnStatement(expression); configureAST(returnStatement, node); return returnStatement; } protected Statement switchStatement(AST switchNode) { AST node = switchNode.getFirstChild(); Expression expression = expression(node); Statement defaultStatement = EmptyStatement.INSTANCE; List list = new ArrayList(); for (node = node.getNextSibling(); isType(CASE_GROUP, node); node = node.getNextSibling()) { Statement tmpDefaultStatement; AST child = node.getFirstChild(); if (isType(LITERAL_case, child)) { List cases = new LinkedList(); // default statement can be grouped with previous case tmpDefaultStatement = caseStatements(child, cases); list.addAll(cases); } else { tmpDefaultStatement = statement(child.getNextSibling()); } if (tmpDefaultStatement != EmptyStatement.INSTANCE) { if (defaultStatement == EmptyStatement.INSTANCE) { defaultStatement = tmpDefaultStatement; } else { throw new ASTRuntimeException(switchNode, "The default case is already defined."); } } } if (node != null) { unknownAST(node); } SwitchStatement switchStatement = new SwitchStatement(expression, list, defaultStatement); configureAST(switchStatement, switchNode); return switchStatement; } protected Statement caseStatements(AST node, List cases) { List expressions = new LinkedList(); Statement statement = EmptyStatement.INSTANCE; Statement defaultStatement = EmptyStatement.INSTANCE; AST nextSibling = node; do { Expression expression = expression(nextSibling.getFirstChild()); expressions.add(expression); nextSibling = nextSibling.getNextSibling(); } while (isType(LITERAL_case, nextSibling)); if (nextSibling != null) { if (isType(LITERAL_default, nextSibling)) { defaultStatement = statement(nextSibling.getNextSibling()); statement = EmptyStatement.INSTANCE; } else { statement = statement(nextSibling); } } Iterator iterator = expressions.iterator(); while (iterator.hasNext()) { Expression expr = (Expression) iterator.next(); Statement stmt; if (iterator.hasNext()) { stmt = new CaseStatement(expr, EmptyStatement.INSTANCE); } else { stmt = new CaseStatement(expr, statement); } configureAST(stmt, node); cases.add(stmt); } return defaultStatement; } protected Statement synchronizedStatement(AST syncNode) { AST node = syncNode.getFirstChild(); Expression expression = expression(node); Statement code = statement(node.getNextSibling()); SynchronizedStatement synchronizedStatement = new SynchronizedStatement(expression, code); configureAST(synchronizedStatement, syncNode); return synchronizedStatement; } protected Statement throwStatement(AST node) { AST expressionNode = node.getFirstChild(); if (expressionNode == null) { expressionNode = node.getNextSibling(); } if (expressionNode == null) { throw new ASTRuntimeException(node, "No expression available"); } ThrowStatement throwStatement = new ThrowStatement(expression(expressionNode)); configureAST(throwStatement, node); return throwStatement; } protected Statement tryStatement(AST tryStatementNode) { AST tryNode = tryStatementNode.getFirstChild(); Statement tryStatement = statement(tryNode); Statement finallyStatement = EmptyStatement.INSTANCE; AST node = tryNode.getNextSibling(); // let's do the catch nodes List catches = new ArrayList(); for (; node != null && isType(LITERAL_catch, node); node = node.getNextSibling()) { catches.add(catchStatement(node)); } if (isType(LITERAL_finally, node)) { finallyStatement = statement(node); node = node.getNextSibling(); } if (finallyStatement instanceof EmptyStatement && catches.size() == 0) { throw new ASTRuntimeException(tryStatementNode, "A try statement must have at least one catch or finally block."); } TryCatchStatement tryCatchStatement = new TryCatchStatement(tryStatement, finallyStatement); configureAST(tryCatchStatement, tryStatementNode); for (CatchStatement statement : catches) { tryCatchStatement.addCatch(statement); } return tryCatchStatement; } protected CatchStatement catchStatement(AST catchNode) { AST node = catchNode.getFirstChild(); Parameter parameter = parameter(node); ClassNode exceptionType = parameter.getType(); String variable = parameter.getName(); node = node.getNextSibling(); Statement code = statement(node); Parameter catchParameter = new Parameter(exceptionType, variable); CatchStatement answer = new CatchStatement(catchParameter, code); configureAST(answer, catchNode); return answer; } protected Statement whileStatement(AST whileNode) { AST node = whileNode.getFirstChild(); assertNodeType(EXPR, node); // TODO remove this once we support declarations in the while condition if (isType(VARIABLE_DEF, node.getFirstChild())) { throw new ASTRuntimeException(whileNode, "While loop condition contains a declaration; this is currently unsupported."); } BooleanExpression booleanExpression = booleanExpression(node); node = node.getNextSibling(); Statement block; if (isType(SEMI, node)) { block = EmptyStatement.INSTANCE; } else { block = statement(node); } WhileStatement whileStatement = new WhileStatement(booleanExpression, block); configureAST(whileStatement, whileNode); return whileStatement; } // Expressions //------------------------------------------------------------------------- protected Expression expression(AST node) { return expression(node, false); } protected Expression expression(AST node, boolean convertToConstant) { Expression expression = expressionSwitch(node); if (convertToConstant && expression instanceof VariableExpression) { // a method name can never be a VariableExpression, so it must converted // to a ConstantExpression then. This is needed as the expression // method doesn't know we want a ConstantExpression instead of a // VariableExpression VariableExpression ve = (VariableExpression) expression; if (!ve.isThisExpression() && !ve.isSuperExpression()) { expression = new ConstantExpression(ve.getName()); } } configureAST(expression, node); return expression; } protected Expression expressionSwitch(AST node) { int type = node.getType(); switch (type) { case EXPR: return expression(node.getFirstChild()); case ELIST: return expressionList(node); case SLIST: return blockExpression(node); case CLOSABLE_BLOCK: return closureExpression(node); case SUPER_CTOR_CALL: return specialConstructorCallExpression(node, ClassNode.SUPER); case METHOD_CALL: return methodCallExpression(node); case LITERAL_new: return constructorCallExpression(node); case CTOR_CALL: return specialConstructorCallExpression(node, ClassNode.THIS); case QUESTION: case ELVIS_OPERATOR: return ternaryExpression(node); case OPTIONAL_DOT: case SPREAD_DOT: case DOT: return dotExpression(node); case IDENT: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_double: case LITERAL_float: case LITERAL_int: case LITERAL_long: case LITERAL_short: case LITERAL_void: case LITERAL_this: case LITERAL_super: return variableExpression(node); case LIST_CONSTRUCTOR: return listExpression(node); case MAP_CONSTRUCTOR: return mapExpression(node); case LABELED_ARG: return mapEntryExpression(node); case SPREAD_ARG: return spreadExpression(node); case SPREAD_MAP_ARG: return spreadMapExpression(node); // commented out of groovy.g due to non determinisms //case MEMBER_POINTER_DEFAULT: // return defaultMethodPointerExpression(node); case MEMBER_POINTER: return methodPointerExpression(node); case INDEX_OP: return indexExpression(node); case LITERAL_instanceof: return instanceofExpression(node); case LITERAL_as: return asExpression(node); case TYPECAST: return castExpression(node); // literals case LITERAL_true: return literalExpression(node, Boolean.TRUE); case LITERAL_false: return literalExpression(node, Boolean.FALSE); case LITERAL_null: return literalExpression(node, null); case STRING_LITERAL: return literalExpression(node, node.getText()); case STRING_CONSTRUCTOR: return gstring(node); case NUM_DOUBLE: case NUM_FLOAT: case NUM_BIG_DECIMAL: return decimalExpression(node); case NUM_BIG_INT: case NUM_INT: case NUM_LONG: return integerExpression(node); // Unary expressions case LNOT: NotExpression notExpression = new NotExpression(expression(node.getFirstChild())); configureAST(notExpression, node); return notExpression; case UNARY_MINUS: return unaryMinusExpression(node); case BNOT: BitwiseNegationExpression bitwiseNegationExpression = new BitwiseNegationExpression(expression(node.getFirstChild())); configureAST(bitwiseNegationExpression, node); return bitwiseNegationExpression; case UNARY_PLUS: return unaryPlusExpression(node); // Prefix expressions case INC: return prefixExpression(node, Types.PLUS_PLUS); case DEC: return prefixExpression(node, Types.MINUS_MINUS); // Postfix expressions case POST_INC: return postfixExpression(node, Types.PLUS_PLUS); case POST_DEC: return postfixExpression(node, Types.MINUS_MINUS); // Binary expressions case ASSIGN: return binaryExpression(Types.ASSIGN, node); case EQUAL: return binaryExpression(Types.COMPARE_EQUAL, node); case IDENTICAL: return binaryExpression(Types.COMPARE_IDENTICAL, node); case NOT_EQUAL: return binaryExpression(Types.COMPARE_NOT_EQUAL, node); case NOT_IDENTICAL: return binaryExpression(Types.COMPARE_NOT_IDENTICAL, node); case COMPARE_TO: return binaryExpression(Types.COMPARE_TO, node); case LE: return binaryExpression(Types.COMPARE_LESS_THAN_EQUAL, node); case LT: return binaryExpression(Types.COMPARE_LESS_THAN, node); case GT: return binaryExpression(Types.COMPARE_GREATER_THAN, node); case GE: return binaryExpression(Types.COMPARE_GREATER_THAN_EQUAL, node); /** * TODO treble equal? return binaryExpression(Types.COMPARE_IDENTICAL, node); case ???: return binaryExpression(Types.LOGICAL_AND_EQUAL, node); case ???: return binaryExpression(Types.LOGICAL_OR_EQUAL, node); */ case LAND: return binaryExpression(Types.LOGICAL_AND, node); case LOR: return binaryExpression(Types.LOGICAL_OR, node); case BAND: return binaryExpression(Types.BITWISE_AND, node); case BAND_ASSIGN: return binaryExpression(Types.BITWISE_AND_EQUAL, node); case BOR: return binaryExpression(Types.BITWISE_OR, node); case BOR_ASSIGN: return binaryExpression(Types.BITWISE_OR_EQUAL, node); case BXOR: return binaryExpression(Types.BITWISE_XOR, node); case BXOR_ASSIGN: return binaryExpression(Types.BITWISE_XOR_EQUAL, node); case PLUS: return binaryExpression(Types.PLUS, node); case PLUS_ASSIGN: return binaryExpression(Types.PLUS_EQUAL, node); case MINUS: return binaryExpression(Types.MINUS, node); case MINUS_ASSIGN: return binaryExpression(Types.MINUS_EQUAL, node); case STAR: return binaryExpression(Types.MULTIPLY, node); case STAR_ASSIGN: return binaryExpression(Types.MULTIPLY_EQUAL, node); case STAR_STAR: return binaryExpression(Types.POWER, node); case STAR_STAR_ASSIGN: return binaryExpression(Types.POWER_EQUAL, node); case DIV: return binaryExpression(Types.DIVIDE, node); case DIV_ASSIGN: return binaryExpression(Types.DIVIDE_EQUAL, node); case MOD: return binaryExpression(Types.MOD, node); case MOD_ASSIGN: return binaryExpression(Types.MOD_EQUAL, node); case SL: return binaryExpression(Types.LEFT_SHIFT, node); case SL_ASSIGN: return binaryExpression(Types.LEFT_SHIFT_EQUAL, node); case SR: return binaryExpression(Types.RIGHT_SHIFT, node); case SR_ASSIGN: return binaryExpression(Types.RIGHT_SHIFT_EQUAL, node); case BSR: return binaryExpression(Types.RIGHT_SHIFT_UNSIGNED, node); case BSR_ASSIGN: return binaryExpression(Types.RIGHT_SHIFT_UNSIGNED_EQUAL, node); case VARIABLE_DEF: return declarationExpression(node); // Regex case REGEX_FIND: return binaryExpression(Types.FIND_REGEX, node); case REGEX_MATCH: return binaryExpression(Types.MATCH_REGEX, node); // Ranges case RANGE_INCLUSIVE: return rangeExpression(node, true); case RANGE_EXCLUSIVE: return rangeExpression(node, false); case DYNAMIC_MEMBER: return dynamicMemberExpression(node); case LITERAL_in: return binaryExpression(Types.KEYWORD_IN, node); case ANNOTATION: return new AnnotationConstantExpression(annotation(node)); case CLOSURE_LIST: return closureListExpression(node); case LBRACK: case LPAREN: return tupleExpression(node); case OBJBLOCK: return anonymousInnerClassDef(node); default: unknownAST(node); } return null; } private TupleExpression tupleExpression(AST node) { TupleExpression exp = new TupleExpression(); configureAST(exp, node); node = node.getFirstChild(); while (node != null) { assertNodeType(VARIABLE_DEF, node); AST nameNode = node.getFirstChild().getNextSibling(); VariableExpression varExp = new VariableExpression(nameNode.getText()); configureAST(varExp, nameNode); exp.addExpression(varExp); node = node.getNextSibling(); } return exp; } private ClosureListExpression closureListExpression(AST node) { isClosureListExpressionAllowedHere(node); AST exprNode = node.getFirstChild(); List list = new LinkedList(); while (exprNode != null) { if (isType(EXPR, exprNode)) { Expression expr = expression(exprNode); configureAST(expr, exprNode); list.add(expr); } else { assertNodeType(EMPTY_STAT, exprNode); list.add(EmptyExpression.INSTANCE); } exprNode = exprNode.getNextSibling(); } ClosureListExpression cle = new ClosureListExpression(list); configureAST(cle, node); return cle; } private void isClosureListExpressionAllowedHere(AST node) { if (!forStatementBeingDef) { throw new ASTRuntimeException(node, "Expression list of the form (a; b; c) is not supported in this context."); } } protected Expression dynamicMemberExpression(AST dynamicMemberNode) { AST node = dynamicMemberNode.getFirstChild(); return expression(node); } protected Expression ternaryExpression(AST ternaryNode) { AST node = ternaryNode.getFirstChild(); Expression base = expression(node); node = node.getNextSibling(); Expression left = expression(node); node = node.getNextSibling(); Expression ret; if (node == null) { ret = new ElvisOperatorExpression(base, left); } else { Expression right = expression(node); BooleanExpression booleanExpression = new BooleanExpression(base); booleanExpression.setSourcePosition(base); ret = new TernaryExpression(booleanExpression, left, right); } configureAST(ret, ternaryNode); return ret; } protected Expression variableExpression(AST node) { String text = node.getText(); // TODO we might wanna only try to resolve the name if we are // on the left hand side of an expression or before a dot? VariableExpression variableExpression = new VariableExpression(text); configureAST(variableExpression, node); return variableExpression; } protected Expression literalExpression(AST node, Object value) { ConstantExpression constantExpression = new ConstantExpression(value, value instanceof Boolean); configureAST(constantExpression, node); return constantExpression; } protected Expression rangeExpression(AST rangeNode, boolean inclusive) { AST node = rangeNode.getFirstChild(); Expression left = expression(node); Expression right = expression(node.getNextSibling()); RangeExpression rangeExpression = new RangeExpression(left, right, inclusive); configureAST(rangeExpression, rangeNode); return rangeExpression; } protected Expression spreadExpression(AST node) { AST exprNode = node.getFirstChild(); AST listNode = exprNode.getFirstChild(); Expression right = expression(listNode); SpreadExpression spreadExpression = new SpreadExpression(right); configureAST(spreadExpression, node); return spreadExpression; } protected Expression spreadMapExpression(AST node) { AST exprNode = node.getFirstChild(); Expression expr = expression(exprNode); SpreadMapExpression spreadMapExpression = new SpreadMapExpression(expr); configureAST(spreadMapExpression, node); return spreadMapExpression; } protected Expression methodPointerExpression(AST node) { AST exprNode = node.getFirstChild(); Expression objectExpression = expression(exprNode); AST mNode = exprNode.getNextSibling(); Expression methodName; if (isType(DYNAMIC_MEMBER, mNode)) { methodName = expression(mNode); } else { methodName = new ConstantExpression(identifier(mNode)); } configureAST(methodName, mNode); MethodPointerExpression methodPointerExpression = new MethodPointerExpression(objectExpression, methodName); configureAST(methodPointerExpression, node); return methodPointerExpression; } /* commented out due to groovy.g non-determinisms protected Expression defaultMethodPointerExpression(AST node) { AST exprNode = node.getFirstChild(); String methodName = exprNode.toString(); MethodPointerExpression methodPointerExpression = new MethodPointerExpression(null, methodName); configureAST(methodPointerExpression, node); return methodPointerExpression; } */ protected Expression listExpression(AST listNode) { List expressions = new ArrayList(); AST elist = listNode.getFirstChild(); assertNodeType(ELIST, elist); for (AST node = elist.getFirstChild(); node != null; node = node.getNextSibling()) { // check for stray labeled arguments: switch (node.getType()) { case LABELED_ARG: assertNodeType(COMMA, node); break; // helpful error? case SPREAD_MAP_ARG: assertNodeType(SPREAD_ARG, node); break; // helpful error } expressions.add(expression(node)); } ListExpression listExpression = new ListExpression(expressions); configureAST(listExpression, listNode); return listExpression; } /** * Typically only used for map constructors I think? */ protected Expression mapExpression(AST mapNode) { List expressions = new ArrayList(); AST elist = mapNode.getFirstChild(); if (elist != null) { // totally empty in the case of [:] assertNodeType(ELIST, elist); for (AST node = elist.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getType()) { case LABELED_ARG: case SPREAD_MAP_ARG: break; // legal cases case SPREAD_ARG: assertNodeType(SPREAD_MAP_ARG, node); break; // helpful error default: assertNodeType(LABELED_ARG, node); break; // helpful error } expressions.add(mapEntryExpression(node)); } } MapExpression mapExpression = new MapExpression(expressions); configureAST(mapExpression, mapNode); return mapExpression; } protected MapEntryExpression mapEntryExpression(AST node) { if (node.getType() == SPREAD_MAP_ARG) { AST rightNode = node.getFirstChild(); Expression keyExpression = spreadMapExpression(node); Expression rightExpression = expression(rightNode); MapEntryExpression mapEntryExpression = new MapEntryExpression(keyExpression, rightExpression); configureAST(mapEntryExpression, node); return mapEntryExpression; } else { AST keyNode = node.getFirstChild(); Expression keyExpression = expression(keyNode); AST valueNode = keyNode.getNextSibling(); Expression valueExpression = expression(valueNode); MapEntryExpression mapEntryExpression = new MapEntryExpression(keyExpression, valueExpression); configureAST(mapEntryExpression, node); return mapEntryExpression; } } protected Expression instanceofExpression(AST node) { AST leftNode = node.getFirstChild(); Expression leftExpression = expression(leftNode); AST rightNode = leftNode.getNextSibling(); ClassNode type = buildName(rightNode); assertTypeNotNull(type, rightNode); Expression rightExpression = new ClassExpression(type); configureAST(rightExpression, rightNode); BinaryExpression binaryExpression = new BinaryExpression(leftExpression, makeToken(Types.KEYWORD_INSTANCEOF, node), rightExpression); configureAST(binaryExpression, node); return binaryExpression; } protected void assertTypeNotNull(ClassNode type, AST rightNode) { if (type == null) { throw new ASTRuntimeException(rightNode, "No type available for: " + qualifiedName(rightNode)); } } protected Expression asExpression(AST node) { AST leftNode = node.getFirstChild(); Expression leftExpression = expression(leftNode); AST rightNode = leftNode.getNextSibling(); ClassNode type = makeTypeWithArguments(rightNode); return CastExpression.asExpression(type, leftExpression); } protected Expression castExpression(AST castNode) { AST node = castNode.getFirstChild(); ClassNode type = makeTypeWithArguments(node); assertTypeNotNull(type, node); AST expressionNode = node.getNextSibling(); Expression expression = expression(expressionNode); CastExpression castExpression = new CastExpression(type, expression); configureAST(castExpression, castNode); return castExpression; } protected Expression indexExpression(AST indexNode) { AST bracket = indexNode.getFirstChild(); AST leftNode = bracket.getNextSibling(); Expression leftExpression = expression(leftNode); AST rightNode = leftNode.getNextSibling(); Expression rightExpression = expression(rightNode); BinaryExpression binaryExpression = new BinaryExpression(leftExpression, makeToken(Types.LEFT_SQUARE_BRACKET, bracket), rightExpression); configureAST(binaryExpression, indexNode); return binaryExpression; } protected Expression binaryExpression(int type, AST node) { Token token = makeToken(type, node); AST leftNode = node.getFirstChild(); Expression leftExpression = expression(leftNode); AST rightNode = leftNode.getNextSibling(); if (rightNode == null) { return leftExpression; } if (Types.ofType(type, Types.ASSIGNMENT_OPERATOR)) { if (leftExpression instanceof VariableExpression || leftExpression.getClass() == PropertyExpression.class || leftExpression instanceof FieldExpression || leftExpression instanceof AttributeExpression || leftExpression instanceof DeclarationExpression || leftExpression instanceof TupleExpression) { // Do nothing. } else if (leftExpression instanceof ConstantExpression) { throw new ASTRuntimeException(node, "\n[" + ((ConstantExpression) leftExpression).getValue() + "] is a constant expression, but it should be a variable expression"); } else if (leftExpression instanceof BinaryExpression) { Expression leftexp = ((BinaryExpression) leftExpression).getLeftExpression(); int lefttype = ((BinaryExpression) leftExpression).getOperation().getType(); if (!Types.ofType(lefttype, Types.ASSIGNMENT_OPERATOR) && lefttype != Types.LEFT_SQUARE_BRACKET) { throw new ASTRuntimeException(node, "\n" + ((BinaryExpression) leftExpression).getText() + " is a binary expression, but it should be a variable expression"); } } else if (leftExpression instanceof GStringExpression) { throw new ASTRuntimeException(node, "\n\"" + ((GStringExpression) leftExpression).getText() + "\" is a GString expression, but it should be a variable expression"); } else if (leftExpression instanceof MethodCallExpression) { throw new ASTRuntimeException(node, "\n\"" + ((MethodCallExpression) leftExpression).getText() + "\" is a method call expression, but it should be a variable expression"); } else if (leftExpression instanceof MapExpression) { throw new ASTRuntimeException(node, "\n'" + ((MapExpression) leftExpression).getText() + "' is a map expression, but it should be a variable expression"); } else { throw new ASTRuntimeException(node, "\n" + leftExpression.getClass() + ", with its value '" + leftExpression.getText() + "', is a bad expression as the left hand side of an assignment operator"); } } /*if (rightNode == null) { throw new NullPointerException("No rightNode associated with binary expression"); }*/ Expression rightExpression = expression(rightNode); BinaryExpression binaryExpression = new BinaryExpression(leftExpression, token, rightExpression); configureAST(binaryExpression, node); return binaryExpression; } protected Expression prefixExpression(AST node, int token) { Expression expression = expression(node.getFirstChild()); PrefixExpression prefixExpression = new PrefixExpression(makeToken(token, node), expression); configureAST(prefixExpression, node); return prefixExpression; } protected Expression postfixExpression(AST node, int token) { Expression expression = expression(node.getFirstChild()); PostfixExpression postfixExpression = new PostfixExpression(expression, makeToken(token, node)); configureAST(postfixExpression, node); return postfixExpression; } protected BooleanExpression booleanExpression(AST node) { BooleanExpression booleanExpression = new BooleanExpression(expression(node)); configureAST(booleanExpression, node); return booleanExpression; } protected Expression dotExpression(AST node) { // let's decide if this is a property invocation or a method call AST leftNode = node.getFirstChild(); if (leftNode != null) { AST identifierNode = leftNode.getNextSibling(); if (identifierNode != null) { Expression leftExpression = expression(leftNode); if (isType(SELECT_SLOT, identifierNode)) { Expression field = expression(identifierNode.getFirstChild(), true); AttributeExpression attributeExpression = new AttributeExpression(leftExpression, field, node.getType() != DOT); if (node.getType() == SPREAD_DOT) { attributeExpression.setSpreadSafe(true); } configureAST(attributeExpression, node); return attributeExpression; } if (isType(SLIST, identifierNode)) { Statement code = statementList(identifierNode); ClosureExpression closureExpression = new ClosureExpression(Parameter.EMPTY_ARRAY, code); configureAST(closureExpression, identifierNode); final PropertyExpression propertyExpression = new PropertyExpression(leftExpression, closureExpression); if (node.getType() == SPREAD_DOT) { propertyExpression.setSpreadSafe(true); } configureAST(propertyExpression, node); return propertyExpression; } Expression property = expression(identifierNode, true); // A."this" assumes a VariableExpression can be used for "this" // we correct that here into a ConstantExpression if (property instanceof VariableExpression) { VariableExpression ve = (VariableExpression) property; property = new ConstantExpression(ve.getName()); } PropertyExpression propertyExpression = new PropertyExpression(leftExpression, property, node.getType() != DOT); if (node.getType() == SPREAD_DOT) { propertyExpression.setSpreadSafe(true); } configureAST(propertyExpression, node); return propertyExpression; } } return methodCallExpression(node); } protected Expression specialConstructorCallExpression(AST methodCallNode, ClassNode special) { AST node = methodCallNode.getFirstChild(); Expression arguments = arguments(node); ConstructorCallExpression expression = new ConstructorCallExpression(special, arguments); configureAST(expression, methodCallNode); return expression; } private int getTypeInParenthesis(AST node) { if (!isType(EXPR, node)) node = node.getFirstChild(); while (node != null && isType(EXPR, node) && node.getNextSibling() == null) { node = node.getFirstChild(); } if (node == null) return -1; return node.getType(); } protected Expression methodCallExpression(AST methodCallNode) { AST node = methodCallNode.getFirstChild(); Expression objectExpression; AST selector; AST elist = node.getNextSibling(); List typeArgumentList = null; boolean implicitThis = false; boolean safe = isType(OPTIONAL_DOT, node); boolean spreadSafe = isType(SPREAD_DOT, node); if (isType(DOT, node) || safe || spreadSafe) { AST objectNode = node.getFirstChild(); objectExpression = expression(objectNode); selector = objectNode.getNextSibling(); } else { implicitThis = true; objectExpression = VariableExpression.THIS_EXPRESSION; selector = node; } if (isType(TYPE_ARGUMENTS, selector)) { typeArgumentList = getTypeArgumentsList(selector); selector = selector.getNextSibling(); } Expression name = null; if (isType(LITERAL_super, selector)) { implicitThis = true; name = new ConstantExpression("super"); if (objectExpression instanceof VariableExpression && ((VariableExpression) objectExpression).isThisExpression()) { objectExpression = VariableExpression.SUPER_EXPRESSION; } } else if (isPrimitiveTypeLiteral(selector)) { throw new ASTRuntimeException(selector, "Primitive type literal: " + selector.getText() + " cannot be used as a method name"); } else if (isType(SELECT_SLOT, selector)) { Expression field = expression(selector.getFirstChild(), true); AttributeExpression attributeExpression = new AttributeExpression(objectExpression, field, node.getType() != DOT); configureAST(attributeExpression, node); Expression arguments = arguments(elist); MethodCallExpression expression = new MethodCallExpression(attributeExpression, "call", arguments); setTypeArgumentsOnMethodCallExpression(expression, typeArgumentList); configureAST(expression, methodCallNode); return expression; } else if (!implicitThis || isType(DYNAMIC_MEMBER, selector) || isType(IDENT, selector) || isType(STRING_CONSTRUCTOR, selector) || isType(STRING_LITERAL, selector)) { name = expression(selector, true); } else { implicitThis = false; name = new ConstantExpression("call"); objectExpression = expression(selector, true); } // if node text is found to be "super"/"this" when a method call is being processed, it is a // call like this(..)/super(..) after the first statement, which shouldn't be allowed. GROOVY-2836 if (selector.getText().equals("this") || selector.getText().equals("super")) { throw new ASTRuntimeException(elist, "Constructor call must be the first statement in a constructor."); } Expression arguments = arguments(elist); MethodCallExpression expression = new MethodCallExpression(objectExpression, name, arguments); expression.setSafe(safe); expression.setSpreadSafe(spreadSafe); expression.setImplicitThis(implicitThis); setTypeArgumentsOnMethodCallExpression(expression, typeArgumentList); Expression ret = expression; //FIXME: do we really want this() to create a new object regardless // the position.. for example not as first statement in a constructor // this=first statement in constructor is handled by specialConstructorCallExpression // we may have to add a check and remove this part of the code if (implicitThis && "this".equals(expression.getMethodAsString())) { ret = new ConstructorCallExpression(this.classNode, arguments); } configureAST(ret, methodCallNode); return ret; } private void setTypeArgumentsOnMethodCallExpression(MethodCallExpression expression, List typeArgumentList) { if (typeArgumentList != null && typeArgumentList.size() > 0) { expression.setGenericsTypes(typeArgumentList.toArray(new GenericsType[typeArgumentList.size()])); } } protected Expression constructorCallExpression(AST node) { AST constructorCallNode = node; ClassNode type = makeTypeWithArguments(constructorCallNode); if (isType(CTOR_CALL, node) || isType(LITERAL_new, node)) { node = node.getFirstChild(); } AST elist = node.getNextSibling(); if (elist == null && isType(ELIST, node)) { elist = node; if ("(".equals(type.getName())) { type = classNode; } } if (isType(ARRAY_DECLARATOR, elist)) { AST expressionNode = elist.getFirstChild(); if (expressionNode == null) { throw new ASTRuntimeException(elist, "No expression for the array constructor call"); } List size = arraySizeExpression(expressionNode); ArrayExpression arrayExpression = new ArrayExpression(type, null, size); configureAST(arrayExpression, constructorCallNode); return arrayExpression; } Expression arguments = arguments(elist); ClassNode innerClass = getAnonymousInnerClassNode(arguments); ConstructorCallExpression ret = new ConstructorCallExpression(type, arguments); if (innerClass != null) { ret.setType(innerClass); ret.setUsingAnonymousInnerClass(true); innerClass.setUnresolvedSuperClass(type); } configureAST(ret, constructorCallNode); return ret; } private ClassNode getAnonymousInnerClassNode(Expression arguments) { if (arguments instanceof TupleExpression) { TupleExpression te = (TupleExpression) arguments; List expressions = te.getExpressions(); if (expressions.size() == 0) return null; Expression last = (Expression) expressions.remove(expressions.size() - 1); if (last instanceof AnonymousInnerClassCarrier) { AnonymousInnerClassCarrier carrier = (AnonymousInnerClassCarrier) last; return carrier.innerClass; } else { expressions.add(last); } } else if (arguments instanceof AnonymousInnerClassCarrier) { AnonymousInnerClassCarrier carrier = (AnonymousInnerClassCarrier) arguments; return carrier.innerClass; } return null; } protected List arraySizeExpression(AST node) { List list; Expression size = null; if (isType(ARRAY_DECLARATOR, node)) { AST right = node.getNextSibling(); if (right != null) { size = expression(right); } else { size = ConstantExpression.EMPTY_EXPRESSION; } list = arraySizeExpression(node.getFirstChild()); } else { size = expression(node); list = new ArrayList(); } list.add(size); return list; } protected Expression arguments(AST elist) { List expressionList = new ArrayList(); // FIXME: all labeled arguments should follow any unlabeled arguments boolean namedArguments = false; for (AST node = elist; node != null; node = node.getNextSibling()) { if (isType(ELIST, node)) { for (AST child = node.getFirstChild(); child != null; child = child.getNextSibling()) { namedArguments |= addArgumentExpression(child, expressionList); } } else { namedArguments |= addArgumentExpression(node, expressionList); } } if (namedArguments) { if (!expressionList.isEmpty()) { // let's remove any non-MapEntryExpression instances // such as if the last expression is a ClosureExpression // so let's wrap the named method calls in a Map expression List argumentList = new ArrayList(); for (Object next : expressionList) { Expression expression = (Expression) next; if (!(expression instanceof MapEntryExpression)) { argumentList.add(expression); } } if (!argumentList.isEmpty()) { expressionList.removeAll(argumentList); checkDuplicateNamedParams(elist, expressionList); MapExpression mapExpression = new MapExpression(expressionList); configureAST(mapExpression, elist); argumentList.add(0, mapExpression); ArgumentListExpression argumentListExpression = new ArgumentListExpression(argumentList); configureAST(argumentListExpression, elist); return argumentListExpression; } } checkDuplicateNamedParams(elist, expressionList); NamedArgumentListExpression namedArgumentListExpression = new NamedArgumentListExpression(expressionList); configureAST(namedArgumentListExpression, elist); return namedArgumentListExpression; } else { ArgumentListExpression argumentListExpression = new ArgumentListExpression(expressionList); configureAST(argumentListExpression, elist); return argumentListExpression; } } private void checkDuplicateNamedParams(AST elist, List expressionList) { if (expressionList.isEmpty()) return; Set namedArgumentNames = new HashSet(); for (Object expression : expressionList) { MapEntryExpression meExp = (MapEntryExpression) expression; if (meExp.getKeyExpression() instanceof ConstantExpression) { String argName = meExp.getKeyExpression().getText(); if (!namedArgumentNames.contains(argName)) { namedArgumentNames.add(argName); } else { throw new ASTRuntimeException(elist, "Duplicate named parameter '" + argName + "' found."); } } } } protected boolean addArgumentExpression(AST node, List expressionList) { if (node.getType() == SPREAD_MAP_ARG) { AST rightNode = node.getFirstChild(); Expression keyExpression = spreadMapExpression(node); Expression rightExpression = expression(rightNode); MapEntryExpression mapEntryExpression = new MapEntryExpression(keyExpression, rightExpression); expressionList.add(mapEntryExpression); return true; } else { Expression expression = expression(node); expressionList.add(expression); return expression instanceof MapEntryExpression; } } protected Expression expressionList(AST node) { List expressionList = new ArrayList(); for (AST child = node.getFirstChild(); child != null; child = child.getNextSibling()) { expressionList.add(expression(child)); } if (expressionList.size() == 1) { return expressionList.get(0); } else { ListExpression listExpression = new ListExpression(expressionList); listExpression.setWrapped(true); configureAST(listExpression, node); return listExpression; } } protected ClosureExpression closureExpression(AST node) { AST paramNode = node.getFirstChild(); Parameter[] parameters = null; AST codeNode = paramNode; if (isType(PARAMETERS, paramNode) || isType(IMPLICIT_PARAMETERS, paramNode)) { parameters = parameters(paramNode); codeNode = paramNode.getNextSibling(); } Statement code = statementListNoChild(codeNode, node); ClosureExpression closureExpression = new ClosureExpression(parameters, code); configureAST(closureExpression, node); return closureExpression; } protected Expression blockExpression(AST node) { AST codeNode = node.getFirstChild(); if (codeNode == null) return ConstantExpression.NULL; if (codeNode.getType() == EXPR && codeNode.getNextSibling() == null) { // Simplify common case of {expr} to expr. return expression(codeNode); } Parameter[] parameters = Parameter.EMPTY_ARRAY; Statement code = statementListNoChild(codeNode, node); ClosureExpression closureExpression = new ClosureExpression(parameters, code); configureAST(closureExpression, node); // Call it immediately. String callName = "call"; Expression noArguments = new ArgumentListExpression(); MethodCallExpression call = new MethodCallExpression(closureExpression, callName, noArguments); configureAST(call, node); return call; } protected Expression unaryMinusExpression(AST unaryMinusExpr) { AST node = unaryMinusExpr.getFirstChild(); // if we are a number literal then let's just parse it // as the negation operator on MIN_INT causes rounding to a long String text = node.getText(); switch (node.getType()) { case NUM_DOUBLE: case NUM_FLOAT: case NUM_BIG_DECIMAL: ConstantExpression constantExpression = new ConstantExpression(Numbers.parseDecimal("-" + text)); configureAST(constantExpression, unaryMinusExpr); return constantExpression; case NUM_BIG_INT: case NUM_INT: case NUM_LONG: ConstantExpression constantLongExpression = new ConstantExpression(Numbers.parseInteger("-" + text)); configureAST(constantLongExpression, unaryMinusExpr); return constantLongExpression; default: UnaryMinusExpression unaryMinusExpression = new UnaryMinusExpression(expression(node)); configureAST(unaryMinusExpression, unaryMinusExpr); return unaryMinusExpression; } } protected Expression unaryPlusExpression(AST unaryPlusExpr) { AST node = unaryPlusExpr.getFirstChild(); switch (node.getType()) { case NUM_DOUBLE: case NUM_FLOAT: case NUM_BIG_DECIMAL: case NUM_BIG_INT: case NUM_INT: case NUM_LONG: return expression(node); default: UnaryPlusExpression unaryPlusExpression = new UnaryPlusExpression(expression(node)); configureAST(unaryPlusExpression, unaryPlusExpr); return unaryPlusExpression; } } protected ConstantExpression decimalExpression(AST node) { String text = node.getText(); Object number = Numbers.parseDecimal(text); ConstantExpression constantExpression = new ConstantExpression(number, number instanceof Double); configureAST(constantExpression, node); return constantExpression; } protected ConstantExpression integerExpression(AST node) { String text = node.getText(); Object number = Numbers.parseInteger(text); ConstantExpression constantExpression = new ConstantExpression(number, number instanceof Integer); configureAST(constantExpression, node); return constantExpression; } protected Expression gstring(AST gstringNode) { List strings = new ArrayList(); List values = new ArrayList(); StringBuffer buffer = new StringBuffer(); boolean isPrevString = false; for (AST node = gstringNode.getFirstChild(); node != null; node = node.getNextSibling()) { int type = node.getType(); String text = null; switch (type) { case STRING_LITERAL: if (isPrevString) assertNodeType(IDENT, node); // parser bug isPrevString = true; text = node.getText(); ConstantExpression constantExpression = new ConstantExpression(text); configureAST(constantExpression, node); strings.add(constantExpression); buffer.append(text); break; default: { if (!isPrevString) assertNodeType(IDENT, node); // parser bug isPrevString = false; Expression expression = expression(node); values.add(expression); buffer.append("$"); buffer.append(expression.getText()); } break; } } GStringExpression gStringExpression = new GStringExpression(buffer.toString(), strings, values); configureAST(gStringExpression, gstringNode); return gStringExpression; } protected ClassNode type(AST typeNode) { // TODO intern types? // TODO configureAST(...) return buildName(typeNode.getFirstChild()); } public static String qualifiedName(AST qualifiedNameNode) { if (isType(IDENT, qualifiedNameNode)) { return qualifiedNameNode.getText(); } if (isType(DOT, qualifiedNameNode)) { AST node = qualifiedNameNode.getFirstChild(); StringBuffer buffer = new StringBuffer(); boolean first = true; for (; node != null && !isType(TYPE_ARGUMENTS, node); node = node.getNextSibling()) { if (first) { first = false; } else { buffer.append("."); } buffer.append(qualifiedName(node)); } return buffer.toString(); } else { return qualifiedNameNode.getText(); } } private static AST getTypeArgumentsNode(AST root) { while (root != null && !isType(TYPE_ARGUMENTS, root)) { root = root.getNextSibling(); } return root; } private int getBoundType(AST node) { if (node == null) return -1; if (isType(TYPE_UPPER_BOUNDS, node)) return TYPE_UPPER_BOUNDS; if (isType(TYPE_LOWER_BOUNDS, node)) return TYPE_LOWER_BOUNDS; throw new ASTRuntimeException(node, "Unexpected node type: " + getTokenName(node) + " found when expecting type: " + getTokenName(TYPE_UPPER_BOUNDS) + " or type: " + getTokenName(TYPE_LOWER_BOUNDS)); } private GenericsType makeGenericsArgumentType(AST typeArgument) { GenericsType gt; AST rootNode = typeArgument.getFirstChild(); if (isType(WILDCARD_TYPE, rootNode)) { ClassNode base = ClassHelper.makeWithoutCaching("?"); if (rootNode.getNextSibling() != null) { int boundType = getBoundType(rootNode.getNextSibling()); ClassNode[] gts = makeGenericsBounds(rootNode, boundType); if (boundType == TYPE_UPPER_BOUNDS) { gt = new GenericsType(base, gts, null); } else { gt = new GenericsType(base, null, gts[0]); } } else { gt = new GenericsType(base, null, null); } gt.setName("?"); gt.setWildcard(true); } else { ClassNode argument = makeTypeWithArguments(rootNode); gt = new GenericsType(argument); } configureAST(gt, typeArgument); return gt; } protected ClassNode makeTypeWithArguments(AST rootNode) { ClassNode basicType = makeType(rootNode); AST node = rootNode.getFirstChild(); if (node == null || isType(INDEX_OP, node) || isType(ARRAY_DECLARATOR, node)) return basicType; if (!isType(DOT, node)) { node = node.getFirstChild(); if (node == null) return basicType; return addTypeArguments(basicType, node); } else { node = node.getFirstChild(); while (node != null && !isType(TYPE_ARGUMENTS, node)) node = node.getNextSibling(); return node == null ? basicType : addTypeArguments(basicType, node); } } private ClassNode addTypeArguments(ClassNode basicType, AST node) { List typeArgumentList = getTypeArgumentsList(node); if (typeArgumentList.size() > 0) { basicType.setGenericsTypes(typeArgumentList.toArray(new GenericsType[typeArgumentList.size()])); } return basicType; } private List getTypeArgumentsList(AST node) { assertNodeType(TYPE_ARGUMENTS, node); List typeArgumentList = new LinkedList(); AST typeArgument = node.getFirstChild(); while (typeArgument != null) { assertNodeType(TYPE_ARGUMENT, typeArgument); GenericsType gt = makeGenericsArgumentType(typeArgument); typeArgumentList.add(gt); typeArgument = typeArgument.getNextSibling(); } return typeArgumentList; } private ClassNode[] makeGenericsBounds(AST rn, int boundType) { AST boundsRoot = rn.getNextSibling(); if (boundsRoot == null) return null; assertNodeType(boundType, boundsRoot); LinkedList bounds = new LinkedList(); for (AST boundsNode = boundsRoot.getFirstChild(); boundsNode != null; boundsNode = boundsNode.getNextSibling() ) { ClassNode bound = null; bound = makeTypeWithArguments(boundsNode); configureAST(bound, boundsNode); bounds.add(bound); } if (bounds.size() == 0) return null; return (ClassNode[]) bounds.toArray(new ClassNode[bounds.size()]); } protected GenericsType[] makeGenericsType(AST rootNode) { AST typeParameter = rootNode.getFirstChild(); LinkedList ret = new LinkedList(); assertNodeType(TYPE_PARAMETER, typeParameter); while (isType(TYPE_PARAMETER, typeParameter)) { AST typeNode = typeParameter.getFirstChild(); ClassNode type = makeType(typeParameter); GenericsType gt = new GenericsType(type, makeGenericsBounds(typeNode, TYPE_UPPER_BOUNDS), null); configureAST(gt, typeParameter); ret.add(gt); typeParameter = typeParameter.getNextSibling(); } return (GenericsType[]) ret.toArray(new GenericsType[0]); } protected ClassNode makeType(AST typeNode) { ClassNode answer = ClassHelper.DYNAMIC_TYPE; AST node = typeNode.getFirstChild(); if (node != null) { if (isType(INDEX_OP, node) || isType(ARRAY_DECLARATOR, node)) { answer = makeType(node).makeArray(); } else { answer = ClassHelper.make(qualifiedName(node)); if (answer.isUsingGenerics()) { ClassNode newAnswer = ClassHelper.makeWithoutCaching(answer.getName()); newAnswer.setRedirect(answer); answer = newAnswer; } } configureAST(answer, node); } return answer; } /** * Performs a name resolution to see if the given name is a type from imports, * aliases or newly created classes */ /*protected String resolveTypeName(String name, boolean safe) { if (name == null) { return null; } return resolveNewClassOrName(name, safe); }*/ /** * Extracts an identifier from the Antlr AST and then performs a name resolution * to see if the given name is a type from imports, aliases or newly created classes */ protected ClassNode buildName(AST node) { if (isType(TYPE, node)) { node = node.getFirstChild(); } ClassNode answer = null; if (isType(DOT, node) || isType(OPTIONAL_DOT, node)) { answer = ClassHelper.make(qualifiedName(node)); } else if (isPrimitiveTypeLiteral(node)) { answer = ClassHelper.make(node.getText()); } else if (isType(INDEX_OP, node) || isType(ARRAY_DECLARATOR, node)) { AST child = node.getFirstChild(); answer = buildName(child).makeArray(); configureAST(answer, node); return answer; } else { String identifier = node.getText(); answer = ClassHelper.make(identifier); } AST nextSibling = node.getNextSibling(); if (isType(INDEX_OP, nextSibling) || isType(ARRAY_DECLARATOR, node)) { answer = answer.makeArray(); configureAST(answer, node); return answer; } else { configureAST(answer, node); return answer; } } protected boolean isPrimitiveTypeLiteral(AST node) { int type = node.getType(); switch (type) { case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_double: case LITERAL_float: case LITERAL_int: case LITERAL_long: case LITERAL_short: return true; default: return false; } } /** * Extracts an identifier from the Antlr AST */ protected String identifier(AST node) { assertNodeType(IDENT, node); return node.getText(); } protected String label(AST labelNode) { AST node = labelNode.getFirstChild(); if (node == null) { return null; } return identifier(node); } // Helper methods //------------------------------------------------------------------------- /** * Returns true if the modifiers flags contain a visibility modifier */ protected boolean hasVisibility(int modifiers) { return (modifiers & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) != 0; } protected void configureAST(ASTNode node, AST ast) { if (ast == null) throw new ASTRuntimeException(ast, "PARSER BUG: Tried to configure " + node.getClass().getName() + " with null Node"); node.setColumnNumber(ast.getColumn()); node.setLineNumber(ast.getLine()); if (ast instanceof GroovySourceAST) { node.setLastColumnNumber(((GroovySourceAST) ast).getColumnLast()); node.setLastLineNumber(((GroovySourceAST) ast).getLineLast()); } // TODO we could one day store the Antlr AST on the Groovy AST // node.setCSTNode(ast); } protected static Token makeToken(int typeCode, AST node) { return Token.newSymbol(typeCode, node.getLine(), node.getColumn()); } protected String getFirstChildText(AST node) { AST child = node.getFirstChild(); return child != null ? child.getText() : null; } public static boolean isType(int typeCode, AST node) { return node != null && node.getType() == typeCode; } private String getTokenName(int token) { if (tokenNames == null) return "" + token; return tokenNames[token]; } private String getTokenName(AST node) { if (node == null) return "null"; return getTokenName(node.getType()); } protected void assertNodeType(int type, AST node) { if (node == null) { throw new ASTRuntimeException(node, "No child node available in AST when expecting type: " + getTokenName(type)); } if (node.getType() != type) { throw new ASTRuntimeException(node, "Unexpected node type: " + getTokenName(node) + " found when expecting type: " + getTokenName(type)); } } protected void notImplementedYet(AST node) { throw new ASTRuntimeException(node, "AST node not implemented yet for type: " + getTokenName(node)); } protected void unknownAST(AST node) { if (node.getType() == CLASS_DEF) { throw new ASTRuntimeException(node, "Class definition not expected here. Please define the class at an appropriate place or perhaps try using a block/Closure instead."); } if (node.getType() == METHOD_DEF) { throw new ASTRuntimeException(node, "Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead."); } throw new ASTRuntimeException(node, "Unknown type: " + getTokenName(node)); } protected void dumpTree(AST ast) { for (AST node = ast.getFirstChild(); node != null; node = node.getNextSibling()) { dump(node); } } protected void dump(AST node) { System.out.println("Type: " + getTokenName(node) + " text: " + node.getText()); } } groovy-1.8.6/src/main/org/codehaus/groovy/antlr/GroovySourceAST.java0000644001501200150120000001055411627206700025022 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.antlr; import antlr.CommonAST; import antlr.Token; import antlr.collections.AST; import java.util.ArrayList; import java.util.List; /** * We have an AST subclass so we can track source information. * Very odd that ANTLR doesn't do this by default. * * @author Mike Spille * @author Jeremy Rayner */ public class GroovySourceAST extends CommonAST implements Comparable, SourceInfo { private int line; private int col; private int lineLast; private int colLast; private String snippet; public GroovySourceAST() { } public GroovySourceAST(Token t) { super(t); } public void initialize(AST ast) { super.initialize(ast); line = ast.getLine(); col = ast.getColumn(); if (ast instanceof GroovySourceAST) { GroovySourceAST node = (GroovySourceAST)ast; lineLast = node.getLineLast(); colLast = node.getColumnLast(); } } public void initialize(Token t) { super.initialize(t); line = t.getLine(); col = t.getColumn(); if (t instanceof SourceInfo) { SourceInfo info = (SourceInfo) t; lineLast = info.getLineLast(); colLast = info.getColumnLast(); } } public void setLast(Token last) { lineLast = last.getLine(); colLast = last.getColumn(); } public int getLineLast() { return lineLast; } public void setLineLast(int lineLast) { this.lineLast = lineLast; } public int getColumnLast() { return colLast; } public void setColumnLast(int colLast) { this.colLast = colLast; } public void setLine(int line) { this.line = line; } public int getLine() { return (line); } public void setColumn(int column) { this.col = column; } public int getColumn() { return (col); } public void setSnippet(String snippet) { this.snippet = snippet; } public String getSnippet() { return snippet; } public int compareTo(Object object) { if (object == null) { return 0; } if (!(object instanceof AST)) { return 0; } AST that = (AST) object; // todo - possibly check for line/col with values of 0 or less... if (this.getLine() < that.getLine()) { return -1; } if (this.getLine() > that.getLine()) { return 1; } if (this.getColumn() < that.getColumn()) { return -1; } if (this.getColumn() > that.getColumn()) { return 1; } return 0; } public GroovySourceAST childAt(int position) { List list = new ArrayList(); AST child = this.getFirstChild(); while (child != null) { list.add(child); child = child.getNextSibling(); } try { return (GroovySourceAST)list.get(position); } catch (IndexOutOfBoundsException e) { return null; } } public GroovySourceAST childOfType(int type) { AST child = this.getFirstChild(); while (child != null) { if (child.getType() == type) { return (GroovySourceAST)child; } child = child.getNextSibling(); } return null; } public List childrenOfType(int type) { List result = new ArrayList(); AST child = this.getFirstChild(); while (child != null) { if (child.getType() == type) { result.add((GroovySourceAST) child); } child = child.getNextSibling(); } return result; } } groovy-1.8.6/src/main/org/codehaus/groovy/syntax/0000755001501200150120000000000011715031256021342 5ustar miguelmiguelgroovy-1.8.6/src/main/org/codehaus/groovy/syntax/Types.java0000644001501200150120000016174011627206700023322 0ustar miguelmiguel/* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.syntax; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.Collections; import java.util.Collection; import org.codehaus.groovy.GroovyBugError; /** * Typing information for the CST system. The types here are those * used by CSTNode, Token, and Reduction. * * @author bob mcwhirter * @author Chris Poirier * * @version $Id$ */ public class Types { //--------------------------------------------------------------------------- // TYPES: NOTE THAT ORDERING AND VALUES ARE IMPORTANT TO LOCAL ROUTINES! // // SPECIAL TOKENS public static final int EOF = -1; // end of file public static final int UNKNOWN = 0; // the unknown token // // RELEVANT WHITESPACE public static final int NEWLINE = 5; // \n // // OPERATORS AND OTHER MARKERS public static final int LEFT_CURLY_BRACE = 10; // { public static final int RIGHT_CURLY_BRACE = 20; // } public static final int LEFT_SQUARE_BRACKET = 30; // [ public static final int RIGHT_SQUARE_BRACKET = 40; // ] public static final int LEFT_PARENTHESIS = 50; // ( public static final int RIGHT_PARENTHESIS = 60; // ) public static final int DOT = 70; // . public static final int DOT_DOT = 75; // .. public static final int DOT_DOT_DOT = 77; // ... public static final int NAVIGATE = 80; // -> public static final int FIND_REGEX = 90; // =~ public static final int MATCH_REGEX = 94; // ==~ public static final int REGEX_PATTERN = 97; // ~ public static final int EQUAL = 100; // = public static final int EQUALS = EQUAL; public static final int ASSIGN = EQUAL; public static final int COMPARE_NOT_EQUAL = 120; // != public static final int COMPARE_IDENTICAL = 121; // === public static final int COMPARE_NOT_IDENTICAL = 122; // !== public static final int COMPARE_EQUAL = 123; // == public static final int COMPARE_LESS_THAN = 124; // < public static final int COMPARE_LESS_THAN_EQUAL = 125; // <= public static final int COMPARE_GREATER_THAN = 126; // > public static final int COMPARE_GREATER_THAN_EQUAL = 127; // >= public static final int COMPARE_TO = 128; // <=> public static final int NOT = 160; // ! public static final int LOGICAL_OR = 162; // || public static final int LOGICAL_AND = 164; // && public static final int LOGICAL_OR_EQUAL = 166; // ||= public static final int LOGICAL_AND_EQUAL = 168; // &&= public static final int PLUS = 200; // + public static final int MINUS = 201; // - public static final int MULTIPLY = 202; // * public static final int DIVIDE = 203; // / public static final int INTDIV = 204; // \ public static final int MOD = 205; // % public static final int STAR_STAR = 206; // ** public static final int POWER = STAR_STAR; // ** public static final int PLUS_EQUAL = 210; // += public static final int MINUS_EQUAL = 211; // -= public static final int MULTIPLY_EQUAL = 212; // *= public static final int DIVIDE_EQUAL = 213; // /= public static final int INTDIV_EQUAL = 214; // \= public static final int MOD_EQUAL = 215; // %= public static final int POWER_EQUAL = 216; // **= public static final int PLUS_PLUS = 250; // ++ public static final int PREFIX_PLUS_PLUS = 251; // ++ public static final int POSTFIX_PLUS_PLUS = 252; // ++ public static final int PREFIX_PLUS = 253; // + public static final int MINUS_MINUS = 260; // -- public static final int PREFIX_MINUS_MINUS = 261; // -- public static final int POSTFIX_MINUS_MINUS = 262; // -- public static final int PREFIX_MINUS = 263; // - (negation) public static final int LEFT_SHIFT = 280; // << public static final int RIGHT_SHIFT = 281; // >> public static final int RIGHT_SHIFT_UNSIGNED = 282; // >>> public static final int LEFT_SHIFT_EQUAL = 285; // <<= public static final int RIGHT_SHIFT_EQUAL = 286; // >>= public static final int RIGHT_SHIFT_UNSIGNED_EQUAL = 287; // >>>= public static final int STAR = MULTIPLY; public static final int COMMA = 300; // - public static final int COLON = 310; // : public static final int SEMICOLON = 320; // ; public static final int QUESTION = 330; // ? // TODO refactor PIPE to be BITWISE_OR public static final int PIPE = 340; // | public static final int DOUBLE_PIPE = LOGICAL_OR; // || public static final int BITWISE_OR = PIPE; // | public static final int BITWISE_AND = 341; // & public static final int BITWISE_XOR = 342; // ^ public static final int BITWISE_OR_EQUAL = 350; // |= public static final int BITWISE_AND_EQUAL = 351; // &= public static final int BITWISE_XOR_EQUAL = 352; // ^= public static final int BITWISE_NEGATION = REGEX_PATTERN; // ~ // // LITERALS public static final int STRING = 400; // any bare string data public static final int IDENTIFIER = 440; // anything text and not a keyword public static final int INTEGER_NUMBER = 450; // integer public static final int DECIMAL_NUMBER = 451; // decimal // // KEYWORDS: (PRIMARILY) CLASS/METHOD DECLARATION MODIFIERS public static final int KEYWORD_PRIVATE = 500; // declaration visibility public static final int KEYWORD_PROTECTED = 501; // declaration visibility public static final int KEYWORD_PUBLIC = 502; // declaration visibility public static final int KEYWORD_ABSTRACT = 510; // method body missing public static final int KEYWORD_FINAL = 511; // declaration cannot be overridden public static final int KEYWORD_NATIVE = 512; // a native code entry point public static final int KEYWORD_TRANSIENT = 513; // property should not be persisted public static final int KEYWORD_VOLATILE = 514; // compiler should never cache property public static final int KEYWORD_SYNCHRONIZED = 520; // modifier and block type public static final int KEYWORD_STATIC = 521; // modifier and block type // // KEYWORDS: TYPE SYSTEM public static final int KEYWORD_DEF = 530; // identifies a function declaration public static final int KEYWORD_DEFMACRO = 539; // XXX br identifies a macro declaration public static final int KEYWORD_CLASS = 531; // identifies a class declaration public static final int KEYWORD_INTERFACE = 532; // identifies an interface declaration public static final int KEYWORD_MIXIN = 533; // identifies a mixin declaration public static final int KEYWORD_IMPLEMENTS = 540; // specifies the interfaces implemented by a class public static final int KEYWORD_EXTENDS = 541; // specifies the base class/interface for a new one public static final int KEYWORD_THIS = 542; // method variable points to the current instance public static final int KEYWORD_SUPER = 543; // method variable points to the base instance public static final int KEYWORD_INSTANCEOF = 544; // type comparator public static final int KEYWORD_PROPERTY = 545; // deprecated; identifies a property public static final int KEYWORD_NEW = 546; // used to create a new instance of a class public static final int KEYWORD_PACKAGE = 550; // declares the package scope public static final int KEYWORD_IMPORT = 551; // declares an external class public static final int KEYWORD_AS = 552; // used in import statements to create an alias // // KEYWORDS: CONTROL STRUCTURES public static final int KEYWORD_RETURN = 560; // returns from a closure or method public static final int KEYWORD_IF = 561; // if public static final int KEYWORD_ELSE = 562; // else public static final int KEYWORD_DO = 570; // do loop public static final int KEYWORD_WHILE = 571; // while loop public static final int KEYWORD_FOR = 572; // for loop public static final int KEYWORD_IN = 573; // for (each) loop separator public static final int KEYWORD_BREAK = 574; // exits a loop or block public static final int KEYWORD_CONTINUE = 575; // restarts a loop on the next iteration public static final int KEYWORD_SWITCH = 576; // switch block public static final int KEYWORD_CASE = 577; // item in a switch block public static final int KEYWORD_DEFAULT = 578; // catch-all item in a switch block public static final int KEYWORD_TRY = 580; // block to monitor for exceptions public static final int KEYWORD_CATCH = 581; // catch block for a particular exception public static final int KEYWORD_FINALLY = 582; // block to always execute on exit of the try public static final int KEYWORD_THROW = 583; // statement to throw an exception public static final int KEYWORD_THROWS = 584; // method modifier to declare thrown transactions public static final int KEYWORD_ASSERT = 585; // alternate throw for code invariants // // KEYWORDS: PRIMITIVE TYPES public static final int KEYWORD_VOID = 600; // void public static final int KEYWORD_BOOLEAN = 601; // boolean public static final int KEYWORD_BYTE = 602; // 1 byte integer public static final int KEYWORD_SHORT = 603; // 2 byte integer public static final int KEYWORD_INT = 604; // 4 byte integer public static final int KEYWORD_LONG = 605; // 8 byte integer public static final int KEYWORD_FLOAT = 606; // 32 bit floating point number public static final int KEYWORD_DOUBLE = 607; // 64 bit floating point number public static final int KEYWORD_CHAR = 608; // unicode character code // // KEYWORDS: SPECIAL VALUES public static final int KEYWORD_TRUE = 610; // boolean truth public static final int KEYWORD_FALSE = 611; // boolean false public static final int KEYWORD_NULL = 612; // missing instance // // KEYWORDS: RESERVED public static final int KEYWORD_CONST = 700; // reserved in java and groovy public static final int KEYWORD_GOTO = 701; // reserved in java and groovy // // SPECIAL (CALCULATED) MEANINGS public static final int SYNTH_COMPILATION_UNIT = 800; // reserved: a synthetic root for a CST public static final int SYNTH_CLASS = 801; // applied to class names public static final int SYNTH_INTERFACE = 802; // applied to interface names public static final int SYNTH_MIXIN = 803; // applied to mixin names public static final int SYNTH_METHOD = 804; // applied to method names public static final int SYNTH_PROPERTY = 805; // applied to property names public static final int SYNTH_PARAMETER_DECLARATION = 806; // applied to method/closure parameter names public static final int SYNTH_LIST = 810; // applied to "[" that marks a list public static final int SYNTH_MAP = 811; // applied to "[" that marks a map public static final int SYNTH_GSTRING = 812; // a complete GString public static final int SYNTH_METHOD_CALL = 814; // applied to the optional "(" that marks a call to a method public static final int SYNTH_CAST = 815; // applied to "(" that marks a type cast public static final int SYNTH_BLOCK = 816; // applied to "{" that marks a block public static final int SYNTH_CLOSURE = 817; // applied to "{" that marks a closure public static final int SYNTH_LABEL = 818; // applied to a statement label public static final int SYNTH_TERNARY = 819; // applied to "?" that marks a ternary expression public static final int SYNTH_TUPLE = 820; // applied to "{" that marks an array initializer public static final int SYNTH_VARIABLE_DECLARATION = 830; // applied to an identifier that specifies // the type of a variable declaration // // GSTRING TOKENS public static final int GSTRING_START = 901; // any marker tha begins a GString public static final int GSTRING_END = 902; // any matching marker that ends a GString public static final int GSTRING_EXPRESSION_START = 903; // the ${ marker that starts a GString expression public static final int GSTRING_EXPRESSION_END = 904; // the } marker that ends a GString expresssion // // TYPE CLASSES public static final int ANY = 1000; // anything public static final int NOT_EOF = 1001; // anything but EOF public static final int GENERAL_END_OF_STATEMENT = 1002; // ";", "\n", EOF public static final int ANY_END_OF_STATEMENT = 1003; // ";", "\n", EOF, "}" public static final int ASSIGNMENT_OPERATOR = 1100; // =, +=, etc. public static final int COMPARISON_OPERATOR = 1101; // ==, ===, >, <, etc. public static final int MATH_OPERATOR = 1102; // +, -, / *, %, plus the LOGICAL_OPERATORS public static final int LOGICAL_OPERATOR = 1103; // ||, &&, ! public static final int RANGE_OPERATOR = 1104; // .., ... public static final int REGEX_COMPARISON_OPERATOR = 1105; // =~, etc. public static final int DEREFERENCE_OPERATOR = 1106; // ., -> public static final int BITWISE_OPERATOR = 1107; // |, &, <<, >>, >>>, ^, ~ public static final int PREFIX_OPERATOR = 1200; // ++, !, etc. public static final int POSTFIX_OPERATOR = 1210; // ++, etc. public static final int INFIX_OPERATOR = 1220; // +, -, =, etc. public static final int PREFIX_OR_INFIX_OPERATOR = 1230; // +, - public static final int PURE_PREFIX_OPERATOR = 1235; // prefix +, prefix - public static final int KEYWORD = 1300; // any keyword public static final int SYMBOL = 1301; // any symbol public static final int LITERAL = 1310; // strings, numbers, identifiers public static final int NUMBER = 1320; // integers and decimals public static final int SIGN = 1325; // "+", "-" public static final int NAMED_VALUE = 1330; // true, false, null public static final int TRUTH_VALUE = 1331; // true, false public static final int PRIMITIVE_TYPE = 1340; // void, byte, short, int, etc. public static final int CREATABLE_PRIMITIVE_TYPE = 1341; // any PRIMITIVE_TYPE except void public static final int LOOP = 1350; // do, while, etc. public static final int RESERVED_KEYWORD = 1360; // const, goto, etc. public static final int KEYWORD_IDENTIFIER = 1361; // keywords that can appear as identifiers public static final int SYNTHETIC = 1370; // any of the SYNTH types public static final int TYPE_DECLARATION = 1400; // class, interface, mixin public static final int DECLARATION_MODIFIER = 1410; // public, private, abstract, etc. public static final int TYPE_NAME = 1420; // identifiers, primitive types public static final int CREATABLE_TYPE_NAME = 1430; // identifiers, primitive types except void public static final int MATCHED_CONTAINER = 1500; // (, ), [, ], {, } public static final int LEFT_OF_MATCHED_CONTAINER = 1501; // (, [, { public static final int RIGHT_OF_MATCHED_CONTAINER = 1502; // ), ], } public static final int EXPRESSION = 1900; // all of the below 1900 series public static final int OPERATOR_EXPRESSION = 1901; // "."-"<<" public static final int SYNTH_EXPRESSION = 1902; // cast, ternary, and closure expression public static final int KEYWORD_EXPRESSION = 1903; // new, this, super, instanceof, true, false, null public static final int LITERAL_EXPRESSION = 1904; // LITERAL public static final int ARRAY_EXPRESSION = 1905; // "[" public static final int SIMPLE_EXPRESSION = 1910; // LITERAL, this, true, false, null public static final int COMPLEX_EXPRESSION = 1911; // SIMPLE_EXPRESSION, and various molecules // // TYPE GROUPS (OPERATIONS SUPPORT) public static final int PARAMETER_TERMINATORS = 2000; // ")", "," public static final int ARRAY_ITEM_TERMINATORS = 2001; // "]", "," public static final int TYPE_LIST_TERMINATORS = 2002; // "implements", "throws", "{", "," public static final int OPTIONAL_DATATYPE_FOLLOWERS = 2003; // identifier, "[", "." public static final int SWITCH_BLOCK_TERMINATORS = 2004; // "case", "default", "}" public static final int SWITCH_ENTRIES = 2005; // "case", "default" public static final int METHOD_CALL_STARTERS = 2006; // LITERAL, "(", "{" public static final int UNSAFE_OVER_NEWLINES = 2007; // things the expression parser should cross lines for in it doesn't have to public static final int PRECLUDES_CAST_OPERATOR = 2008; // anything that prevents (X) from being a cast //--------------------------------------------------------------------------- // TYPE HIERARCHIES /** * Given two types, returns true if the second describes the first. */ public static boolean ofType( int specific, int general ) { if( general == specific ) { return true; } switch( general ) { case ANY: return true; case NOT_EOF: return specific >= UNKNOWN && specific <= SYNTH_VARIABLE_DECLARATION; case GENERAL_END_OF_STATEMENT: switch( specific ) { case EOF: case NEWLINE: case SEMICOLON: return true; } break; case ANY_END_OF_STATEMENT: switch( specific ) { case EOF: case NEWLINE: case SEMICOLON: case RIGHT_CURLY_BRACE: return true; } break; case ASSIGNMENT_OPERATOR: return specific == EQUAL || (specific >= PLUS_EQUAL && specific <= POWER_EQUAL) || (specific >= LOGICAL_OR_EQUAL && specific <= LOGICAL_AND_EQUAL) || (specific >= LEFT_SHIFT_EQUAL && specific <= RIGHT_SHIFT_UNSIGNED_EQUAL) || (specific >= BITWISE_OR_EQUAL && specific <= BITWISE_XOR_EQUAL); case COMPARISON_OPERATOR: return specific >= COMPARE_NOT_EQUAL && specific <= COMPARE_TO; case MATH_OPERATOR: return (specific >= PLUS && specific <= RIGHT_SHIFT_UNSIGNED) || (specific >= NOT && specific <= LOGICAL_AND) || (specific >= BITWISE_OR && specific <= BITWISE_XOR); case LOGICAL_OPERATOR: return specific >= NOT && specific <= LOGICAL_AND; case BITWISE_OPERATOR: return (specific >= BITWISE_OR && specific <= BITWISE_XOR) || specific == BITWISE_NEGATION; case RANGE_OPERATOR: return specific == DOT_DOT || specific == DOT_DOT_DOT; case REGEX_COMPARISON_OPERATOR: return specific == FIND_REGEX || specific == MATCH_REGEX; case DEREFERENCE_OPERATOR: return specific == DOT || specific == NAVIGATE; case PREFIX_OPERATOR: switch( specific ) { case MINUS: case PLUS_PLUS: case MINUS_MINUS: return true; } /* FALL THROUGH */ case PURE_PREFIX_OPERATOR: switch( specific ) { case REGEX_PATTERN: case NOT: case PREFIX_PLUS: case PREFIX_PLUS_PLUS: case PREFIX_MINUS: case PREFIX_MINUS_MINUS: case SYNTH_CAST: return true; } break; case POSTFIX_OPERATOR: switch( specific ) { case PLUS_PLUS: case POSTFIX_PLUS_PLUS: case MINUS_MINUS: case POSTFIX_MINUS_MINUS: return true; } break; case INFIX_OPERATOR: switch( specific ) { case DOT: case NAVIGATE: case LOGICAL_OR: case LOGICAL_AND: case BITWISE_OR: case BITWISE_AND: case BITWISE_XOR: case LEFT_SHIFT: case RIGHT_SHIFT: case RIGHT_SHIFT_UNSIGNED: case FIND_REGEX: case MATCH_REGEX: case DOT_DOT: case DOT_DOT_DOT: case KEYWORD_INSTANCEOF: return true; } return (specific >= COMPARE_NOT_EQUAL && specific <= COMPARE_TO) || (specific >= PLUS && specific <= MOD_EQUAL) || specific == EQUAL || (specific >= PLUS_EQUAL && specific <= POWER_EQUAL) || (specific >= LOGICAL_OR_EQUAL && specific <= LOGICAL_AND_EQUAL) || (specific >= LEFT_SHIFT_EQUAL && specific <= RIGHT_SHIFT_UNSIGNED_EQUAL) || (specific >= BITWISE_OR_EQUAL && specific <= BITWISE_XOR_EQUAL); case PREFIX_OR_INFIX_OPERATOR: switch( specific ) { case POWER: case PLUS: case MINUS: case PREFIX_PLUS: case PREFIX_MINUS: return true; } break; case KEYWORD: return specific >= KEYWORD_PRIVATE && specific <= KEYWORD_GOTO; case SYMBOL: return specific >= NEWLINE && specific <= PIPE; case LITERAL: return specific >= STRING && specific <= DECIMAL_NUMBER; case NUMBER: return specific == INTEGER_NUMBER || specific == DECIMAL_NUMBER; case SIGN: switch( specific ) { case PLUS: case MINUS: return true; } break; case NAMED_VALUE: return specific >= KEYWORD_TRUE && specific <= KEYWORD_NULL; case TRUTH_VALUE: return specific == KEYWORD_TRUE || specific == KEYWORD_FALSE; case TYPE_NAME: if( specific == IDENTIFIER ) { return true; } /* FALL THROUGH */ case PRIMITIVE_TYPE: return specific >= KEYWORD_VOID && specific <= KEYWORD_CHAR; case CREATABLE_TYPE_NAME: if( specific == IDENTIFIER ) { return true; } /* FALL THROUGH */ case CREATABLE_PRIMITIVE_TYPE: return specific >= KEYWORD_BOOLEAN && specific <= KEYWORD_CHAR; case LOOP: switch( specific ) { case KEYWORD_DO: case KEYWORD_WHILE: case KEYWORD_FOR: return true; } break; case RESERVED_KEYWORD: return specific >= KEYWORD_CONST && specific <= KEYWORD_GOTO; case KEYWORD_IDENTIFIER: switch( specific ) { case KEYWORD_CLASS: case KEYWORD_INTERFACE: case KEYWORD_MIXIN: case KEYWORD_DEF: case KEYWORD_DEFMACRO: case KEYWORD_IN: case KEYWORD_PROPERTY: return true; } break; case SYNTHETIC: return specific >= SYNTH_COMPILATION_UNIT && specific <= SYNTH_VARIABLE_DECLARATION; case TYPE_DECLARATION: return specific >= KEYWORD_CLASS && specific <= KEYWORD_MIXIN; case DECLARATION_MODIFIER: return specific >= KEYWORD_PRIVATE && specific <= KEYWORD_STATIC; case MATCHED_CONTAINER: switch( specific ) { case LEFT_CURLY_BRACE: case RIGHT_CURLY_BRACE: case LEFT_SQUARE_BRACKET: case RIGHT_SQUARE_BRACKET: case LEFT_PARENTHESIS: case RIGHT_PARENTHESIS: return true; } break; case LEFT_OF_MATCHED_CONTAINER: switch( specific ) { case LEFT_CURLY_BRACE: case LEFT_SQUARE_BRACKET: case LEFT_PARENTHESIS: return true; } break; case RIGHT_OF_MATCHED_CONTAINER: switch( specific ) { case RIGHT_CURLY_BRACE: case RIGHT_SQUARE_BRACKET: case RIGHT_PARENTHESIS: return true; } break; case PARAMETER_TERMINATORS: return specific == RIGHT_PARENTHESIS || specific == COMMA; case ARRAY_ITEM_TERMINATORS: return specific == RIGHT_SQUARE_BRACKET || specific == COMMA; case TYPE_LIST_TERMINATORS: switch( specific ) { case KEYWORD_IMPLEMENTS: case KEYWORD_THROWS: case LEFT_CURLY_BRACE: case COMMA: return true; } break; case OPTIONAL_DATATYPE_FOLLOWERS: switch( specific ) { case IDENTIFIER: case LEFT_SQUARE_BRACKET: case DOT: return true; } break; case SWITCH_BLOCK_TERMINATORS: if( specific == RIGHT_CURLY_BRACE ) { return true; } /* FALL THROUGH */ case SWITCH_ENTRIES: return specific == KEYWORD_CASE || specific == KEYWORD_DEFAULT; case METHOD_CALL_STARTERS: if( specific >= STRING && specific <= DECIMAL_NUMBER ) { return true; } switch( specific ) { case LEFT_PARENTHESIS: case GSTRING_START: case SYNTH_GSTRING: case KEYWORD_NEW: return true; } break; case UNSAFE_OVER_NEWLINES: if( ofType(specific, SYMBOL) ) { switch( specific ) { case LEFT_CURLY_BRACE: case LEFT_PARENTHESIS: case LEFT_SQUARE_BRACKET: case PLUS: case PLUS_PLUS: case MINUS: case MINUS_MINUS: case REGEX_PATTERN: case NOT: return true; } return false; } switch( specific ) { case KEYWORD_INSTANCEOF: case GSTRING_EXPRESSION_START: case GSTRING_EXPRESSION_END: case GSTRING_END: return false; } return true; case PRECLUDES_CAST_OPERATOR: switch( specific ) { case PLUS: case MINUS: case PREFIX_MINUS: case PREFIX_MINUS_MINUS: case PREFIX_PLUS: case PREFIX_PLUS_PLUS: case LEFT_PARENTHESIS: return false; } return !ofType( specific, COMPLEX_EXPRESSION ); case OPERATOR_EXPRESSION: return specific >= DOT && specific <= RIGHT_SHIFT_UNSIGNED; case SYNTH_EXPRESSION: switch( specific ) { case SYNTH_CAST: case SYNTH_CLOSURE: case SYNTH_TERNARY: return true; } break; case KEYWORD_EXPRESSION: switch( specific ) { case KEYWORD_NEW: case KEYWORD_THIS: case KEYWORD_SUPER: case KEYWORD_INSTANCEOF: case KEYWORD_TRUE: case KEYWORD_FALSE: case KEYWORD_NULL: return true; } break; case LITERAL_EXPRESSION: return specific >= STRING && specific <= DECIMAL_NUMBER; case ARRAY_EXPRESSION: return specific == LEFT_SQUARE_BRACKET; case EXPRESSION: if( specific >= DOT && specific <= RIGHT_SHIFT_UNSIGNED ) { return true; } if( specific >= STRING && specific <= DECIMAL_NUMBER ) { return true; } switch( specific ) { case SYNTH_CAST: case SYNTH_CLOSURE: case SYNTH_TERNARY: case SYNTH_GSTRING: case KEYWORD_NEW: case KEYWORD_THIS: case KEYWORD_SUPER: case KEYWORD_INSTANCEOF: case KEYWORD_TRUE: case KEYWORD_FALSE: case KEYWORD_NULL: case LEFT_SQUARE_BRACKET: return true; } break; case COMPLEX_EXPRESSION: switch( specific ) { case KEYWORD_NEW: case SYNTH_METHOD_CALL: case SYNTH_GSTRING: case SYNTH_LIST: case SYNTH_MAP: case SYNTH_CLOSURE: case SYNTH_TERNARY: case SYNTH_VARIABLE_DECLARATION: return true; } /* FALL THROUGH */ case SIMPLE_EXPRESSION: if( specific >= STRING && specific <= DECIMAL_NUMBER ) { return true; } switch( specific ) { case KEYWORD_SUPER: case KEYWORD_THIS: case KEYWORD_TRUE: case KEYWORD_FALSE: case KEYWORD_NULL: return true; } break; } return false; } //--------------------------------------------------------------------------- // TYPE COERSIONS /** * Given two types, returns true if the first can be viewed as the second. * NOTE that canMean() is orthogonal to ofType(). */ public static boolean canMean( int actual, int preferred ) { if( actual == preferred ) { return true; } switch( preferred ) { case SYNTH_PARAMETER_DECLARATION: case IDENTIFIER: switch( actual ) { case IDENTIFIER: case KEYWORD_DEF: case KEYWORD_DEFMACRO: case KEYWORD_CLASS: case KEYWORD_INTERFACE: case KEYWORD_MIXIN: return true; } break; case SYNTH_CLASS: case SYNTH_INTERFACE: case SYNTH_MIXIN: case SYNTH_METHOD: case SYNTH_PROPERTY: return actual == IDENTIFIER; case SYNTH_LIST: case SYNTH_MAP: return actual == LEFT_SQUARE_BRACKET; case SYNTH_CAST: return actual == LEFT_PARENTHESIS; case SYNTH_BLOCK: case SYNTH_CLOSURE: return actual == LEFT_CURLY_BRACE; case SYNTH_LABEL: return actual == COLON; case SYNTH_VARIABLE_DECLARATION: return actual == IDENTIFIER; } return false; } /** * Converts a node from a generic type to a specific prefix type. * Throws a GroovyBugError if the type can't be converted * and requested. */ public static void makePrefix( CSTNode node, boolean throwIfInvalid ) { switch( node.getMeaning() ) { case PLUS: node.setMeaning( PREFIX_PLUS ); break; case MINUS: node.setMeaning( PREFIX_MINUS ); break; case PLUS_PLUS: node.setMeaning( PREFIX_PLUS_PLUS ); break; case MINUS_MINUS: node.setMeaning( PREFIX_MINUS_MINUS ); break; default: if( throwIfInvalid ) { throw new GroovyBugError( "cannot convert to prefix for type [" + node.getMeaning() + "]" ); } } } /** * Converts a node from a generic type to a specific postfix type. * Throws a GroovyBugError if the type can't be converted. */ public static void makePostfix( CSTNode node, boolean throwIfInvalid ) { switch( node.getMeaning() ) { case PLUS_PLUS: node.setMeaning( POSTFIX_PLUS_PLUS ); break; case MINUS_MINUS: node.setMeaning( POSTFIX_MINUS_MINUS ); break; default: if( throwIfInvalid ) { throw new GroovyBugError( "cannot convert to postfix for type [" + node.getMeaning() + "]" ); } } } //--------------------------------------------------------------------------- // OPERATOR PRECEDENCE /** * Returns the precendence of the specified operator. Non-operator's will * receive -1 or a GroovyBugError, depending on your preference. */ public static int getPrecedence( int type, boolean throwIfInvalid ) { switch( type ) { case LEFT_PARENTHESIS: return 0; case EQUAL: case PLUS_EQUAL: case MINUS_EQUAL: case MULTIPLY_EQUAL: case DIVIDE_EQUAL: case INTDIV_EQUAL: case MOD_EQUAL: case POWER_EQUAL: case LOGICAL_OR_EQUAL: case LOGICAL_AND_EQUAL: case LEFT_SHIFT_EQUAL: case RIGHT_SHIFT_EQUAL: case RIGHT_SHIFT_UNSIGNED_EQUAL: case BITWISE_OR_EQUAL: case BITWISE_AND_EQUAL: case BITWISE_XOR_EQUAL: return 5; case QUESTION: return 10; case LOGICAL_OR: return 15; case LOGICAL_AND: return 20; case BITWISE_OR: case BITWISE_AND: case BITWISE_XOR: return 22; case COMPARE_IDENTICAL: case COMPARE_NOT_IDENTICAL: return 24; case COMPARE_NOT_EQUAL: case COMPARE_EQUAL: case COMPARE_LESS_THAN: case COMPARE_LESS_THAN_EQUAL: case COMPARE_GREATER_THAN: case COMPARE_GREATER_THAN_EQUAL: case COMPARE_TO: case FIND_REGEX: case MATCH_REGEX: case KEYWORD_INSTANCEOF: return 25; case DOT_DOT: case DOT_DOT_DOT: return 30; case LEFT_SHIFT: case RIGHT_SHIFT: case RIGHT_SHIFT_UNSIGNED: return 35; case PLUS: case MINUS: return 40; case MULTIPLY: case DIVIDE: case INTDIV: case MOD: return 45; case NOT: case REGEX_PATTERN: return 50; case SYNTH_CAST: return 55; case PLUS_PLUS: case MINUS_MINUS: case PREFIX_PLUS_PLUS: case PREFIX_MINUS_MINUS: case POSTFIX_PLUS_PLUS: case POSTFIX_MINUS_MINUS: return 65; case PREFIX_PLUS: case PREFIX_MINUS: return 70; case POWER: return 72; case SYNTH_METHOD: case LEFT_SQUARE_BRACKET: return 75; case DOT: case NAVIGATE: return 80; case KEYWORD_NEW: return 85; } if( throwIfInvalid ) { throw new GroovyBugError( "precedence requested for non-operator" ); } return -1; } //--------------------------------------------------------------------------- // TEXTS private static final Map TEXTS = new HashMap(); // symbol/keyword type -> text private static final Map LOOKUP = new HashMap(); // text -> symbol/keyword type private static final Set KEYWORDS = new HashSet(); // valid keywords public static Collection getKeywords() { return Collections.unmodifiableSet(KEYWORDS); } public static boolean isKeyword(final String text) { return KEYWORDS.contains(text); } /** * Returns the type for the specified symbol/keyword text. Returns UNKNOWN * if the text isn't found. You can filter finds on a type. */ public static int lookup( String text, int filter ) { int type = UNKNOWN; if( LOOKUP.containsKey(text) ) { type = LOOKUP.get(text); if( filter != UNKNOWN && !ofType(type, filter) ) { type = UNKNOWN; } } return type; } /** * Returns the type for the specified keyword text. Returns UNKNOWN * if the text isn't found. */ public static int lookupKeyword( String text ) { return lookup( text, KEYWORD ); } /** * Returns the type for the specified symbol text. Returns UNKNOWN * if the text isn't found. */ public static int lookupSymbol( String text ) { return lookup( text, SYMBOL ); } /** * Returns the text for the specified type. Returns "" if the * text isn't found. */ public static String getText( int type ) { String text = ""; if( TEXTS.containsKey(type) ) { text = TEXTS.get( type ); } return text; } /** * Adds a element to the TEXTS and LOOKUP. */ private static void addTranslation( String text, int type ) { TEXTS.put( type, text ); LOOKUP.put( text, type ); } /** * Adds a element to the KEYWORDS, TEXTS and LOOKUP. */ private static void addKeyword( String text, int type ) { KEYWORDS.add(text); addTranslation(text, type); } static { // // SYMBOLS addTranslation( "\n" , NEWLINE ); addTranslation( "{" , LEFT_CURLY_BRACE ); addTranslation( "}" , RIGHT_CURLY_BRACE ); addTranslation( "[" , LEFT_SQUARE_BRACKET ); addTranslation( "]" , RIGHT_SQUARE_BRACKET ); addTranslation( "(" , LEFT_PARENTHESIS ); addTranslation( ")" , RIGHT_PARENTHESIS ); addTranslation( "." , DOT ); addTranslation( ".." , DOT_DOT ); addTranslation( "..." , DOT_DOT_DOT ); addTranslation( "->" , NAVIGATE ); addTranslation( "=~" , FIND_REGEX ); addTranslation( "==~" , MATCH_REGEX ); addTranslation( "~" , REGEX_PATTERN ); addTranslation( "=" , EQUAL ); addTranslation( "!=" , COMPARE_NOT_EQUAL ); addTranslation( "===" , COMPARE_IDENTICAL ); addTranslation( "!==" , COMPARE_NOT_IDENTICAL ); addTranslation( "==" , COMPARE_EQUAL ); addTranslation( "<" , COMPARE_LESS_THAN ); addTranslation( "<=" , COMPARE_LESS_THAN_EQUAL ); addTranslation( ">" , COMPARE_GREATER_THAN ); addTranslation( ">=" , COMPARE_GREATER_THAN_EQUAL ); addTranslation( "<=>" , COMPARE_TO ); addTranslation( "!" , NOT ); addTranslation( "||" , LOGICAL_OR ); addTranslation( "&&" , LOGICAL_AND ); addTranslation( "||=" , LOGICAL_OR_EQUAL ); addTranslation( "&&=" , LOGICAL_AND_EQUAL ); addTranslation( "+" , PLUS ); addTranslation( "-" , MINUS ); addTranslation( "*" , MULTIPLY ); addTranslation( "/" , DIVIDE ); addTranslation( "\\" , INTDIV ); addTranslation( "%" , MOD ); addTranslation( "**" , POWER ); addTranslation( "+=" , PLUS_EQUAL ); addTranslation( "-=" , MINUS_EQUAL ); addTranslation( "*=" , MULTIPLY_EQUAL ); addTranslation( "/=" , DIVIDE_EQUAL ); addTranslation( "\\=" , INTDIV_EQUAL ); addTranslation( "%=" , MOD_EQUAL ); addTranslation( "**=" , POWER_EQUAL ); addTranslation( "++" , PLUS_PLUS ); addTranslation( "--" , MINUS_MINUS ); addTranslation( "<<" , LEFT_SHIFT ); addTranslation( ">>" , RIGHT_SHIFT ); addTranslation( ">>>" , RIGHT_SHIFT_UNSIGNED ); addTranslation( "<<=" , LEFT_SHIFT_EQUAL ); addTranslation( ">>=" , RIGHT_SHIFT_EQUAL ); addTranslation( ">>>=" , RIGHT_SHIFT_UNSIGNED_EQUAL ); addTranslation( "&" , BITWISE_AND ); addTranslation( "^" , BITWISE_XOR ); addTranslation( "|=" , BITWISE_OR_EQUAL ); addTranslation( "&=" , BITWISE_AND_EQUAL ); addTranslation( "^=" , BITWISE_XOR_EQUAL ); addTranslation( "," , COMMA ); addTranslation( ":" , COLON ); addTranslation( ";" , SEMICOLON ); addTranslation( "?" , QUESTION ); addTranslation( "|" , PIPE ); addTranslation( "${}" , GSTRING_EXPRESSION_START ); // // Keywords addKeyword( "abstract" , KEYWORD_ABSTRACT ); addKeyword( "as" , KEYWORD_AS ); addKeyword( "assert" , KEYWORD_ASSERT ); addKeyword( "break" , KEYWORD_BREAK ); addKeyword( "case" , KEYWORD_CASE ); addKeyword( "catch" , KEYWORD_CATCH ); addKeyword( "class" , KEYWORD_CLASS ); addKeyword( "const" , KEYWORD_CONST ); addKeyword( "continue" , KEYWORD_CONTINUE ); addKeyword( "def" , KEYWORD_DEF ); addKeyword( "defmacro" , KEYWORD_DEF ); // xxx br defmacro addKeyword( "default" , KEYWORD_DEFAULT ); addKeyword( "do" , KEYWORD_DO ); addKeyword( "else" , KEYWORD_ELSE ); addKeyword( "extends" , KEYWORD_EXTENDS ); addKeyword( "final" , KEYWORD_FINAL ); addKeyword( "finally" , KEYWORD_FINALLY ); addKeyword( "for" , KEYWORD_FOR ); addKeyword( "goto" , KEYWORD_GOTO ); addKeyword( "if" , KEYWORD_IF ); addKeyword( "in" , KEYWORD_IN ); addKeyword( "implements" , KEYWORD_IMPLEMENTS ); addKeyword( "import" , KEYWORD_IMPORT ); addKeyword( "instanceof" , KEYWORD_INSTANCEOF ); addKeyword( "interface" , KEYWORD_INTERFACE ); addKeyword( "mixin" , KEYWORD_MIXIN ); addKeyword( "native" , KEYWORD_NATIVE ); addKeyword( "new" , KEYWORD_NEW ); addKeyword( "package" , KEYWORD_PACKAGE ); addKeyword( "private" , KEYWORD_PRIVATE ); addKeyword( "property" , KEYWORD_PROPERTY ); addKeyword( "protected" , KEYWORD_PROTECTED ); addKeyword( "public" , KEYWORD_PUBLIC ); addKeyword( "return" , KEYWORD_RETURN ); addKeyword( "static" , KEYWORD_STATIC ); addKeyword( "super" , KEYWORD_SUPER ); addKeyword( "switch" , KEYWORD_SWITCH ); addKeyword( "synchronized", KEYWORD_SYNCHRONIZED ); addKeyword( "this" , KEYWORD_THIS ); addKeyword( "throw" , KEYWORD_THROW ); addKeyword( "throws" , KEYWORD_THROWS ); addKeyword( "transient" , KEYWORD_TRANSIENT ); addKeyword( "try" , KEYWORD_TRY ); addKeyword( "volatile" , KEYWORD_VOLATILE ); addKeyword( "while" , KEYWORD_WHILE ); addKeyword( "true" , KEYWORD_TRUE ); addKeyword( "false" , KEYWORD_FALSE ); addKeyword( "null" , KEYWORD_NULL ); addKeyword( "void" , KEYWORD_VOID ); addKeyword( "boolean" , KEYWORD_BOOLEAN ); addKeyword( "byte" , KEYWORD_BYTE ); addKeyword( "int" , KEYWORD_INT ); addKeyword( "short" , KEYWORD_SHORT ); addKeyword( "long" , KEYWORD_LONG ); addKeyword( "float" , KEYWORD_FLOAT ); addKeyword( "double" , KEYWORD_DOUBLE ); addKeyword( "char" , KEYWORD_CHAR ); } //--------------------------------------------------------------------------- // DESCRIPTIONS private static final Map DESCRIPTIONS = new HashMap(); /** * Gets the description for the specified type. */ public static String getDescription( int type ) { if (DESCRIPTIONS.containsKey(type)) { return DESCRIPTIONS.get(type); } return "<>"; } /** * Adds a description to the set. */ private static void addDescription(int type, String description) { if (description.startsWith("<") && description.endsWith(">")) { DESCRIPTIONS.put(type, description); } else { DESCRIPTIONS.put(type, '"' + description + '"'); } } static { Iterator iterator = LOOKUP.keySet().iterator(); while( iterator.hasNext() ) { String text = iterator.next(); int key = LOOKUP.get(text); addDescription( key, text ); } addDescription( NEWLINE , "" ); addDescription( PREFIX_PLUS_PLUS , "" ); addDescription( POSTFIX_PLUS_PLUS , "" ); addDescription( PREFIX_MINUS_MINUS , "" ); addDescription( POSTFIX_MINUS_MINUS , "" ); addDescription( PREFIX_PLUS , "" ); addDescription( PREFIX_MINUS , "" ); addDescription( STRING , "" ); addDescription( IDENTIFIER , "" ); addDescription( INTEGER_NUMBER , "" ); addDescription( DECIMAL_NUMBER , "" ); addDescription( SYNTH_COMPILATION_UNIT , "" ); addDescription( SYNTH_CLASS , "" ); addDescription( SYNTH_INTERFACE , "" ); addDescription( SYNTH_MIXIN , "" ); addDescription( SYNTH_METHOD , "" ); addDescription( SYNTH_METHOD_CALL , "" ); addDescription( SYNTH_PROPERTY , "" ); addDescription( SYNTH_PARAMETER_DECLARATION , "" ); addDescription( SYNTH_LIST , "" ); addDescription( SYNTH_MAP , "" ); addDescription( SYNTH_TUPLE , "" ); addDescription( SYNTH_GSTRING , "" ); addDescription( SYNTH_CAST , "" ); addDescription( SYNTH_BLOCK , "" ); addDescription( SYNTH_CLOSURE , "" ); addDescription( SYNTH_TERNARY , "" ); addDescription( SYNTH_LABEL , "